Reading input is really important in programming. It means that we can interact with the computer program.
The input function returns a value which is a piece of string (text) data.
At a later point we will look at how to convert this string into a different type of data such as a number.
Below is a program that will print a message and then ask for the user to enter their name.
Make a Python script and test this code.
print("Welcome!") first_name = input("Please enter your first name: ") print("Hello", first_name)
If you were to run this program you would get the following output if you entered the name Lenny
Welcome Please enter your first name: Lenny Hello Lenny
Try running the program and seeing what happens if you enter no name
Note that if we write a program to read in a number it reads it as a string. We need to cast (convert) it to a number.
The example below casts the value to an int (integer / whole number). If we enter anything that isn’t a whole number the program will crash.
age = input("Enter your age: ") age = int(age) future_age = age + 5 print("You will be", future_age, "in five years time!")
This will result in the output below if given the input age of 8
Enter your age: 8 You will be 13 in five years time!
If we give the input eight we will get the following error as the program cannot convert text to an int
Enter your age: eight Exception has occurred: ValueError invalid literal for int() with base 10: 'eight' File "C:\Users\andre\Github\python-exercises-all\1_introduction\scratch.py", line 2, in <module> age = int(age)
We get a similar error if we input a decimal value
Enter your age: 8.5 Exception has occurred: ValueError invalid literal for int() with base 10: '8.5' File "C:\Users\andre\Github\python-exercises-all\1_introduction\scratch.py", line 2, in <module> age = int(age)
Note that we can use these error messages to help with debugging our code as it tells us the line that we had a problem on. In this case line 2. Note that it is not always this line that has caused the problem but it gives us a good starting point.