8.1 User Input-Output (Modified)
8.1 User Input-Output (Modified)
8.1 User Input-Output (Modified)
Python allows for user input. That means we are able to ask the user for input. Python version
3.6 uses the input() method. Python version 2.7 uses the raw_input() method. The following
example asks for the username, and when you entered the username, it gets printed on the
screen.
Python provides two built-in functions to read a line of text from standard input, which by
default comes from the keyboard. These functions are −
raw_input
input
The raw_input Function: The raw_input([prompt]) function reads one line from standard input
and returns it as a string (removing the trailing newline).
This prompts you to enter any string and it would display same string on the screen. When I type
"Hello Python!", its output is like this −
Enter your input: Hello Python
Received input is : Hello Python
The input Function: The input([prompt]) function is equivalent to raw_input, except that it
assumes the input is a valid Python expression and returns the evaluated result to you.
This would produce the following result against the entered input −
You can add parameters inside the curly brackets to specify how to convert the value:
Multiple Values
If you want to use more values, just add more values to the format() method and add more
placeholders.
print(txt.format(price, itemno, count))
Example: quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Result: I want 3 pieces of item number 567 for 49.00 dollars.
Index Numbers
You can use index numbers (a number inside the curly brackets {0}) to be sure the values are
placed in the correct placeholders.
Example: quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Also, if you want to refer to the same value more than once, use the index number.
Example: age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
Named Indexes
You can also use named indexes by entering a name inside the curly brackets {carname} but
then you must use names when you pass the parameter values txt.format(carname = "Ford").