Intro to Python Programming with Mosh – Pt. 04

April 22, 2019

Intro to Python Programming

Tutorial – 04

Youtube – Learn Python 3 for Machine Learning & Web Development [2019]

By: Programming with Mosh
Progress

End Time: 1:41:55

Next Part of Tutorial: For Loops

NOTES

Weight Converter

This was a simple exercise to try and create a simple weight converter. It would take a user input weight and ask if it was in Kilograms or Pounds (lbs), then convert it to the other unit.

Their solution to this exercise provided a nice way to make strings less case sensitive. Since the unit input was just the first letter of the unit abbreviation (L for pounds and K for kilograms), this could make it completely non-case sensitive. You simply use the upper() method on the string you are comparing a value for before checking what it is. Then you only have to compare it to the capital case instance and either they will have already typed in the capital instance, or you will have converted the lower case to an upper case before comparing.

While Loops

These are used to execute blocks of code multiple times. The syntax for while loops is similar to C#. You just use the while key word with a condition, ending with a colon. Then the following indented code will be executed as long as the condition is met.

Guessing Game

This uses a while loop to build a simple guessing game.

This example went over “refactoring”, which is renaming a variable and all the instances of it in your code. This can be done with the keyboard shortcut: Shift + F6.

The Break command is used to immediately exit the program out of a while loop. This is useful when a varied condition is met that doesn’t need the loop to run again. This also prevents any Else counterparts of the while loop from executing.

While loops can also have Else counterparts. These will execute if the entire while loop is completed without the use of a Break.

Car Game

This was another exercise to do on your own. This time it was creating a “Car Game” that just said you started the car if you typed ‘start’ and stopped the car if you typed ‘stop’. I used a simple while loop to contain the game as a whole, with a game_started bool. The entire game ran in this while loop while game_started is true, and terminates when that is set to false. This gave me a way to quit the game when the user typed in quit.

Within the main game while loop, there were just a lot of if statements (with elif) to determine what to print based on what the player typed in. There was also an extra bool added which was car_started, which could be used to determine if the car was already started or stopped. This could be used to make sure the player couldn’t stop an already stopped car or start an already started one.