我正在尝试以非负整数的形式收集用户输入。然后我想取这个整数并告诉用户整数中有多少个奇数,偶数和零个单位数字。
实施例。用户输入“123”并且程序输出Evens:1 Odds:2 Zeros:0
到目前为止,这是我的代码。
def main():
print("1. Enter a new number")
print("2. Print the number of odd, even and zero digits in the integer")
print("3. Print the sum of the digits of the integer")
print("4. Quit the program")
value = (input("Please enter a non-negative integer"))
Sum = 0
evens = 0
odds = 0
zeros = 0
loop=True
while loop:
main()
choice = int(input("Enter a number between 1 and 4:"))
if choice==1:
loop=False
value = int(input("Please enter a non-negative integer"))
loop=True
elif choice==2:
loop=False
value_string = str(value)
for ch in value_string:
print(ch)
for [1] in value:
if i % 2 == 0:
evens = evens + 1
print(evens)
elif choice==3:
loop=False
while (value >0):
remainder = value % 10
Sum = Sum + remainder
value = value //10
print("Sum of the digits = %d" %Sum)
答案 0 :(得分:0)
您的代码严重缩进,难以理解。但你可以这样做。
value = input('enter digits ')
digits = [int(d) for d in value]
odds = sum(d % 2 for d in digits)
zeros = sum(d == 0 for d in digits)
evens = len(digits) - odds
print('evens: {}, odds: {}, zeros: {}'.format(evens, odds, zeros))
答案 1 :(得分:0)
在这里,我有相同的代码缩进,重构和改进,以处理一些边缘情况并提供正确的结果。
def main():
print("1. Enter a new number")
print("2. Print the number of odd, even and zero digits in the integer")
print("3. Print the sum of the digits of the integer")
print("4. Quit the program")
loop = True
while loop:
main()
choice = str(input("Enter a number between 1 and 4: "))
if (choice.isdigit() and 1 <= int(choice) <= 4):
choice = int(choice)
if choice == 1:
value = str(input("Please enter a non-negative integer"))
if (value.isdigit() and int(value) >= 0):
value = int(value)
else:
print(
"You provided an invalid input. Please enter a non-negative number")
elif choice == 2:
value = str(value)
odds = len([d for d in value if (int(d) % 2) == 1])
evens = len([d for d in value if (int(d) % 2) == 0])
zeros = len([d for d in value if d == '0'])
print('odd: {} even: {} zeros: {}'.format(odds, evens, zeros))
elif choice == 3:
value = str(value)
print('Sum of digits = {}'.format(sum(map(int, value))))
elif choice == 4:
print("Program is exiting")
loop = False
else:
print("You provided an invalid input. Please enter a number between 1 and 4")