In this lesson, you will learn about variables in Python, how to declare and assign them, their types, and good naming conventions. You will also create a higher or lower game using the Microbits Python editor.
Variables are used to store values in a program. They have a name and can store different types of data such as numbers, text, and more. In Python, you don't need to specify the type of data a variable will store, as it automatically detects the type based on the value you assign to it.
Let's take a look at some examples of declaring and assigning variables of different types:
age = 42
message = "Hello, World!"
isOpen = True
productPrice = 3.14
In this example, we have created four variables:
To declare and assign a variable in Python, you simply write the variable name followed by an equal sign and the value you want to store. For example:
my_variable = 10
This creates a variable named 'my_variable' and assigns it the value 10.
Python has several variable types, including:
Python automatically detects the variable type based on the value you assign to it. For example:
number_variable = 5
float_variable = 5.5
string_variable = 'Hello'
boolean_variable = True
Let's learn how to change variable values, including incrementing, decrementing, and string concatenation.
1. Incrementing a variable:
counter = 5
counter = counter + 1 # the value counter will now be 6
This increases the value of 'counter' by 1, making it 6.
2. Decrementing a variable:
counter = 5
counter = counter - 1 # the value counter will now be 4
This decreases the value of 'counter' by 1, making it 4.
3. String concatenation:
greeting = "Hello"
name = "John"
message = greeting + ", " + name # the message counter will now be 'Hello, John'
This combines the strings 'greeting' and 'name' with a comma and space, resulting in the message 'Hello, John'.