1. Variables#
One of the main concepts in programming are variables. In Python, a variable is a symbolic name that represents a value stored in memory. It allows you to store and manipulate data, making your code more flexible and reusable. Variables can hold different types of data, such as numbers, strings, lists, and more, and you can change their values throughout your program’s execution.
1.1. Creating and assigning a value to a variable#
Here is a simple example of creating and assigning value to a variable. In the code below, the numeric value of 5 is assigned (or bound) to variable x
using =
. To execute this line of code, also called a statement, you should first click on the code block and run it using the play button or “shift”+“enter”. The first line of code doesn’t show you anything as output, but to print this value you can use the print()
command. Also note that Python is case-sensitive; this means x
will be considered a different variable than X
.
Note that a command refers to an instruction or action that you give to the computer to perform a specific task. Commands are the building blocks of your Python programs, allowing you to create functionality and automation.
x = 5 # assigning value 5 to variable x
print(x)
5
Note that the text after hash sign #
is considered as comment (or note) by the computer and not executable code, so it will be ignored. It is only added to increase the readability of your code for you and others. Make sure to add comments to your code as you are writing it.
1.1.1. Variable Names#
In Python, variable names can contain both letters and numbers, but they can’t begin with a number. It is conventional to use only lowercase for variable names. The underscore character, _, can be used in names with multiple words: your_name
or airspeed_of_unladen_swallow
.
Note that there are some keywords in Python that the interpreter uses to recognize the structure of the program, and they cannot be used as variable names. If you give a variable an illegal name, you get a syntax error. This applies to the following keywords:
and |
as |
assert |
async |
await |
break |
class |
continue |
def |
del |
elif |
else |
except |
False |
finally |
for |
from |
global |
if |
import |
in |
is |
lambda |
None |
nonlocal |
not |
or |
pass |
raise |
return |
True |
try |
while |
with |
yield |
1.2. Basic data types in Python#
In Python, a data type defines the kind of value a variable can hold, such as numbers, text, lists, or more complex structures. It helps Python understand how to handle and manipulate the data correctly and efficiently. There are four basic data types that you should know:
int: integer numerical values with no decimal point.
float: floating points for real numbers with decimal point.
bool: boolean True or False values.
str: string, text values composed of a sequence of characters.
Below you can see how you can create variables and assign different types of data to them. If needed, you can check the type of a variable using the type()
command.
# Basic data types in python
# integer
x = 4
print(x)
type(x)
4
int
# float
y = 2.5
type(y)
float
# boolean
t = True
f = False
type(t)
bool
# string
message = "hello, There" # you can use " " or ' ', it doesn't matter
type(message)
str
1.2.1. Exercise#
Write a Python program with one variable to store your name
and then print the value of the variable.
Step 1: Declare variable
Step 2: Print the result using the print() function
# your code here
1.3. Declaring or changing the type of a variable#
If necessary, we can change the type of a variable to another one using the commands: int()
, float()
, and str()
. See some examples below:
v = float(2.5) # v is float
print(v, type(v))
2.5 <class 'float'>
# from float to integer
v = int(v)
print(v, type(v))
2 <class 'int'>
# from float to string
v = str(v) # v is not a number anymore but string
print(v, type(v))
2 <class 'str'>
Later you’ll see more examples of how you can convert the type of variable. One common example is to convert numbers read from a text file (str) to numbers (int or float) to perform arithmetic operations on them.
1.4. Reassign values#
You can reassign a new value to an old variable. By doing so, Python ignores the old value and replaces it with the new value. Below is an example.
m = 3 # first assignment
m = 6 # re-assignment
print(m)
6
Here is a simple example where we convert a fraction (4 out of 10, written as a decimal) to a percentage and reassign it to the same value.
completed_steps = 0.4 # first assignment
completed_steps = completed_steps*100 # re-assignment
print(completed_steps)
40.0
1.4.1. Exercise#
Write a Python program that: assigns value 2.8 to the variable num
, prints its type and then changes the type of num
to int
. Print the variable num
’s type and value again to make sure your code works properly.
Step 1: Declare variable
num
and assign the value 2.8 to itStep 2: Print the type of variable
num
Step 3: Change the type of variable
num
toint
Step 4: Print the type and value of the variable
num
again
# your code here
1.5. Print()
Function#
Here we take a break from variables and focus on the print()
function, as we will be using it very often to display text and variables. We will cover basic printing, string concatenation, and introducing some options to format the output.
Basic printing: Let’s start by printing a simple text (string) message
# printing simple text
print("Hello, world!")
# printing multiple lines
quote = """
Life is short,
and the world is wide.
"""
print(quote)
Hello, world!
Life is short,
and the world is wide.
Printing variables: You can also print the values of variables using the
print()
function. For printing multiple variables or texts you can use,
in between them (providing multiple inputs to the function).
name = "Alice"
age = 25
# printing single variables
print(age)
# printing multiple variables and text
print(f"My name is {name} and I am {age} years old.")
25
My name is Alice and I am 25 years old.
Formatting options: You may also see examples where F-strings orthe
.format()
method are used to provide a concise way to embed or insert variables within strings for printing. This can be done in two ways:
item = "book"
price = 19.9999
print(f"The {item} costs ${price}.")
print("The {} costs ${}.".format(item, price))
# for printing only 2 decimal points
print("The {} costs ${:.2f}.".format(item, price))
The book costs $19.9999.
The book costs $19.9999.
The book costs $20.00.
Note that we can also add .2f
to indicate that we want the float to have two decimals, as seen in the resulting output.
1.5.1. Exercise#
Declare a variable course
and assign it the name of a subject (e.g., “Math”).
Declare a variable duration and assign it an integer (e.g., 6).
Use both the input()
function with multiple input variables and the string formatting method using .format()
to print the following message, replacing [course] with the name of the course and [duration] with the duration:
Explore the world of [course] in just [duration] weeks!
# your code here