Computer Science · Ch 5 — Getting Started with Python
Input and Output
Input and Output
A program often needs to interact with its user — to collect some input data from the end user, process it, and present the desired output. Python provides two built-in functions for this: input() for reading data from the user, and print() for displaying data on the screen.
Taking input: the input() function
The input() function prompts the user to enter data and reads what they type. Its syntax is:
input([Prompt])
- Prompt is an optional string that is displayed on the screen before the input is taken — typically a message telling the user what to enter. When a prompt is given, it is shown first, and then the user types their data.
- Typing is terminated by pressing the Enter key.
input()takes exactly what was typed at the keyboard, converts it into a string, and assigns it to the variable on the left-hand side of the assignment operator=.
The crucial point: input() treats everything as a string. Even if the user types a number, the function returns it as string data.
>>> fname = input("Enter your first name: ")
Enter your first name: Arnab
>>> age = input("Enter your age: ")
Enter your age: 19
>>> type(age)
<class 'str'>
Here fname receives the string 'Arnab' — as expected. But age receives the string '19', not the number 19, which is why type(age) reports <class 'str'>.
Converting the input to a number
If we need to do arithmetic with the input, we must typecast it — change the data type of the accepted string to an appropriate numeric type. Wrapping the input() call in int() converts the string to an integer:
>>> age = int(input("Enter your age: "))
Enter your age: 19
>>> type(age)
<class 'int'>
Caution: if the user enters a non-numeric value (say nineteen), the conversion fails and an error is generated.
Producing output: the print() function
Python uses the print() function to send data to the standard output device — the screen. print() first evaluates the expression given to it and then displays the result. It outputs a complete line and then moves to the next line for subsequent output. Its syntax is:
print(value [, ..., sep = ' ', end = '\n'])
Two optional parameters control the formatting:
sep— the separator placed between the output values when several are printed. It can be any character, integer or string; the default separator is a space.end— a string appended after the last value. The default is a newline ('\n'), which is why eachprint()normally starts a fresh line.
print("Hello")
print(10 * 2.5)
print("I" + "love" + "my" + "country")
print("I'm", 16, "years old")
Output:
Hello
25.0
Ilovemycountry
I'm 16 years old
Joining with + versus separating with ,
The third and fourth statements above look similar but behave differently:
- The third uses
+to concatenate strings. Concatenation joins the pieces with no space added — henceIlovemycountry. …