1.3 Input and Variables
The input() function is used to take user input. The following code snippet will prompt the user to enter their name, wait for the user to enter their name and press enter. The value that the user enters will be stored in the memory location called name.
name = input("Enter your name ")
Variable in Python
A variable is a named memory location, that stores a value, this value can change while the program is running. In the example above:
- the name of the variable is name
- the value that is stored is whatever the name the user enters
- The the user can choose to change the value that is stored in name later in the program
We can print the value that is stored in a variable, by including the name of the variable in the print statement. The following program prompts the user to enter their name, age and print them back to the screen.
name = input("What is your name: ")
age = input("What is your age: ")
print(name + " you are " + age + " years old !! ")
When variables are created in Python, we should also ensure that meaningful names are used so that one can remember what they represent. When creating variables, use words that describe the data that will be stored. Follow these rules when you create variables in Python:
- must begin with a letter of the alphabet or the underscore character
- cannot contain any space, therefore my name is not a valid variable name
- cannot be a reserved word (word with special meaning) in Python
Here are some examples of valid variable names in Python:
age
height
name
length_of_room
_item
position23
Here is a list of Python reserved words that you should avoid as variable names.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not