Here are the most used control structures in Python, along with three examples of each:
- If-else statements – These are used to conditionally execute code based on the outcome of a logical expression.
# Example - Testing if X is positive
x = 5
if x > 0:
print("x is positive")
else:
print("x is non-positive")
# Example - Assigning letter grade based on test score
grade = 85
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("F")
# Example - Assigning a outcome based on a boolean condition
is_raining = True
if is_raining:
print("Take an umbrella with you")
else:
print("It's not raining, enjoy your day!")
Loops – Loops are used to execute a block of code repeatedly until a certain condition is met. In Python, there are two types of loops: for loops and while loops.
# Example - Loop through a list, and print each item in the list
# (for loop)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Example - loop through values in range(x), and print each item in range
# (for loop)
for i in range(5):
print(i)
# Example - Printing the values from 0 - 4
# (while loop)
i = 0
while i < 5:
print(i)
i += 1
Functions – Functions are used to encapsulate a piece of code that can be reused throughout a program.
# Example - Returns the squared value of X
def square(x):
return x**2
print(square(3))
# Example - Returns the amount of income tax due based on income
def calculate_tax(income):
if income < 10000:
tax = 0
elif income < 50000:
tax = 0.1 * income
else:
tax = 0.2 * income
return tax
print(calculate_tax(25000))
# Example - Returns the number of permutations of n objects taken r at a
# time
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
The highly rated book to learn more about Python control structures for data science is “Python Crash Course” by Eric Matthes. It covers the basics of Python programming, including control structures, and includes practical examples and exercises that are relevant to data science. It’s a great resource for beginners who want to learn how to program in Python for data analysis.