Advertisement
tuomasvaltanen

Untitled

Oct 20th, 2024 (edited)
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.98 KB | None | 0 0
  1. # lecture 6, repetition statements / loops
  2. print("Welcome!")
  3.  
  4. # NEW FILE
  5.  
  6. # a simple for-loop: 10 cycles
  7. # basically: we ask Python to run this
  8. # line of code 10 in a row
  9. # first cycle: x is 0
  10. # last cycle: x is 9
  11. for x in range(10):
  12.     print(f"Cycle: {x}")
  13.  
  14. # NEW FILE
  15.  
  16. # save these to variable for
  17. # easier modification later
  18. start = 2018
  19. end = 2024
  20.  
  21. # you can also define the start and end of the range
  22. # for example: a year range
  23. for year in range(start, end):
  24.     print(year)
  25.  
  26. # NEW FILE, version 2
  27.  
  28. # save these to variable for
  29. # easier modification later
  30. start = 2018
  31. end = 2024
  32.  
  33. # you can also define the start and end of the range
  34. # for example: a year range
  35. # you can also use the third parameter
  36. # if you wish to skip numbers in the for-loop
  37. # in this case: only print every other number
  38. for year in range(start, end, 2):
  39.     print(year)
  40.  
  41. # NEW FILE
  42. print("Start!")
  43.  
  44. # try this code in Python Tutor
  45. # in order to see the execution of the for -loop!
  46. for cycle in range(10):
  47.     number = cycle * 2
  48.     print(f"Number: {number}")
  49.  
  50. print("End!")
  51.  
  52. # NEW FILE
  53.  
  54. # try this also in Python Tutor
  55. # initialize an empty string variable
  56. text = ""
  57.  
  58. # the idea is to build the text-variable
  59. # from pieces in a loop
  60. for year in range(2018, 2025):
  61.     text = text + str(year) + "-"
  62.  
  63. # we can use a substring to remove the final dash from the end
  64. text = text[:-1]
  65.  
  66. # print the text-variable AFTER
  67. # the loop has added all the years into it
  68. print(text)
  69.  
  70. # NEW FILE
  71.  
  72. print("Start!")
  73.  
  74. # for loop for 10 cycles
  75. for x in range(10):
  76.     if x % 2 == 0:
  77.         print(f"Cycle: {x} (even)")
  78.     else:
  79.         print("SKIP! (odd number)")
  80.        
  81. print("End!")
  82.  
  83. # NEW FILE
  84.  
  85. print("APPLICATION STARTED!")
  86.  
  87. counter = 1
  88.  
  89. # while-loop, in other words:
  90. # run this code AS LONG AS the counter variable
  91. # is less or equal to 10
  92. while counter <= 10:
  93.     print(f"Cycle: {counter}")
  94.    
  95.     # you have to increase the counter yourself
  96.     # or otherwise you might get an infinite loop
  97.     counter = counter + 1
  98.  
  99. # loop done, inform user
  100. print("THANK YOU FOR USING THE APPLICATION!")
  101.  
  102. # NEW FILE
  103.  
  104. # variable that controls
  105. # if the app should be running still
  106. running = True
  107.  
  108. # in this situation we can't know the exact number
  109. # of cycles, so this is why while-loop is more natural
  110. # (when compared to for-loop)
  111. while running:
  112.     print("Run application! Ask stuff from user, calculate something etc...")
  113.     print()
  114.    
  115.     # here comes all the code that should be run
  116.     # on each cycle (ask user inputs, make calculations etc.)
  117.     number = input("Give a number:\n")
  118.     number = int(number)
  119.  
  120.     # double the number and print it out
  121.     total = number * 2
  122.     print(f"Number doubled: {total}")
  123.     print()
  124.  
  125.     # FINAL PHASE: ask user whether they wish to continue
  126.     answer = input("Would you like to continue? (y/n)\n")
  127.  
  128.     # if user wants to quit, they write "n"
  129.     if answer.lower() == "n":
  130.         running = False
  131.  
  132. # thank the user and end application
  133. print("\nThank you for using the application! (end program)")
  134.  
  135. # NEW FILE
  136. print("Start!\n")
  137.  
  138. # MAIN LOOP -> Run this 3 times only
  139. for x in range(3):
  140.     print(f"MAIN LOOP: x = {x}")
  141.  
  142.     for y in range(5):
  143.         print(f"\t\tnested loop: y = {y}")
  144.  
  145.  
  146. print("\nEND APPLICATION!")
  147.  
  148. # NEW FILE
  149.  
  150. # A MORE PRACTICAL VERSION OF NESTED LOOPS
  151. print("Today's sales report:\n")
  152.  
  153. # our logic is this =>
  154. # we have orders, each order has certain amount of products
  155.  
  156. # so, orders => products
  157. # we could have more complex stuff as well,
  158. # e.g. department => order => product
  159. # first, let's loop the orders (main loop)
  160. for order in range(3):
  161.     print(f"Start processing order no.: {order + 1}")
  162.  
  163.     # process each product in this order
  164.     # here we assume each order has exactly 5 products
  165.     for product in range(5):
  166.         print(f"\t\tProcessing order no: {order + 1}, product: {product + 1}")
  167.  
  168. print("\nEnd of today's report (all orders processed).")
  169.  
  170. # NEW FILE
  171.  
  172. # use loops to do automated parts of code
  173. total = 0
  174.  
  175. # use loops to automate
  176. # repeating structures in code
  177. for x in range(10):
  178.     number = int(input("Give number:\n"))
  179.     total = total + number
  180.  
  181. print("Total sum of the numbers:")
  182. print(total)
  183.  
  184. # NEW FILE
  185.  
  186. # let's allow the user to choose the amount
  187. # of cycles in the for loop later
  188. cycles = input("How many numbers would you like to give?\n")
  189. cycles = int(cycles)
  190.  
  191. # use loops to do automated parts of code
  192. total = 0
  193.  
  194. # use loops to automate
  195. # repeating structures in code
  196. # using cycles from user to determine the
  197. # amount of cycles
  198. for x in range(cycles):
  199.     number = int(input("Give number:\n"))
  200.     total = total + number
  201.  
  202. print("Total sum of the numbers:")
  203. print(total)
  204.  
  205. # NEW FILE
  206.  
  207. # interest calculator, loop version
  208.  
  209. # compound interest with loops instead of mathematics
  210. # yearly interest is 7%
  211. # add 2000 €in the beginning of each year
  212. start_money = 15000
  213. yearly_money = 2000
  214.  
  215. # interest in modifier format 1 + 0.07
  216. interest = 1.07
  217.  
  218. # our money in the start
  219. total = start_money
  220.  
  221. # the goal is to find new money after 10 years
  222.  
  223. # use Python to calculate the interest for our money
  224. # for 10 years in a row
  225. for year in range(10):
  226.     total = total + yearly_money
  227.     total = total * interest
  228.  
  229.  
  230. # finalize the calculations
  231. total = round(total, 2)
  232.  
  233. # remove the inital investment plus the yearly investments
  234. new_money = total - start_money - 10 * yearly_money
  235. print(f"Total money after 10 years: {total} €")
  236. print(f"New money accumulated: {new_money} €")
  237.  
  238. # NEW FILE
  239.  
  240. # VERSION 2: Interest calculator / compound interest
  241. # how many years does it take for us to reach a certain profit
  242.  
  243. start_money = 15000
  244. yearly_money = 2000
  245.  
  246. # what is our target savings
  247. target_profit = 150000
  248.  
  249. # 7% interest per each year
  250. interest = 1.07
  251.  
  252. # helper variables for the loop to keep track of current situation
  253. total = start_money
  254. current_profit = 0
  255.  
  256. # for-loop for years 1-30
  257. for year in range(1, 31):
  258.     # add the yearly money
  259.     total = total + yearly_money
  260.  
  261.     # add interest
  262.     total = total * interest
  263.  
  264.     # update how much profit we have earned so far
  265.     current_profit = total - start_money - (year * yearly_money)
  266.  
  267.     # check if we have met our goal yet
  268.     if current_profit >= target_profit:
  269.         print(f"We met our goal in the year: {year}")
  270.         # since we already know the year, no point continuing
  271.         # the loop => break
  272.         break
  273.  
  274. # if we didn't get to the target profit
  275. # print an informing message for the user
  276. if current_profit < target_profit:
  277.     print("This goal cannot be met within this time limit and starting investment.")
  278.  
  279. # NEW FILE
  280.  
  281. # ANOTHER EXAMPLE, CLASSIC: FIBONACCI
  282.  
  283. # Fibonacci sequence: every number is the sum of two previous numbers
  284. # first 9 numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21
  285.  
  286. # OUR GOAL: ask user a number: which Fibonacci number do they
  287. # want to see, and count the value with a for-loop
  288.  
  289. # examples:
  290. # if user inputs 5 = 1 + 2 = 3
  291. # if user inputs 6 = 2 + 3 = 5
  292. # if user inputs 7 = 3 + 5 = 8
  293. # if user inputs 8 = 5 + 8 = 13
  294. # x. number is old number + new number = fibonacci number
  295.  
  296. # helper variables to keep track of old and new number
  297. old_number = 0
  298. new_number = 1
  299.  
  300. # initialize fibonacci number to be 1 in the beginning
  301. fibonacci = 1
  302.  
  303.  
  304. choice = input("Which Fibonacci number would you like to see?\n")
  305. choice = int(choice) - 2
  306. print()
  307.  
  308. # for-loop that counts the Fibonacci number
  309. # until the choice-variable dictates
  310.  
  311. for number in range(choice):
  312.     print("New cycle!")
  313.     # calculate the current value
  314.     fibonacci = old_number + new_number
  315.  
  316.     print(f"Fibonacci is now: {old_number} + {new_number} = {fibonacci}")
  317.  
  318.     # update the old number
  319.     old_number = new_number
  320.  
  321.     # update the new number to be whatever fibonacci is now
  322.     new_number = fibonacci
  323.  
  324.     print(f"After this cycle: old_number = {old_number}, new number = {new_number}")
  325.     print()
  326.  
  327. print()
  328. print(f"Fibonacci number = {fibonacci}")
  329.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement