Keyboard Input
So far we have used the print() function to display information to the user. To get keyboard input from the user we use another function called input(). A function is a piece of prewritten code that performs an operation and often returns a value back to the program. Normally the value that is returned is assigned to a variable so that it can be used later in the program.
The input() function always returns whatever the user types as a string value. The general format is:
where prompt is an optional string that tells the user what input is expected, and variable is the name of some variable that will reference the string value read from the keyboard. For example:
1 2 |
ageString = input("Enter Your Age: ") # input() always returns a 'string' value print("You are", ageString, "years old.") |
Be careful if you need to use the value read from the user as an integer or float value instead. For example, the following line will crash because Python cannot add a string and an integer:
1 |
print("In 2 years you will be", ageString + 2, "years old!") # ERROR! |
To solve this problem you must convert the string to an integer (using a function called int()), like so:
1 2 |
ageInt = int(ageString) print("In 2 years you will be", ageInt + 2, "years old!") |
There is also a function called float() that will convert a string to a float value if needed.
Performing Calculations
Python supports seven mathematical operators, which are symbols used to perform calculations:
In math class, when you have a mathematical expression involving more than one operator, you know that there are special precedence (or “order of operations”) rules that must be followed — remember BEDMAS? The same rules of precedence apply to Python. In other words, ** has the highest precedence and is always done first, then *, /, //, and % (from left to right in the order they appear), and finally + and – (from left to right in the order they appear). The result of a mathematical expression is almost always assigned to a variable. For example:
1 2 |
answer = 12 + 3 ** 2 / 10 # answer = 12.9 # (exp first, next div, finally add) |
You may also group parts of a mathematical expression using parentheses ( and ) to force some operations to be performed before others.
Special Notes About Division
You may have noticed that there are 3 mathematical operators related to division: /, //, and %.
The / operator divides one number by another and always produces a float result, even if the factional part is .0
1 2 3 |
print(3 / 4) # displays 0.75 print(4 / 2) # displays 2.0 print(5.5 / 1.1) # displays 5.0 |
The / and % operators are related to long-division — remember that from Grade 4? The // operator gives the integer quotient of a division, and the % operator gives the integer remainder.
1 2 |
print(7 // 2) # displays 3 print(7 % 2) # displays 1 |
However, be aware that if one or both of the operands (the values on the right and left of the // or % operators) are float values, then the result will also be a float value ending with .0 (not an integer).
1 2 3 |
print(7.0 // 2) # displays 3.0 print(7 % 2.0) # displays 1.0 print(7.0 // 2.0) # displays 3.0 |
Advanced Output
To finish off today, let’s look at some handy features related to Python’s print() function.
Escape Characters
Most modern languages, including Python and Java, support escape characters within strings. An escape character is a character preceded with a backslash ( \ ). When the string is printed, escape characters are treated as special formatting information. These are the basic escape characters supported by Python:
Here’s an example:
1 |
print("Vik\nTwenty says \"You will get 90\\100\"\tI\'m hoping that he\'s right!") |
And the output:
Vik
Twenty says “You will get 90\100” I’m hoping that he’s right!
The ‘end=’ Parameter
By default, the print() function automatically appends a \n (newline) character to the end of the output string so that the cursor goes to the next line. To change this behaviour, you can include a special end= parameter to specify a different ending character, or none at all. For example, the following two statements:
1 2 |
print("Vik", end="") print("Twenty") |
will display on the same line, like this:
Vik Twenty
The end=”” tells Python to end the first output string without the default \n, thus the output of the second print() continues right after the first on the same line.
Rounding Float Values
Real (i.e., float) numbers are usually printed with up to 12 significant digits in Python, but it can be useful to be able to display such values rounded to a specific number of decimal places. To do this we can use another useful function called round():
myValue is 1.23456789
and rounded it’s 1.235
myValue is still 1.23456789
Note that the round() function returns a float value rounded to a specific number of decimal places, but it does not change the original first parameter; i.e., myValue is not changed by round().
To actually change myValue we could do this instead (note line 4):
1 2 3 4 5 |
myValue = 1.23456789 print("myValue is", myValue) myValue = round(myValue,2) print("myValue is now", myValue) |
String Concatenation
We have used the + operator to add numbers. A nice feature of Python is that + can also be used for string concatenation, which means it appends (or joins) one string to another, to create a whole new string. For example:
1 2 3 4 |
name = "VIK-20" winMessage = "The Top Scorer is " + name + "! Congratulations " + "and good luck!" print(winMessage) |
As you can see, the + operator behaves differently when it is working with numbers than strings. When the same operator can be used for more than one job, it’s called operator overloading.
Interestingly, the * operator has also been overloaded for use with strings:
1 |
print("Ho!" * 3) # displays: Ho!Ho!Ho! |
Data Type Conversions
Earlier we saw how the int() and float() functions can be used to convert a string value into a numeric type. These functions can also be used to convert integer values to float values and vice versa. For example:
1 2 3 4 5 6 7 |
a = 4.74 # a refers to a float value of 4.74 b = int(a) # b now refers to an int value of 4 print("a = ", a, " and b = ", b) c = 3 # c refers to an int value of 3 d = float(c) # d now refers to a float value of 3.0 print("c = ", c, " and d = ", d) |
Notice that the int() function truncates any fractional part of the float value 4.74 being converted. Truncate means that any fractional part of the result is actually thrown away (not rounded) to give an integer result. In this case, after line 2, variable b would reference the integer value 4, the .74 is thrown away.
Sometimes it can be handy to be able to convert an int or float value into a string. For example, this statement gives an error:
1 |
print("high score is " + 5) # ERROR! |
because it’s ambiguous to the Python interpreter how to add a string and an integer. To solve this problem we can use the str() function to convert the integer to a string like so:
1 |
print("high score is " + str(5)) # FIXED! |
Breaking Long Lines of Code
Finally, most programming statements are written on one line. Occasionally a line of code can become so long that you can’t see it all at once in your code editor, or it poorly wraps lines when you print your code. To solve this problem, you can break a statement into multiple lines by using the line continuation character, the backslash ( \ ).
1 2 3 |
print(playerScore1 + playerScore2 + playerScore3 + playerScore4 + \ playerScore5 + playerScore6 + \ playerScore7 + playerScore8) |
You Try!
-
- Add the heading “1-8 Input, Processing, Output (IPO)” to your learning journal and answer the following questions:
- When does the + sign concatenate rather than add?
- Why use the line continuation character if the Python Interpreter does not care how long a line is?
- Write a program (using the Mu editor) that requests the user to enter two numbers and prints the sum, product, difference and quotient of the two numbers.
- Predict the output of the following statements, then check using Python:
- Add the heading “1-8 Input, Processing, Output (IPO)” to your learning journal and answer the following questions:
-
-
- print( 6 + 3 * 5 − 1)
- print( 2 * -2 )
- print( 9 / 2 )
- print( 9 // 2 )
- print( 9 // 2.0 )
- print( 9 % 2 )
- print( 7 + 3 * 6 / 2 – 1 )
- print( (6 + 2) * 3 )
- print( 14 // (7 – 1) )
- print( 2 % 2 + 2 * 2 – 2 / 2 )
- print( ( 2 ** 3 * ( 4 + ( 5 * 6 / ( 10 ) ) ) ) )
- print( float(2) + int(3.6) )
-
-
- Write a program that converts Fahrenheit temperatures into Celsius. Your program should prompt the user to enter the temperature in Fahrenheit, and then display the temperature converted to Celsius, rounded to 1 decimal place. The formula is: C = (F – 32) x 5/9
Note: Be sure to use proper style: meaningful variable names, comments etc.
- Write a program that converts Fahrenheit temperatures into Celsius. Your program should prompt the user to enter the temperature in Fahrenheit, and then display the temperature converted to Celsius, rounded to 1 decimal place. The formula is: C = (F – 32) x 5/9