Learn Python from Scratch 2023: Module 2
Module 2: Basic Programming Concepts
2.1 Variables and data types:
Variables and Data Types In Python, a variable is a container for storing data. There are different data types in Python, including:
- Integer: whole numbers, such as 1, 2, 3
- Float: decimal numbers, such as 3.14, 2.5
- String: text, such as “Hello, World!”
- Boolean: True or False
Here’s an example of creating a variable:
# Integer variable
age = 25
# Float variable
price = 2.99
# String variable
name = "John"
# Boolean variable
is_student = True
2.2: Operators:
Operators are symbols that perform operations on variables and values. There are different types of operators in Python, including:
- Arithmetic operators: +, -, *, /, % (modulus), ** (exponentiation)
- Assignment operators: =, +=, -=, *=, /=, %=
- Comparison operators: == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to)
- Logical operators: and, or, not
Here’s an example of using operators:
# Arithmetic operators
a = 10
b = 5
c = a + b # c = 15
d = a / b # d = 2.0
e = a % b # e = 0
# Assignment operators
f = 1
f += 2 # f = 3
f *= 2 # f = 6
# Comparison operators
g = 5
h = 10
print(g == h) # False
print(g < h) # True
# Logical operators
i = True
j = False
print(i and j) # False
print(i or j) # True
print(not i) # False
2.3 Control flow (if-else, loops):
Control Flow Control flow refers to the order in which the code is executed. There are different control flow statements in Python, including:
- If statement: executes a block of code if a condition is true
- Else statement: executes a block of code if the condition in the if statement is false
- Elif statement: executes a block of code if the condition in the if statement is false, but another condition is true
- For loop: executes a block of code for each item in a sequence
- While loop: executes a block of code as long as a condition is true
Here’s an example of using control flow statements:
# If statement
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
# Elif statement
y = 3
if y > 5:
print("y is greater than 5")
elif y == 5:
print("y is equal to 5")
else:
print("y is less than 5")
# For loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# While loop
i = 1
while i < 6:
print(i)
i += 1
That’s it for Module 2! By following these steps, you should now have a solid understanding of variables, data types,