Variables

Here's code from a previous section that uses variables:
# Gets the user's name and greets them
my_name = "Jason"
user_name = input("Enter your name: ")
print(f"Hello {user_name}, nice to meet you. I am {my_name}.\n")

# Gets the user's age and compares
my_age = 31
user_age = input("Enter your age: ")
difference = my_age - int(user_age)
print(f"I am {difference} years older than you.")
On the first line, "Jason" is saved in a variable. A variable stores a value to be used later in the program. The value can have one of several different data types. Examples of data types are:
  • strings - words or sentences wrapped in quotes like "hello"
  • integers - whole numbers like 1 or -76
  • floats - decimal numbers like 1.5 or 0.006
To create a variable, give it a name, and set it equal to a value using the = operator. Variable names can contain only letters, numbers, and the underscore symbol, and the first character cannot be a number. So variable223 and new_value1 are valid variable names, but 1num and v@r are not. Variables should be all lowercase, and words should be separated by underscores. This is called snake case.
To inject a variable in a string, use an f-string. The line print(f"Hello {user_name}, nice to meet you. I am {my_name}.\n") in the code is an example of an f-string. Put the letter f in front of the quotes, and wrap variables in curly brackets.

Exercise 1 of 9

Which of these are all Python data types?

Exercise 2 of 9

What data type is the variable x?
x = "hello"

Exercise 3 of 9

What data type is the variable y?
y = -4.6

Exercise 4 of 9

What data type is the variable z?
z = 187

Exercise 5 of 9

Which of these is an acceptable variable name?

Exercise 6 of 9

Correct the mistake in the line of code.
my var = 12

Your code

Exercise 7 of 9

Which of these is NOT true about variable names?

Exercise 8 of 9

Write a line of code to print a sentence using the variable name.
name = "Jessica"

Your code

Exercise 9 of 9

Write a line of code to print a sentence using the variable age.
age = 12

Your code