“并非在字符串格式化期间转换所有参数”取模数,其中isnumeric()为True

时间:2017-10-27 16:56:22

标签: python

while True:
    ans = input('Enter a number : ')
    if ans.isalpha():
        if ans == 'q':
            break
    elif ans.isnumeric():
        if ans == 1 or ans == 0:
            print('NOT even NOR odd number')
        elif ans % 2 == 0:
            print('EVEN number')
        else:
            print('ODD number')

并且像这样出错:

Traceback (most recent call last):
  File "C:/Users/Me.Qa/Desktop/app0001.py", line 9, in <module>
    elif ans % 2 == 0:
TypeError: not all arguments converted during string formatting

2 个答案:

答案 0 :(得分:0)

你不能将“ans”变量转换为int。只需添加

ans = int(ans)

if ans == 1 or ans == 0:

答案 1 :(得分:0)

ans是一个字符串。你不能在字符串上做数学;你需要先将它解析为数字。

如评论中所述,请将您的第二部分更改为:

elif ans.isnumeric():
    # int takes a string and returns 
    #  the number it represents
    num_ans = int(ans) 
    if num_ans == 1 or num_ans == 0:
        print('NOT even NOR odd number')
    elif num_ans % 2 == 0:
        print('EVEN number')
    else:
        print('ODD number')