Fork/Clone Ch.03 Input/Output Jedi Training
Fork/Clone Ch.03 Input/Output Jedi Training
In the last chapter we just used the Python Console to quickly test lines of code. Now that we want to create entire programs we need to create and save an entire file and then run it. To create a new file click ⌘N and then select Python File.
Give your file a name. Let's call it Hello_World. All Python files will have a .py extension but you don't need to include that in the name. Add it to Git.
From the dawn of computer science languages the simplest and first program that coders learn to write is printing the words "Hello World" to the screen. It is interesting to see how many different computer languages there are. You can get an idea how complex a language is by how easy the "Hello World" program is. Here is a collection of "Hello World" programs in most every language.
The upper right window is your editor screen where you write your program code. Type in the following code:
print("Hello World!")
Click Cmd⇧R (Command-Shift-R) to run this program. You should see the output printed below in a new RUN window.
Hello World!
Tell your parents tonight that today you coded your very first computer program!!!! Feel free to tweak your code and print other things to the screen. You only need to enter ^⇧R the first time you run your code. After that there is a little green play arrow on the upper right.
Remember, the function for printing in Python is easy. Just use print. After the print command are a set of parentheses ( ). Inside these parentheses is what should be printed to the screen. Using parentheses to pass information to a function is standard practice in math, and computer languages. Math students learn to use parentheses evaluating an expression like sin(θ) which is called a function. Data passed to this function is inside the parentheses. What is different in our case is that the information being passed is text.
Try to predict the result of each line of code below. Enter each line at a time in the Python Console and record the results. Which one gave a Syntax Error and why?
>>>print("2+3")
>>>print(2+3)
>>>print(Hello World)
Try to predict the result of each line of code below. Enter each line at a time in the Python Console and record the results. Which one gave a Syntax Error and why?
>>>print("Your new score is", 1030+10)
>>>print("Your new score is", "1030+10")
>>>print("Your new score is," 1030+10)
>>>print("Your new score is,", 1030+10)
If quotes are used to tell the computer the start and end of the string of text you wish to print, how does a program print out a set of double quotes? For example:
>>>print("I want to print a double quote " for some reason.")
This code doesn't work. The computer looks at the quote in the middle of the string and thinks that is the end of the text. Then it has no idea what to do with the commands for some reason and the quote at the end of the string confuses the computer even further.
It is necessary to tell the computer that we want to treat that middle double quote as text, not as a quote ending the string. This is easy, just prepend a backslash in front of quotes to tell the computer it is part of a string, not a character that terminates a string. For example:
>>>print("I want to print a double quote \" for some reason.")
This combination of the two characters \" is called an escape code. Almost every language has them. Because the backslash is used as part of an escape code, the backslash itself must be escaped. For example, this code does not work correctly:
>>>print("The file is stored in C:\new folder")
Why? Because \n is an escape code. To print the backslash it is necessary to escape it like so:
>>>print("The file is stored in C:\\new folder")
There are a few other important escape codes to know. Here is a table of the important escape codes:
What is a "Carriage Return" and a "Linefeed"? Try printing some text strings with \r and \n escape codes at various places in the text and record what happens.
There are some pretty cool escape codes that allow you to change the color and style of the printed python text. This can definitely make your text-based python programs cooler. I will leave that learning up to you: Printing Escape Codes
By default, the print statement puts a carriage return at the end of what is printed out. The carriage return is a character that moves the next line of output to be printed to the next line. Most of the time this is what we want. Sometimes it isn't. If we want to continue printing on the same line, we can change the default character printed at the end. The code below is an example before we change the ending character. Copy into the editor and then run the code.
print("May the FORCE")
print("be with you!")
May the FORCE
be with you!
If we wanted the code output to print on the same line, it can be done by using a new option to set the end character. A space between the double quotes will put a space between the two print statements. Here are a couple of examples:
print("May the FORCE", end=" ")
print("be with you!")
May the FORCE be with you!
Another Example:
i = 0
print(i, end=" ")
i = 1
print(i, end=" ")
0 1
Sometimes code needs some extra explanation to the person reading it. To do this, we add "comments" to the code. The comments are meant for the human reading the code, and not for the computer.
There are two ways to create a comment. The first is to use the # symbol. The computer will ignore any text in a Python program that occurs after the #. Therefore, you can temporarily disable a line of code simply by putting the # in front of it. Test the results of each of the following lines of code.
# This is a comment, it begins with a # sign
# and the computer will ignore it.
print("This is not a comment, the computer will")
print("run this and print it out.")
print("A # sign between quotes is not a comment.")
# print("This is a comment, even if it is code.")
print("Hi") # This is an end-of-line comment
It is possible to comment out multiple lines of code using three single quotes ''' in a row as seen in the example below.
Most professional Python programmers will only use this type of multi-line comment for something called docstrings. Docstrings allow documentation to be written along side the code and later be automatically pulled out into printed documentation, websites, and Integrated Development Environments (IDEs). For general comments, the # tag works best.
print("Hi")
'''
This is a multi-line comment.
Nothing will run in between these quotes.
print("There")
'''
print("Done")
SHORTCUT: The shortcut in PyCharm to comment out an entire section of code is ⌘/. You can un-comment a section of code by highlighting it and again using ⌘/.
Even if you are going to be the only one reading the code that you write, comments can help save time. Adding a comment that says "These are not the droids you are looking for" will allow you to quickly remember what that section of code does without having to read and decipher it. I cannot stress enough the importance of commenting your code!!!
⌘N for a new Python File, name it MPG_calculator.py and add it to Git. Copy the following script into the file and run it to see the output.
miles_driven = 294
gallons_used = 10.5
mpg = miles_driven / gallons_used
print(mpg)
28.0
This program would be even more useful if it would interact with the user and ask the user for the miles driven and gallons used. This can be done with the input statement. Now it's getting exciting! Modify your program to look like the following and run it. You will get a TypeError. What is the cause of the error?
# This code almost works
miles_driven = input("Enter miles driven:")
gallons_used = input("Enter gallons used:")
mpg = miles_driven / gallons_used
print("Miles per gallon:", mpg)
Enter miles driven:300
Enter gallons used:12
The reason for the error is that the computer will take the user input and assume it is a "string". To tell the computer these are numbers, it is necessary to surround the input function with an int( ) or a float( ). Use the former for integers, and the latter for floating point numbers. Let's modify and run the program again.
# This code should now work!
miles_driven = float(input("Enter miles driven:"))
gallons_used = float(input("Enter gallons used:"))
mpg = miles_driven / gallons_used
print("Miles per gallon:", mpg)
Enter miles driven:300
Enter gallons used:12
Miles per gallon: 25.0
In the real world, users don't always follow instructions perfectly. They might enter non-numeric values when asked for numbers, which can cause your program to crash. To handle these errors more gracefully, we can use a try-except block. This will allow our program to "catch" the error and prompt the user to correct their input, instead of crashing the program.
We can wrap the code that might fail in a try block, and if an error occurs, we handle it with an except block. Here's how it works: TRY IT!
try:
miles_driven = float(input("Enter miles driven:"))
gallons_used = float(input("Enter gallons used:"))
mpg = miles_driven / gallons_used
print("Miles per gallon:", mpg)
except ValueError:
print("You must enter numbers.")
Try Block: We put the input and calculation code inside a try block. Python will attempt to run this code.
Except Block: If the user enters something that can’t be converted to an integer or float, a ValueError will occur, and the program will jump to the except block. Instead of crashing, the program will print a friendly error message asking the user to input valid numbers.
The only problem with this program is that if the user doesn't put in numbers, it tells them that they must enter numbers but the program just ends. It needs to go back to the Try Block. We need to wrap this whole thing in a loop which we haven't talked about.
Here are some fairly common error types you might use in the except block:
ZeroDivisionError
What it is: The classic error that occurs when you attempt to divide a number by zero.
Example: result = 10 / 0
ValueError
What it is: This happens when a function receives an argument of the correct data type but an inappropriate value. It's very common when converting user input or dealing with domain-specific math functions.
Examples:
int("hello") (Trying to convert a non-numeric string to an integer).
math.sqrt(-1) (Trying to take the square root of a negative number).
TypeError
What it is: Occurs when you try to perform an operation on an object of the wrong data type. This is a very common error when variables are not what you expect.
Example: result = 5 + "apple" (You can't add a number and a string).
Also if you don't want to try to predict the error you could use this code instead. It will just print the error to the screen.
try:
miles_driven = float(input("Enter miles driven:"))
gallons_used = float(input("Enter gallons used:"))
mpg = miles_driven / gallons_used
print("Miles per gallon:", mpg)
except Exception as e:
print(e)
WHILE TRUE:
For now, we will wrap everything below in a while True:
Tab your entire try-except code over one TAB and put while True: before it. A while True: loop will go forever unless we add in a special word called break. We put the break word after the print statement so the program will only end once it's successfully printed the result of the program.
By using try-except, you make your program more robust, preventing crashes and providing helpful messages to users when they make mistakes.