+ 1
Just a doubt!
Hello everyone! How are you? I'm learning phyton and I've some questions. How can I "decide" which of this methods is better suited, runs faster and it's more "phytonical" correct? # Get 10 numbers from a user and sum them. 1) list=[] for i in range(10): list.append(int(input("Enter a number: "))) print(sum(list)) 2) sum=0 for i in range (10): number = int(input("Enter a number: ")) sum += number print(sum)
7 Respuestas
+ 3
Both works, both are pythonic, and both are just the same since when you run your number (1), number(2) is happening in the background.
In other words when you use "sum" function, there is an iteration happening in the background similar to your second snippet.
+ 3
speed has not to be considered, as the loop is asynchronous related to user input (and even speed difference would be unuseful and micro-optimisation).
+ 2
The solution from Abol is very concise and pythonic although I wonder what Allah has to do with it.
To understand it, read about List comprehension. At this level you shouldn't worry about runtime performance. Instead focus on clean and readable code.
If you want to use the numbers for something else, consider this variant:
numbers = [int(input()) for _ in range(10)]
print(sum(numbers))
0
Discuss teaching and learning methods