我想知道如何获得输入的列表中有多少个奇数。
例如,如果我输入[1、3、31、42、52],程序将打印出“有3个奇数”
number =list(input('list: '))
total = 0
for a in number :
a = int(a)
if a % 2 == 1 :
total = total + 1
print("odd number : %d 개" % total)
这是我的最大努力,但我不知道如何对此应用“列表”:我需要将此程序更改为打印出奇数之和的程序。
我的问题是:如何通过将最小代码从codeA更改为打印列表中的奇数之和的程序(codeB,来制作一个打印列表(codeA)中的奇数数的程序? )?
numbers = input('list: ')
# Convert, for example: "1, 3, 5" -> ["1", " 3", " 5"]
number = numbers.split(",")
total = 0
for a in number:
# Since these numbers are strings, they need to be converted to
# integers. You may also want to strip whitespace
if int(a.strip()) % 2 == 1:
total = total + 1
print("odd number : ", total)
a = list(input("list:"))
no_of_odds = 0
sum_of_odds = 0
for number in a:
try:
if int(number) % 2 == 1:
no_of_odds += 1
sum_of_odds += int(number)
except ValueError:
print("{0} is not a number. Skipping".format(number))
print("List: {0}".format(a))
print("No of odd numbers in list: {0}".format(no_of_odds))
print("Sum of the odd numbers in list: {0}".format(sum_of_odds))