Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # lecture 6, repetition statements / loops
- print("Welcome!")
- # NEW FILE
- # a simple for-loop: 10 cycles
- # basically: we ask Python to run this
- # line of code 10 in a row
- # first cycle: x is 0
- # last cycle: x is 9
- for x in range(10):
- print(f"Cycle: {x}")
- # NEW FILE
- # save these to variable for
- # easier modification later
- start = 2018
- end = 2024
- # you can also define the start and end of the range
- # for example: a year range
- for year in range(start, end):
- print(year)
- # NEW FILE, version 2
- # save these to variable for
- # easier modification later
- start = 2018
- end = 2024
- # you can also define the start and end of the range
- # for example: a year range
- # you can also use the third parameter
- # if you wish to skip numbers in the for-loop
- # in this case: only print every other number
- for year in range(start, end, 2):
- print(year)
- # NEW FILE
- print("Start!")
- # try this code in Python Tutor
- # in order to see the execution of the for -loop!
- for cycle in range(10):
- number = cycle * 2
- print(f"Number: {number}")
- print("End!")
- # NEW FILE
- # try this also in Python Tutor
- # initialize an empty string variable
- text = ""
- # the idea is to build the text-variable
- # from pieces in a loop
- for year in range(2018, 2025):
- text = text + str(year) + "-"
- # we can use a substring to remove the final dash from the end
- text = text[:-1]
- # print the text-variable AFTER
- # the loop has added all the years into it
- print(text)
- # NEW FILE
- print("Start!")
- # for loop for 10 cycles
- for x in range(10):
- if x % 2 == 0:
- print(f"Cycle: {x} (even)")
- else:
- print("SKIP! (odd number)")
- print("End!")
- # NEW FILE
- print("APPLICATION STARTED!")
- counter = 1
- # while-loop, in other words:
- # run this code AS LONG AS the counter variable
- # is less or equal to 10
- while counter <= 10:
- print(f"Cycle: {counter}")
- # you have to increase the counter yourself
- # or otherwise you might get an infinite loop
- counter = counter + 1
- # loop done, inform user
- print("THANK YOU FOR USING THE APPLICATION!")
- # NEW FILE
- # variable that controls
- # if the app should be running still
- running = True
- # in this situation we can't know the exact number
- # of cycles, so this is why while-loop is more natural
- # (when compared to for-loop)
- while running:
- print("Run application! Ask stuff from user, calculate something etc...")
- print()
- # here comes all the code that should be run
- # on each cycle (ask user inputs, make calculations etc.)
- 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()
- # FINAL PHASE: ask user whether they wish to continue
- answer = input("Would you like to continue? (y/n)\n")
- # if user wants to quit, they write "n"
- if answer.lower() == "n":
- running = False
- # thank the user and end application
- print("\nThank you for using the application! (end program)")
- # NEW FILE
- print("Start!\n")
- # MAIN LOOP -> Run this 3 times only
- for x in range(3):
- print(f"MAIN LOOP: x = {x}")
- for y in range(5):
- print(f"\t\tnested loop: y = {y}")
- print("\nEND APPLICATION!")
- # NEW FILE
- # A MORE PRACTICAL VERSION OF NESTED LOOPS
- print("Today's sales report:\n")
- # our logic is this =>
- # we have orders, each order has certain amount of products
- # so, orders => products
- # we could have more complex stuff as well,
- # e.g. department => order => product
- # first, let's loop the orders (main loop)
- for order in range(3):
- print(f"Start processing order no.: {order + 1}")
- # process each product in this order
- # here we assume each order has exactly 5 products
- for product in range(5):
- print(f"\t\tProcessing order no: {order + 1}, product: {product + 1}")
- print("\nEnd of today's report (all orders processed).")
- # NEW FILE
- # use loops to do automated parts of code
- total = 0
- # use loops to automate
- # repeating structures in code
- for x in range(10):
- number = int(input("Give number:\n"))
- total = total + number
- print("Total sum of the numbers:")
- print(total)
- # NEW FILE
- # let's allow the user to choose the amount
- # of cycles in the for loop later
- cycles = input("How many numbers would you like to give?\n")
- cycles = int(cycles)
- # use loops to do automated parts of code
- total = 0
- # use loops to automate
- # repeating structures in code
- # using cycles from user to determine the
- # amount of cycles
- for x in range(cycles):
- number = int(input("Give number:\n"))
- total = total + number
- print("Total sum of the numbers:")
- print(total)
- # NEW FILE
- # interest calculator, loop version
- # compound interest with loops instead of mathematics
- # yearly interest is 7%
- # add 2000 €in the beginning of each year
- start_money = 15000
- yearly_money = 2000
- # interest in modifier format 1 + 0.07
- interest = 1.07
- # our money in the start
- total = start_money
- # the goal is to find new money after 10 years
- # use Python to calculate the interest for our money
- # for 10 years in a row
- for year in range(10):
- total = total + yearly_money
- total = total * interest
- # finalize the calculations
- total = round(total, 2)
- # remove the inital investment plus the yearly investments
- new_money = total - start_money - 10 * yearly_money
- print(f"Total money after 10 years: {total} €")
- print(f"New money accumulated: {new_money} €")
- # NEW FILE
- # 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.")
- # NEW FILE
- # 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