Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # lecture 10.10.2023, repetition statements, also known as: loops
- print("Welcome!")
- # NEW FILE
- # a simple for-loop: 10 cycles
- # basically: we ask Python to run this line of
- # code 10 times in a row
- for x in range(10):
- # this is the line we ask Python to run 10 times in a row
- print(x)
- # ANOTHER VERSION
- # a simple for-loop: 10 cycles
- # basically: we ask Python to run this line of
- # code 10 times in a row
- for x in range(10):
- # this is the line we ask Python to run 10 times in a row
- print(f"Number: {x}")
- # NEw FILE
- # usually we place the range limits
- # into variables
- start = 2017
- end = 2023
- # we can also define start and end
- # of the range
- for year in range(start, end):
- print(year)
- # ANOTHER VERSION
- # usually we place the range limits
- # into variables
- start = 2017
- end = 2023
- # we can also define start and end
- # of the range
- # third parameter is called step
- # if you use 2, the loop skips in increments of 2
- # instead of 1 (default step is 1)
- for year in range(start, end, 2):
- print(year)
- # NEW FILE
- # you can try this in Python Tutor also
- # to visualize the logic
- # create an empty text variable
- text = ""
- # the idea is build the text-variable
- # from pieces in a loop
- for year in range(2017, 2024):
- text = text + str(year) + "-"
- # let's remove the extra dash from the end
- # this substring means: take everything from
- # beginning until second last character
- text = text[:-1]
- print(text)
- # NEW FILE
- print("Start!")
- # a simple for + if/else
- # each cycle checks if the number is even or odd
- for x in range(10):
- if x % 2 == 0:
- print("Even!")
- else:
- print("Odd!")
- print("App ended.")
- # NEW FILE
- # counter variable, initialize to 1
- # can also be 0
- counter = 1
- # while-loop is similar to if-statement, it has a condition
- # so while the counter variable is less or equal to 10
- # => keep running this code
- while counter <= 10:
- print(counter)
- # always increment (add 1) to counter
- # in the end of each cycle
- # otherwise we get an infinite loop
- # because counter will always be under 10
- counter = counter + 1
- # NEW FILE
- # create a helper variable that keeps track
- # if our application should still be running
- running = True
- # our main loop, run the code as long as the user wants to
- while running:
- print("App is running!")
- # ask user a number for this cycle of app
- number = input("Give a number:\n")
- number = int(number)
- # double the number and print it out
- total = number * 2
- print(f"Number doubled: {total}")
- print()
- # ask user if they still want to continue with the app
- choice = input("Would you like to continue? (y/n)?\n")
- # if users inputs "n" => exit the app
- if choice.lower() == "n":
- running = False
- # this is run afterwards as the final code line
- # when the while loop above ends (user inputs "n")
- print("Thank you for using our application!")
- # NEW FILE
- # nesting loops
- print("Start!")
- for x in range(3):
- print(f"MAIN LOOP, x = {x}")
- # whatever is inside this main loop
- # is run 3 times (range(3))
- # including nested loops
- # so this loop is also run 3 times
- for y in range(5):
- print(f"\tNested for-loop: y = {y}")
- print("End app!")
- # A MORE PRACTICAL VERSION OF THE ABOVE
- print("Today's sales report:")
- # we could also have a more complex nesting
- # for example:
- # department -> order -> product
- # first, let's loop all our orders
- for order in range(3):
- print(f"Processing order: {order}")
- # each order has 5 products
- # => loop through all the products in
- # this cycle's product
- for product in range(5):
- print(f"\tProcessing order {order}, product {product}!")
- print("All ready.")
- # ANOTHER EXAMPLE
- print("Start app!")
- # 5 persons in line
- for person in range(5):
- # new person in turn
- print(f"Person {person + 1} turn!")
- # it's this person's turn to say numbers 1-4
- for number in range(4):
- print(f"Person {person + 1} says number: {number + 1}!")
- print()
- print("Everyone has spoken!")
- # NEW FILE
- print("Start!")
- for x in range(5):
- # if x == 3 => stop this for-loop
- # and continue after the for-loop
- if x == 3:
- break
- print(x)
- print("End.")
- # NEW FILE
- print("Start!")
- for x in range(5):
- # if x == 3 => skip this cycle
- # and continue where x = 4
- if x == 3:
- continue
- print(x)
- print("End.")
- # NEW FILE
- total = 0
- # ask user 10 times a number
- # add the number to the total -variable
- for x in range(10):
- number = int(input("Give number:\n"))
- total = total + number
- # what is the sum in them
- print(total)
- # NEW FILE
- # how many cycles we want to ask the number
- # any integer works, even random integers (as long as it's an integer)
- cycles = int(input("How many numbers to ask?\n"))
- total = 0
- # run the for-loop as many times as user wanted
- # and accumulate the total -variable
- for x in range(cycles):
- number = int(input("Give number:\n"))
- total = total + number
- print(total)
- # NEW FILE
- # interest calculator
- # compound interest, with loops instead of mathematical equation
- # yearly interest = 7%
- # add 2000€ in the beginning of each year
- start_money = 15000
- yearly_money = 2000
- # interest of 7%, use 1.07 for easier multiplication
- interest = 1.07
- # the goal is to find out the amount of new money after 10 years of saving
- total = start_money
- # use Python to calculate interest
- # for our money 10 years in a row
- for year in range(10):
- # in the beginning of each year, add 2000€ more
- total = total + yearly_money
- # calculate interest
- total = total * interest
- # total money in the end
- total = round(total, 2)
- print(f"Money after 10 years of saving: {total} €")
- # new money in the end => how much profit we had
- profit = total - start_money - (10 * yearly_money)
- print(f"After 10 years, our profit is = {profit} €")
- # NEW VERSION
- # VERSION 2: Interest calculator / compound interest
- # how many years does it take for us to reach a certain profit
- start_money = 15000
- yearly_money = 2000
- # what is our target savings
- target_profit = 150000
- # 7% interest per each year
- interest = 1.07
- # helper variables for the loop to keep track of current situation
- total = start_money
- current_profit = 0
- # for-loop for years 1-30
- for year in range(1, 31):
- # add the yearly money
- total = total + yearly_money
- # add interest
- total = total * interest
- # update how much profit we have earned so far
- current_profit = total - start_money - (year * yearly_money)
- # check if we have met our goal yet
- if current_profit >= target_profit:
- print(f"We met our goal in the year: {year}")
- # since we already know the year, no point continuing
- # the loop => break
- break
- # if we didn't get to the target profit
- # print an informing message for the user
- if current_profit < target_profit:
- print("This goal cannot be met within this time limit and starting investment.")
- # ANOTHER EXAMPLE, CLASSIC: FIBONACCI
- # Fibonacci sequence: every number is the sum of two previous numbers
- # first 9 numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21
- # OUR GOAL: ask user a number: which Fibonacci number do they
- # want to see, and count the value with a for-loop
- # examples:
- # if user inputs 5 = 1 + 2 = 3
- # if user inputs 6 = 2 + 3 = 5
- # if user inputs 7 = 3 + 5 = 8
- # if user inputs 8 = 5 + 8 = 13
- # x. number is old number + new number = fibonacci number
- # helper variables to keep track of old and new number
- old_number = 0
- new_number = 1
- # initialize fibonacci number to be 1 in the beginning
- fibonacci = 1
- choice = input("Which Fibonacci number would you like to see?\n")
- choice = int(choice) - 2
- print()
- # for-loop that counts the Fibonacci number
- # until the choice-variable dictates
- for number in range(choice):
- print("New cycle!")
- # calculate the current value
- fibonacci = old_number + new_number
- print(f"Fibonacci is now: {old_number} + {new_number} = {fibonacci}")
- # update the old number
- old_number = new_number
- # update the new number to be whatever fibonacci is now
- new_number = fibonacci
- print(f"After this cycle: old_number = {old_number}, new number = {new_number}")
- print()
- print()
- print(f"Fibonacci number = {fibonacci}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement