2017-02-03 60 views
-1

我正在嘗試以非負整數的形式收集用戶輸入。然後我想取這個整數並告訴用戶它們的整數中有多少奇數,偶數和零個單獨的數字。如何從字符串中讀取單個數字並對其執行功能?

Ex。用戶輸入「123」,程序輸出Evens:1賠率:2個零: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

'對於[1]值:'有相當多的問題。 –

+4

請修復您的縮進 –

+0

再次放置代碼並使用按鈕「{}」在SO上正確格式化代碼。 – furas

回答

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)) 
+0

比你先生!這解決了我的問題。我對編碼相當陌生,所以我對可怕的縮進道歉。 – NickeyBear

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") 
相關問題