Python Project: Multiply all integers from 1 - 100
Write a program that multiplies all integers from 1 until the product exceeds 100.
This is the final code and below is the documentation of this code.
"""Multiplicera heltal till = 100"""
"""Skriv ett program som multiplicerar alla heltal
från 1 upp till det att produkten överstiger 100."""
# create a list of all integers where product > 100.
integers = list(range(1, 6))
product = 1
# use for loop to multiply list until product > 100.
for number in integers: # iterate *= each element in integers list.
product *= number # the value of *= number is stored in product.
if product >= 100: # condition statement. if True
break # break
print(product)
Logic:
- Use while loop, *= and break statement
Use while loop and *= to increment (multiply) all integers until product > 100. Use the break condition to stop.
- list and range() function
Create a variable with all the lists of integers using range() function. Multiply all numbers within this list until the x > 100 condition is True. Choose range() function because the code should not be too complicated.
Source: w3schools.com/python/ref_func_range.asp
Step 1: Create a list with all the integers where product > 100 and assign that list to a variable named integers. Use the range() function to decide the parameter, which is (1,6) because when calculated, the numbers that yields the product >= 100 are from 1 to 5. The last index is not included, therefore, we write the parameter (1, 6).
Create a variable named product and assign the value 1. Product = 1 starts from because it is multiplied from 1, not 0.
Step 2: CODE and TRIAL ERROR.
This is the first trial and it has not been corrected yet.
Output:
Change the variable integers to product and change the condition to product <= 100.
Output: This happens when Python isn’t told to stop looping.
Output:
Something is wrong with this code. I want to use *= to multiply everything in my integers list. I also want to use if product >= 100: break. I need to use a different kind of loop, which is for loop.
for loop and break statement
According to geeksforgeeks.org, while loop is not the appropriate statement to use for a list with known iterations. It should be for loop.
It is known that the number of iterations (range(1, 6)). Also, we don’t want to repeat the increment *= execution continuously, so the use of for loop is better.
Use this syntax as a guide. Although the list, the variables and the assignment operator must be changed in the code.
Use syntax structure in my code:
Final Output: I know it is not the best answer to the question. But I want to increment the products of range(1, 6) by using product *=number.
I also want to use if product >= 100: break, statement.