In this section, we're going to look more closely at variables. Here's
the code we were using in the previous section:
# 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")
Now let's look at the first line. Here, the word "Jason" is being saved
in a variable. A variable in Python stores a value to be used
later on in the program. The value can have one of several different
data types. Some examples of data types are:
-
strings: These are words or sentences wrapped in quotes like
"hello"
-
integers: These are whole numbers like
1
or
-76
-
floats: These are decimal numbers like
1.5
or
.006
To create a variable, simply give it a name and set it equal to a value
using =
. Variable names can only be made of 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 in Python should be written in snake case,
which means all the letters are lowercase, and spaces are replaced with
underscores.
Now, what if we want to use a variable inside a string? Say, for
example, we have a program that takes in the user's name in order to
greet them. To do that, we use an f-string. The line,
print(f"Hello {user_name}, nice to meet you. I am {my_name}\n")
in our code is an example of an f-string. We put the letter
f
in front of the quotes, and any variables we want to
include, we have to wrap in curly braces.