Lesson 4: Basic input and output
Output
One example of getting output from a Python program is by using the print() function to print a string, within quotes, to the screen.
print ("Hello TecKno!")
You can list more than one item within a single print statement by separating the items with commas.
count = 12 print("The current value of the counter is", count)
You can perform calculations within a print statement and output the result.
Formatting output
Use the backslash symbol (\) to escape, or ignore, a special character within the quotes of a string.
Try it!
Fix the following code example by using the backslash symbol where appropriate:
You can also use the backslash symbol to format text within strings:
- \n inserts a new line into the string.
- \t inserts a tab into the string.
Input
You can read user input into your program by using the input() function.
Used on its own, the input() function waits for input from the keyboard. After you press Enter, the input is read in.
Alternatively, you can pass a string to the input() function, which uses that string to prompt the user to enter text.
Try it!
Edit the example above to use a string with the input() function to prompt the user for input. The first print statement should no longer be needed.
Unless you tell it otherwise, Python assumes that any input you give it is a string. In our example, when it reads in your number, it treats that number like a string. This becomes apparent when we attempt to double the number. See what happens when you run it.
Why is it giving the incorrect answer?
Resources