由于整数值和字符串之间的混淆,我的程序无法运行

时间:2016-07-26 00:16:10

标签: python

my program confuse between integer value and string 
import random


def test():
    num=random.randrange(100,1000,45)
    while True:
        ans=run(num)
        print ans
        ss=raw_input("if you want to exit press t: ")
        if ss=='t':
            break

def run(userinput2):
    first = int(userinput2/20)
    print "i will send it in %s big pack"%str(first)
    userinput2=userinput2%20
    second =int(userinput2/10)
    print "i will send it in %s med pack"%str(second)
    third =userinput2%10
    print "i will send it in %s med pack"%str(third)



def main():
    print "the began of pro"
    print "@"*20
    userinput=raw_input("test or run: ")
    if userinput.lower()=='test':
        test()
    else:
        while True:
            userinput2=int(raw_input("press t to exit or chose a number:"))
            if userinput2 =='t':
                break
            else:
                answer=run(userinput2)


if __name__ == "__main__":
      main()

这段代码我有错误

userinput2 = int(raw_input(“按t退出或选择一个数字:”))             如果userinput2 =='t':

如果我将其更改为字符串我不接受字符串,如果使其成为字符串,则不接受整数

1 个答案:

答案 0 :(得分:2)

我认为这涵盖了您需要的案例:

while True:
    userinput2=raw_input("press t to exit or chose a number:")
    if userinput2 =='t':
        break
    try:
        userinput2 = int(userinput2)
    except ValueError:
        print('That was neither a number nor a "t".  Try again.')
        continue
    answer=run(userinput2)