User Input
Your programs can get information from the person using them.
In other words, you can ask the user to type something in.
When Python reaches the input() function it pauses, and it carries on only after the user has entered something.
The next example asks for a name and, once you type one, shows it on the screen:
Example
Asking the user for input:
Output: complete Python program
print("Enter your name:")
name = input()
print(f"Hello {name}")
Using prompt
Above, the name had to be typed on a new line. The input() function also takes a prompt parameter: a message shown just before the place where the user types, on the same line:
Example
Show a message in front of the input:
Output: complete Python program
name = input("Enter your name:")
print(f"Hello {name}")
Multiple Inputs
A program can ask for input as many times as you like. At each request, Python pauses until the user responds:
Example
Asking for several inputs:
Output: complete Python program
name = input("Enter your name:")
print(f"Hello {name}")
fav1 = input("What is your favorite animal:")
fav2 = input("What is your favorite color:")
fav3 = input("What is your favorite number:")
print(f"Do you want a {fav2} {fav1} with {fav3} legs?")
Input Number
Whatever the user types arrives as a string. That applies to numbers too, as with the favorite number in the example above: the interpreter still sees a string.
To get a real number, pass the input to the float() function:
Example
Calculating a square root needs a number, so the input is converted first:
Output: complete Python program
import math
x = input("Enter a number:")
#find the square root of the number:
y = math.sqrt(float(x))
print(f"The square root of {x} is {y}")
Validate Input
Checking what the user typed is good practice. In the example above, typing anything other than a number causes an error.
We can prevent that by testing the input first. When it isn't a number, the user can see a message such as "Wrong input, please try again" and get another chance:
Example
Repeat the question until the user enters a number:
Output: complete Python program
y = True
while y == True:
x = input("Enter a number:")
try:
x = float(x);
y = False
except:
print("Wrong input, please try again.")
print("Thank you!")