1. The print()
function sends data to the console, while the input()
function gets data from the console.
2. The input()
function comes with an optional parameter: the prompt string. It allows you to write a message before the user input, e.g.:
1 2 |
name = input("Enter your name: ") print("Hello, " + name + ". Nice to meet you!") |
3. When the input()
function is called, the program’s flow is stopped, the prompt symbol keeps blinking (it prompts the user to take action when the console is switched to input mode) until the user has entered an input and/or pressed the Enter key.
NOTE
The input()
function can be used to prompt the user to end a program. Look at the code below:
1 2 3 4 5 6 7 |
name = input("Enter your name: ") print("Hello, " + name + ". Nice to meet you!") print("\nPress Enter to end the program.") input() print("THE END.") |
input()
function is a string. You can add strings to each other using the concatenation (+
) operator. Check out this code:
1 2 3 4 |
num_1 = input("Enter the first number: ") # Enter 12 num_2 = input("Enter the second number: ") # Enter 21 print(num_1 + num_2) # the program returns 1221 |
5. You can also multiply (*
‒ replication) strings, e.g.:
1 2 |
my_input = input("Enter something: ") # Example input: hello print(my_input * 3) # Expected output: hellohellohello |
Type casting
Python offers two simple functions to specify a type of data and solve this problem – here they are:
1 |
int() |
and
1 |
float() |
Their names are self-commenting:
- the
int()
function takes one argument (e.g., a string:int(string)
) and tries to convert it into an integer; if it fails, the whole program will fail too (there is a workaround for this situation, but we’ll show you this a little later); - the
float()
function takes one argument (e.g., a string:float(string)
) and tries to convert it into a float (the rest is the same).
Type conversion: str()
This type of conversion is not a one-way street. You can also convert a number into a string, which is way easier and safer ‒ this kind of operation is always possible.
A function capable of doing that is called str()
:
1 |
str(number) |
Exercise 1
What is the output of the following snippet?
1 2 |
x = int(input("Enter a number: ")) # The user enters 2 print(x * "5") |
55
Exercise 2
What is the expected output of the following snippet?
1 2 |
x = input("Enter a number: ") # The user enters 2 print(type(x)) |
<class 'str'>