+ 1
Please update the code...
This code takes numbers from the user... Then removes spaces between them... In the loop, each number first becomes integer then if i % 2 == 0 in short, if it's even then sum gets it... So this code calculates the sum of even numbers entered by the user... But if I enter 11 12 13 14 15... it separates them too... How can I overcome this problem... https://code.sololearn.com/cmi5h0Umtn0U/?ref=app
4 Respuestas
+ 8
numbers = [int(i) for i in input().split()]
"input().split()" splits the given input or string by whitespace by default, (you can split string with whatever character you want)
For example:
INPUT: 1 2 3 4
>> ["1", "2", "3" "4"]
But they are taken as a string because input() takes input as string by default, therefore we need to use list comprehension to convert each element into integer.
[int(i) for i in input().split()]
https://code.sololearn.com/c7eXjIByCX4d/?ref=app
+ 8
Name , you are about to finish the python tutorial and i assume that you have already some experience. here is quite compact code:
numbers = list(map(int, input().split()))
print(sum([num for num in numbers if num % 2 == 0]))
- the first line uses map which applies the int conversion to each element coming from input.split() it creates a list of int numbers
- the second line is a list comprehension with a if... conditional. the crated numbers will be summarized and printed
+ 2
Thanks Nicko 12
0
Thanks, Lothar