Advertisement
tuomasvaltanen

Untitled

Oct 9th, 2023 (edited)
707
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.45 KB | None | 0 0
  1. # lecture 10.10.2023, repetition statements, also known as: loops
  2. print("Welcome!")
  3.  
  4. # NEW FILE
  5.  
  6. # a simple for-loop: 10 cycles
  7. # basically: we ask Python to run this line of
  8. # code 10 times in a row
  9. for x in range(10):
  10.     # this is the line we ask Python to run 10 times in a row
  11.     print(x)
  12.  
  13. # ANOTHER VERSION
  14.  
  15. # a simple for-loop: 10 cycles
  16. # basically: we ask Python to run this line of
  17. # code 10 times in a row
  18. for x in range(10):
  19.     # this is the line we ask Python to run 10 times in a row
  20.     print(f"Number: {x}")
  21.  
  22. # NEw FILE
  23.  
  24. # usually we place the range limits
  25. # into variables
  26. start = 2017
  27. end = 2023
  28.  
  29. # we can also define start and end
  30. # of the range
  31. for year in range(start, end):
  32.     print(year)
  33.  
  34. # ANOTHER VERSION
  35.  
  36. # usually we place the range limits
  37. # into variables
  38. start = 2017
  39. end = 2023
  40.  
  41. # we can also define start and end
  42. # of the range
  43. # third parameter is called step
  44. # if you use 2, the loop skips in increments of 2
  45. # instead of 1 (default step is 1)
  46. for year in range(start, end, 2):
  47.     print(year)
  48.  
  49. # NEW FILE
  50. # you can try this in Python Tutor also
  51. # to visualize the logic
  52. # create an empty text variable
  53. text = ""
  54.  
  55. # the idea is build the text-variable
  56. # from pieces in a loop
  57. for year in range(2017, 2024):
  58.     text = text + str(year) + "-"
  59.  
  60. # let's remove the extra dash from the end
  61. # this substring means: take everything from
  62. # beginning until second last character
  63. text = text[:-1]
  64. print(text)
  65.  
  66. # NEW FILE
  67.  
  68. print("Start!")
  69.  
  70. # a simple for + if/else
  71. # each cycle checks if the number is even or odd
  72. for x in range(10):
  73.     if x % 2 == 0:
  74.         print("Even!")
  75.     else:
  76.         print("Odd!")
  77.  
  78. print("App ended.")
  79.  
  80. # NEW FILE
  81.  
  82. # counter variable, initialize to 1
  83. # can also be 0
  84. counter = 1
  85.  
  86. # while-loop is similar to if-statement, it has a condition
  87. # so while the counter variable is less or equal to 10
  88. # => keep running this code
  89. while counter <= 10:
  90.     print(counter)
  91.  
  92.     # always increment (add 1) to counter
  93.     # in the end of each cycle
  94.     # otherwise we get an infinite loop
  95.     # because counter will always be under 10
  96.     counter = counter + 1
  97.  
  98. # NEW FILE
  99.  
  100. # create a helper variable that keeps track
  101. # if our application should still be running
  102. running = True
  103.  
  104. # our main loop, run the code as long as the user wants to
  105. while running:
  106.     print("App is running!")
  107.  
  108.     # ask user a number for this cycle of app
  109.     number = input("Give a number:\n")
  110.     number = int(number)
  111.  
  112.     # double the number and print it out
  113.     total = number * 2
  114.     print(f"Number doubled: {total}")
  115.     print()
  116.  
  117.     # ask user if they still want to continue with the app
  118.     choice = input("Would you like to continue? (y/n)?\n")
  119.  
  120.     # if users inputs "n" => exit the app
  121.     if choice.lower() == "n":
  122.         running = False
  123.  
  124. # this is run afterwards as the final code line
  125. # when the while loop above ends (user inputs "n")
  126. print("Thank you for using our application!")
  127.  
  128. # NEW FILE
  129.  
  130. # nesting loops
  131.  
  132. print("Start!")
  133.  
  134. for x in range(3):
  135.     print(f"MAIN LOOP, x = {x}")
  136.  
  137.     # whatever is inside this main loop
  138.     # is run 3 times (range(3))
  139.     # including nested loops
  140.     # so this loop is also run 3 times
  141.     for y in range(5):
  142.         print(f"\tNested for-loop: y = {y}")
  143.  
  144.  
  145. print("End app!")
  146.  
  147. # A MORE PRACTICAL VERSION OF THE ABOVE
  148.  
  149. print("Today's sales report:")
  150.  
  151. # we could also have a more complex nesting
  152. # for example:
  153. # department -> order -> product
  154.  
  155. # first, let's loop all our orders
  156. for order in range(3):
  157.     print(f"Processing order: {order}")
  158.  
  159.     # each order has 5 products
  160.     # => loop through all the products in
  161.     # this cycle's product
  162.     for product in range(5):
  163.         print(f"\tProcessing order {order}, product {product}!")
  164.  
  165. print("All ready.")
  166.  
  167. # ANOTHER EXAMPLE
  168.  
  169. print("Start app!")
  170.  
  171. # 5 persons in line
  172. for person in range(5):
  173.     # new person in turn
  174.     print(f"Person {person + 1} turn!")
  175.  
  176.     # it's this person's turn to say numbers 1-4
  177.     for number in range(4):
  178.         print(f"Person {person + 1} says number: {number + 1}!")
  179.  
  180.  
  181. print()
  182. print("Everyone has spoken!")
  183.  
  184. # NEW FILE
  185.  
  186. print("Start!")
  187.  
  188. for x in range(5):
  189.     # if x == 3 => stop this for-loop
  190.     # and continue after the for-loop
  191.     if x == 3:
  192.         break
  193.  
  194.     print(x)
  195.  
  196. print("End.")
  197.  
  198. # NEW FILE
  199.  
  200. print("Start!")
  201.  
  202. for x in range(5):
  203.     # if x == 3 => skip this cycle
  204.     # and continue where x = 4
  205.     if x == 3:
  206.         continue
  207.  
  208.     print(x)
  209.  
  210. print("End.")
  211.  
  212. # NEW FILE
  213.  
  214. total = 0
  215.  
  216. # ask user 10 times a number
  217. # add the number to the total -variable
  218. for x in range(10):
  219.     number = int(input("Give number:\n"))
  220.     total = total + number
  221.  
  222. # what is the sum in them
  223. print(total)
  224.  
  225. # NEW FILE
  226.  
  227. # how many cycles we want to ask the number
  228. # any integer works, even random integers (as long as it's an integer)
  229. cycles = int(input("How many numbers to ask?\n"))
  230. total = 0
  231.  
  232. # run the for-loop as many times as user wanted
  233. # and accumulate the total -variable
  234. for x in range(cycles):
  235.     number = int(input("Give number:\n"))
  236.     total = total + number
  237.  
  238. print(total)
  239.  
  240. # NEW FILE
  241.  
  242. # interest calculator
  243.  
  244. # compound interest, with loops instead of mathematical equation
  245. # yearly interest = 7%
  246. # add 2000€ in the beginning of each year
  247.  
  248. start_money = 15000
  249. yearly_money = 2000
  250.  
  251. # interest of 7%, use 1.07 for easier multiplication
  252. interest = 1.07
  253.  
  254. # the goal is to find out the amount of new money after 10 years of saving
  255.  
  256. total = start_money
  257.  
  258. # use Python to calculate interest
  259. # for our money 10 years in a row
  260. for year in range(10):
  261.     # in the beginning of each year, add 2000€ more
  262.     total = total + yearly_money
  263.  
  264.     # calculate interest
  265.     total = total * interest
  266.  
  267. # total money in the end
  268. total = round(total, 2)
  269. print(f"Money after 10 years of saving: {total} €")
  270.  
  271. # new money in the end => how much profit we had
  272. profit = total - start_money - (10 * yearly_money)
  273. print(f"After 10 years, our profit is = {profit} €")
  274.  
  275. # NEW VERSION
  276.  
  277. # VERSION 2: Interest calculator / compound interest
  278. # how many years does it take for us to reach a certain profit
  279.  
  280. start_money = 15000
  281. yearly_money = 2000
  282.  
  283. # what is our target savings
  284. target_profit = 150000
  285.  
  286. # 7% interest per each year
  287. interest = 1.07
  288.  
  289. # helper variables for the loop to keep track of current situation
  290. total = start_money
  291. current_profit = 0
  292.  
  293. # for-loop for years 1-30
  294. for year in range(1, 31):
  295.     # add the yearly money
  296.     total = total + yearly_money
  297.  
  298.     # add interest
  299.     total = total * interest
  300.  
  301.     # update how much profit we have earned so far
  302.     current_profit = total - start_money - (year * yearly_money)
  303.  
  304.     # check if we have met our goal yet
  305.     if current_profit >= target_profit:
  306.         print(f"We met our goal in the year: {year}")
  307.         # since we already know the year, no point continuing
  308.         # the loop => break
  309.         break
  310.  
  311. # if we didn't get to the target profit
  312. # print an informing message for the user
  313. if current_profit < target_profit:
  314.     print("This goal cannot be met within this time limit and starting investment.")
  315.  
  316. # ANOTHER EXAMPLE, CLASSIC: FIBONACCI
  317.  
  318. # Fibonacci sequence: every number is the sum of two previous numbers
  319. # first 9 numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21
  320.  
  321. # OUR GOAL: ask user a number: which Fibonacci number do they
  322. # want to see, and count the value with a for-loop
  323.  
  324. # examples:
  325. # if user inputs 5 = 1 + 2 = 3
  326. # if user inputs 6 = 2 + 3 = 5
  327. # if user inputs 7 = 3 + 5 = 8
  328. # if user inputs 8 = 5 + 8 = 13
  329. # x. number is old number + new number = fibonacci number
  330.  
  331. # helper variables to keep track of old and new number
  332. old_number = 0
  333. new_number = 1
  334.  
  335. # initialize fibonacci number to be 1 in the beginning
  336. fibonacci = 1
  337.  
  338.  
  339. choice = input("Which Fibonacci number would you like to see?\n")
  340. choice = int(choice) - 2
  341. print()
  342.  
  343. # for-loop that counts the Fibonacci number
  344. # until the choice-variable dictates
  345.  
  346. for number in range(choice):
  347.     print("New cycle!")
  348.     # calculate the current value
  349.     fibonacci = old_number + new_number
  350.  
  351.     print(f"Fibonacci is now: {old_number} + {new_number} = {fibonacci}")
  352.  
  353.     # update the old number
  354.     old_number = new_number
  355.  
  356.     # update the new number to be whatever fibonacci is now
  357.     new_number = fibonacci
  358.  
  359.     print(f"After this cycle: old_number = {old_number}, new number = {new_number}")
  360.     print()
  361.  
  362. print()
  363. print(f"Fibonacci number = {fibonacci}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement