Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

4 IntroToPython-ControlFlowStatements

The document discusses control flow statements in Python, including if-else statements and loops. It provides examples of using if-else statements to perform operations conditionally based on simple comparisons and logical operators. It also demonstrates using while and for loops to iterate over items in a list, string, or range of numbers. Key points covered include using indentation properly with if-else statements in Python, breaking out of loops early, and nesting loops to iterate over multiple sequences.

Uploaded by

Hermine Koué
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

4 IntroToPython-ControlFlowStatements

The document discusses control flow statements in Python, including if-else statements and loops. It provides examples of using if-else statements to perform operations conditionally based on simple comparisons and logical operators. It also demonstrates using while and for loops to iterate over items in a list, string, or range of numbers. Key points covered include using indentation properly with if-else statements in Python, breaking out of loops early, and nesting loops to iterate over multiple sequences.

Uploaded by

Hermine Koué
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Financial Econometrics with Python

Introduction to Python
Control Flow Statements

Kevyn Stefanelli
2023-2024

4. Control flow statements


4.1 If-else statements
By using the 'if' statement, we perform operations only if a certain condition is true.

Additionally, we can include an 'else' statement if we want to execute an operation only when
the same condition is not satisfied.

Furthermore, we can add sequences of 'else if' (known as 'elif' in Python) statements in case we
want to specify different conditions and execute operations only when one of these conditions is
met.

4.1.1 if statement
# Define two variables
a = 4
b = 4

if b>a:
print("b is greater than a")
# it prints the string only if the condition is met!

Note on Indentation in Python:


In Python, indentation plays a crucial role in the execution of code, particularly when working
with conditional statements like 'if', 'else if' (known as 'elif' in Python), and 'else'. Unlike other
programming languages that use curly braces or keywords to delineate code blocks, Python
relies on proper indentation to define the scope of these blocks.

When using conditional statements, such as 'if', 'elif', and 'else', it is essential to maintain
consistent indentation. Each indented block under these statements represents a separate code
branch. Incorrect or inconsistent indentation can lead to syntax errors or unintended behavior.
4.1.2 else if (elif) statement
# re-define two variables
a= 3
b=3

if b>a:
print("b is greater than a")
elif a==b:
print("b is equal to a")

b is equal to a

4.1.3 if-else statement


# re-define two variables
a = 30
b = 2

if b>a:
print("b is greater than a")
elif a==b:
print("b is equal to a")
else:
print("b is lower than a")

b is lower than a

4.1.4 Using logical operators (and, or) within conditions


a = 30
b = 10
c = 5

# and
if a>b and c>a:
print("Great job!")

# or
if a>b or c>b:
print("The 'or' works fine!")

The 'or' works fine!

4.1.5 Nested if
Running a if statement into anothor if statement

# define a variable
x=15
if x>10:
print("x is greater than 10")
if x>20:
print("x is also greater than 20")
else:
print("x is greater than 10, but lower than 20")

x is greater than 10
x is greater than 10, but lower than 20

Take Home Exercises


Take Home Exercises

1. Your vending machine

Define a catalogue of four goods (e.g. “Coffee”, “Cappuccino”, “Tea”, and “Hot Water”) and
assign them the relative prices (e.g. 1, 1.50, 0.80, 0.05).

Using the conditional statements, write a function that given a string of character containing one
of the four goods returns its price. If the input is different from those four products the function
returns "Sorry, product not available.".

Try to order a Coffee, a Tea and a Ginseng. (Remember: Python is case sensitive: a ̸=A)

1. Saving when I do shopping

The following table contains a list of groceries which sell tomatoes, potatoes, zucchinis, and
eggplants along with their prices per kg.

I have to buy for my restaurant:

• 2 kg of tomatoes;
• 3 kg of potatoes;
• 5 kg of zucchinies;
• 4 kg of Eggplants.
Shops Tomatoes Potatoes Zucchinis Eggplants
TheLaughing 0.99 0.23 0.54 0.34
Tomato
PoorZucchini 0.98 0.28 0.50 0.34
BadApple 1.07 0.17 0.48 0.39
ToPearOrNot 0.93 0.22 0.57 0.33
ToPear

Where I should go shopping to save money?

Write a Python function that takes as input a dataframe called Grocery, which is a copy of the
table above, and returns a string containing the name of the cheapest grocery shop.
4.2 Loop
Loops are fundamental constructs in programming that enable the repetition of a set of
instructions multiple times.

Loops allow you to:

• iterate over collections of data;


• perform a specific action a certain number of times;
• execute code until a particular condition is met.

Python provides two main types of loops:

• for
• while

4.2.1 While loops


The while loop is a powerful programming construct in Python that enables the execution of a
block of code repeatedly as long as a specified condition remains true.

The while loop is particularly useful for situations where the exact number of iterations is not
known beforehand, allowing for flexible and responsive programming solutions.

However, careful consideration of the loop's termination condition is essential to avoid potential
infinite loops that can hang or crash a program.

# initialize a counter, not necessarily starting from 1


i = 1

while i < 6: # remember that 6 is excluded!


print("This is the iteration number", i)
i += 1

This is the iteration number 1


This is the iteration number 2
This is the iteration number 3
This is the iteration number 4
This is the iteration number 5

Note: if I don't increment the counter, the while loop never stops!

Combine loops and if-else


break statement
We can use the instruction 'break' to stop the loop if a certain condition is met.

# re-initialize the counter i


i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1 # pay attention to the indentation

1
2
3

Combining while and else


# re-initialize the counter i
i = 1

while i<6:
print(i)
i+=1
else:
print("now, i is not lower than 6")

1
2
3
4
5
now, i is not lower than 6

Example: The Number Guessing Challenge


Get ready for a thrilling challenge of numbers and strategy!

In this game, you and your friend will take turns guessing a secret number between 1 and 20.

If you guess the correct number, you'll be rewarded with a prize of 10.

But here's the twist: if your guess is off the mark, you'll need to pay a fee of 2.

Are you up for the challenge?

Let's see who can crack the code and come out on top! Use a while loop to keep the game going
until someone guesses the secret number.

import numpy as np
from numpy import random

# Generate the secret number between 1 and 20


secret_number = random.randint(1, 20)

# Initialize variables
player_score = 0
guesses = 0

# Start the guessing game


while True:
player_guess = int(input("Guess the secret number between 1 and
20: "))
guesses += 1

if player_guess == secret_number:
print("Congratulations! You guessed the secret number!")
player_score += 10
break
else:
print("Oops! That's not the right number. Try again.")
player_score -= 2

# Print the result


print(f"Number of guesses: {guesses}")
print(f"Your final score: {player_score}")

Guess the secret number between 1 and 20: 10


Oops! That's not the right number. Try again.
Guess the secret number between 1 and 20: 11
Oops! That's not the right number. Try again.
Guess the secret number between 1 and 20: 12
Congratulations! You guessed the secret number!
Number of guesses: 3
Your final score: 6

4.2.2 For loops


The 'for' loop is a fundamental element of Python programming that facilitates the iteration over
a sequence of items, such as lists, tuples, strings, or other iterable objects.

Unlike the 'while' loop, which operates based on a condition, the 'for' loop follows a
predetermined iteration pattern. It systematically moves through each item in the sequence,
executing a specified block of code for each item. This makes the 'for' loop an ideal choice when
you know the exact number of iterations required.

Python's 'for' loop simplifies the process of handling collections of data, performing repetitive
tasks efficiently, and applying the same operation to each element within the sequence.

Use the loop to iterate over the elements of a list (tuple)


The counter j runs from the first to the last element of the list (tuple)
# define a list
sports = ["soccer", "tennis", "swimming"]

# let j run over the list


for j in sports:
print(j)

soccer
tennis
swimming

Use the loop to iterate over a string


If we have a string of 6 letters, the operation will be executed six times

a = sports[-1] # 'a' is now equal to "swimming", so 8 letters

for k in a:
print(k)

s
w
i
m
m
i
n
g

# also:
for j in "fencing":
print(j)

f
e
n
c
i
n
g

Using break with for


for x in sports:
if x == "tennis":
break
print(x) # note: 'tennis' is excluded

soccer
Iterate with 'range'
# iterare con range:
for k in range(6): # it goes from 0 to 5
print(k)

0
1
2
3
4
5

# I can specify the starting and ending points.


for k in range(2,6):
print(k)

2
3
4
5

# and the step:


for k in range(3,22,6): # each 6
print(k)

3
9
15
21

Combining else and for loop


for t in range(10):
print("printed",t, "/9")
else:
print("The loop is concluded!")

printed 0 /9
printed 1 /9
printed 2 /9
printed 3 /9
printed 4 /9
printed 5 /9
printed 6 /9
printed 7 /9
printed 8 /9
printed 9 /9
The loop is concluded!
Nested for loops
# define two lists
locations = ["beach", "mountain", "countryside"]
accommodations = ["hotel", "residence", "campground", "B&B", "hostel"]

# run the loop over locations and over accomodations


for location in locations:
for accommodation in accommodations:
print(location, accommodation)

beach hotel
beach residence
beach campground
beach B&B
beach hostel
mountain hotel
mountain residence
mountain campground
mountain B&B
mountain hostel
countryside hotel
countryside residence
countryside campground
countryside B&B
countryside hostel

Note: there are more efficient techniques to execute if-else statements and loops. Those
methods won't be covered in this course to prioritize providing clear and understandable
material.

Example
Calculate the Sum of the First N Numbers

Write a program that asks the user to input a positive integer N. Then, using a for loop, calculate
the sum of the first N positive integers and print the result.

# Ask the user to input a positive integer


N = int(input("Enter a positive integer: "))

# Initialize the variable for the sum


sumfirst = 0

# Calculate the sum of the first N positive integers using a for loop
for number in range(1, N + 1):
sumfirst += number

# Print the result


print(f"The sum of the first {N} positive integers is {sumfirst}.")
Enter a positive integer: 6
The sum of the first 6 positive integers is 21.

Calculate Daily Calorie Intake

You want to track your daily calorie intake for a week.

You have a dictionary of meals and their total calorie counts for each day.

Write a program that calculates and displays your total daily calorie intake for each day of the
week.

# List of days in a week


days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday"]

# Dictionary of meals and their total calorie counts for each day
meals = {
"Monday": {"Breakfast": 300, "Lunch": 500, "Dinner": 600, "Snack":
150},
"Tuesday": {"Breakfast": 350, "Lunch": 550, "Dinner": 620,
"Snack": 130},
"Wednesday": {"Breakfast": 320, "Lunch": 480, "Dinner": 590,
"Snack": 170},
"Thursday": {"Breakfast": 290, "Lunch": 510, "Dinner": 580,
"Snack": 160},
"Friday": {"Breakfast": 280, "Lunch": 490, "Dinner": 610, "Snack":
140},
"Saturday": {"Breakfast": 330, "Lunch": 520, "Dinner": 560,
"Snack": 180},
"Sunday": {"Breakfast": 310, "Lunch": 540, "Dinner": 570, "Snack":
120}
}

# Calculate and display the daily calorie intake


for day in days:
daily_total_calories = 0
print(f"{day}:")
for meal, calories in meals[day].items():
daily_total_calories += calories
print(f" {meal}: {calories} calories")
print(f"Total Calories for {day}: {daily_total_calories} calories\
n")

Monday:
Breakfast: 300 calories
Lunch: 500 calories
Dinner: 600 calories
Snack: 150 calories
Total Calories for Monday: 1550 calories
Tuesday:
Breakfast: 350 calories
Lunch: 550 calories
Dinner: 620 calories
Snack: 130 calories
Total Calories for Tuesday: 1650 calories

Wednesday:
Breakfast: 320 calories
Lunch: 480 calories
Dinner: 590 calories
Snack: 170 calories
Total Calories for Wednesday: 1560 calories

Thursday:
Breakfast: 290 calories
Lunch: 510 calories
Dinner: 580 calories
Snack: 160 calories
Total Calories for Thursday: 1540 calories

Friday:
Breakfast: 280 calories
Lunch: 490 calories
Dinner: 610 calories
Snack: 140 calories
Total Calories for Friday: 1520 calories

Saturday:
Breakfast: 330 calories
Lunch: 520 calories
Dinner: 560 calories
Snack: 180 calories
Total Calories for Saturday: 1590 calories

Sunday:
Breakfast: 310 calories
Lunch: 540 calories
Dinner: 570 calories
Snack: 120 calories
Total Calories for Sunday: 1540 calories

You might also like