- 1
For loop
list = [1, 2, 3, 4, 5, 6, 7, 8, 9] sum = 0 #your code goes here for x in list: if (x <= 10): sum += x if sum == 45: print(sum) is there a simpler code than this? I can only complete the task this way. The question of this assignment is to add each number in the list. until the total number is 45.
7 ответов
+ 5
Please avoid using built-in class or function names for variable names. Here you are using 'list' and 'sum' as variable names.
+ 5
Adi Purnomo
There is a shorter code to add the numbers in a list together, but I believe your teacher wanted you to use the for loop format , with the variable incrementaion.
However for your future knowledge:
lst = list(range(10))
print(sum(lst))
This could be broken down even further:
print(sum(list(range(10)))
But it is important to understand what is happening in the background, which is why the system you used is so important
+ 4
Adi Purnomo Your code keeps adding all the elements of the list even after the total reaches 45.
If you want the adding to stop and the total to be printed when it reaches 45, you can use a 'while' loop.
Ipang made a good point about not using built in function names as variables, so I changed them.
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
tot = 0
#your code goes here
while tot < 45:
for x in lst:
tot += x
print(tot)
Btw you don't need the parentheses () after 'if' ;)
+ 2
Ipang Yes, from the questions I got it was like that. maybe next time i code it myself, i'll shorten it again. thank you
+ 2
Rik Wittkopp yes, it could be like that. thank you. I will study harder
+ 1
Add number from 1 to 9 is 45.
list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sum = 0
#your code goes here
for x in list:
sum += x
print(sum)#output is 45
That is enough
+ 1
Myo Thuzar it can't be like that, the result will be written 1.3.6.9 and so on. and sorry maybe my statement is a little confusing. I mean the output should be 45. but thanks for answering