Learning Python is fun

Welcome to ‘learning python is fun - for beginners’

Previous: Running Python

Next: Strings

Python Variables

Lesson: 4 - Storing Data for Later Usage

In the previous lesson, we used Python like a calculator and explored various arithmetic operators.

Wouldn’t it be great if we could save and re-use our calculations results? For this purpose we will use Python variables. In this lesson you will learn what a variable is and how to declare it.

Variable definition

What the hell is a variable?

A variable is used to store information that can be referenced later.

We use variables to name the result of a calculation we made. In other words, we can assign the result of that calculation to a variable. We can create an unlimited number of variables; we just have to make sure we give them unique names.

  • x can be a variable of how long it takes you to drive to granny's
  • A more clear cut variable name for that would be drive_duration
  • cost can be a variable of how much it costs to visit a restaurant
  • students_names can be a variable of the names of all the students at your class

Variable declaration

Creating a python variable is super easy. let's check if your REPL has a variable called result:

>>> result
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'result' is not defined

This is the way Python lets you know about errors. Ignore the first two lines and focus on the actual error instead. Python reports: name 'result' is not defined.

Python errors tend to be very helpful if you know where to look. You’ll eventually need to write code on your own and you are going to run into errors. Being able to decipher error messages is a useful skill!

Now let’s declare the variable name result and try this again:

click to run python

Did you run these 2 lines of code?
What happened?

Python sees an assignment: we assign the result of 3 * 5 to the variable called result. Assignments are done with the = character. So we declared that result is the result of the expression 3 * 5.

Variable naming

In the previous example, we picked the general name result as our variable name, but you can choose any name you deem appropriate. Generally you should always pick a variable name that best describes its contents. This practice makes your code more readable and easy to understand.

If we were counting this sentence's total number of characters for example, a good name would be sentence_length.

click to run python

Variables & expressions

Remember how we did math with number? You can do just as well with Python variables too, it's a crucial part of programing to use variables with expressions:

>>> time_passed_in_seconds = 20
>>> 3 * time_passed_in_seconds
60
>>> time_passed_in_seconds - time_passed_in_seconds
0
>>> _

Expressions

An expression is basically anything that Python can evaluate to a value

These are all valid expressions because Python can evaluate them to a value:

click to run python

What you see above the expressions are called comments. Anything that follows a hash symbol (the #) is seen as a Python comment and is ignored by the Python interpreter.

Variable types

A value assigned to a variable does not have to be a number,
It can also be a string for example.

Python has several more data types, like booleans, tuples, lists and dictionaries; which can all be stored in variables.

Python has a built-in function called type(), which we can use to determine a variable or expression type.
Here are some examples:

  • create a variable called 'number' and pass it into the 'type' function
    >>> number = 4
    >>> type(number)
    <class 'int'>

    Python tells us this variable is of class int, which is short for integer

  • create a string and pass it into the 'type' function
    >>> string = 'super man'
    >>> type(string)
    <class 'str'>

    Python tells us this variable is of class str, which is short for string

Valid Variable Names

Some characters are not allowed in a variable name; there are a few rules we need to abide by.

valid characters

  • Lower & upper case letters: a-z and A-Z
  • Numbers: 0-9
  • Underscores: _

naming rules

  • Variable names must start with a letter or the underscore character and can not start with a number
  • Names are case-sensitive: name and Name are not the same

valid examples

  • name_1
  • name_2
  • _id

invalid examples

  • 1name
  • 2_name
  • 3-name
  • 4 name

If your coming from a programing language like C# or Java, your probably used to name variables in the camel-case format. With camel-case, we use uppercase letters to separate words clearly.

While we can use camel-case in Python, we usually prefer 'snake-case' where we use underscores to separate the words of the variable name. Camel-case is only used to name classes in python. So instead of fullName, we pythonists use full_name.

Proving your skills

I have gathered some basic challenges for you to go over.

These scripting tasks are perfect for beginners,
to practice variable naming and basic operations in Python.

Try to solve these and sweet sale in confidence onto the next lesson.

  1. Assign your first name to a variable and print it.
  2. Assign your last name to a variable and print it.
  3. Concatenate your first name and last name and print the result.
  4. Assign your age to a variable and print it.
  5. Create a variable for the current year and print it.
  6. Calculate and print the year you were born based on your age and the current year.
  7. Assign a temperature in Celsius to a variable and print it.
  8. Convert the temperature from Celsius to Fahrenheit and print the result.
  9. Assign the length of a rectangle to a variable and print it.
  10. Assign the width of the same rectangle to another variable and print it.
  11. Calculate and print the area of the rectangle using the length and width variables.
  12. Create a variable for the number of hours you sleep per day and print it.
  13. Create a variable for the number of hours you spend studying per day and print it.
  14. Calculate and print the total number of hours you are awake per day.
  15. Assign a number to a variable and print it.
  16. Double the value of the number using a new variable and print it.
  17. Assign a price to a variable and print it.
  18. Apply a 10% discount to the price using a new variable and print it.
  19. Assign the number of siblings you have to a variable and print it.
  20. Assign the number of cousins you have to another variable and print it.
  21. Calculate and print the total number of relatives you have (siblings + cousins).
  22. Assign a distance in kilometers to a variable and print it.
  23. Convert the distance from kilometers to miles and print the result.
  24. Assign your favorite color to a variable and print it.
  25. Assign your favorite food to another variable and print it.
  26. Combine your favorite color and food into a single sentence and print it.
  27. Assign a number to a variable and print it.
  28. Add 10 to the number using a new variable and print it.
  29. Subtract 5 from the number using another variable and print it.
  30. Divide the number by 2 using a new variable and print it.
click to run python

Lesson Completed 👏

Great job! 🍺🍺“🎉“🎉

We learned how to deal with numbers and how to store numbers in variables. But what about text? In the next lesson we will learn all about Python strings.

Previous: Running Python

Next: Strings