In this part of the tutorial you will learn about variables.
A variable in Python points at a place in memory and is assigned to what is stored there. Think of it like a big whiteboard filled with information. A variable points at a specific place on the whiteboard and has the value it points at.
This variable can change value for two reasons.
- If the variable is pointed at a new value (a new place on the white board),
- or if the value is changed (someone writes something new at that place in the whiteboard).
Are you ready to try?
- Step 1 Print an assigned value by executing the program (hint: press play symbol)
- Step 2 Try to reassign the variable below the first statement.
- Step 3 Guess what happens before you press execute.
- Step 4 Try to add two variables together by using the new interpreter below.
- Step 5 Then change the first variable to be assigned to “10” (my_first_variable = “10”)
- Lesson: There are types to variables. In the example above you have.
- my_first_variable = “10” is a string (the quotes “” shows you that)
- my_second_variable = 20 is an integer
- Step 6: Change the first variable to 6.4 (my_first_variable = 6.4) and press run.
- Lesson: Now the first variable became a float (number with decimal) and the addition worked. That means that an integer and a float can be added together.
- Step 7: Assigning to new variables. See the code below and guess what it will print.
- Step 8: What happens if you change the assignment of c to c = a*b + 3?
- Lesson: While it does not seem as much, but that changed the type of c from a float to an integer. For now you should master the following three primitive types in Python.
- Integer (int): a = 10
- Float (float): b = 3.7
- String (str): c = “Hello”
- Lesson: If you add the following types you get.
- An integer added to an integer gives an integer (example a = 10 + 20)
- A float added to an integer gives a float (example: b = 3.4 + 10)
- A float added to a float gives a float (example: c = -4.8 + 1.9)
- An integer added to a string gives an error (example: d = 10 + “Hello”)
- A float added to a string gives an error (example: e = 1.9 + “World”)