我的节目剂量不会因为整数值,字符串

我的节目剂量不会因为整数值,字符串

问题描述:

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() 

这段代码之间的混淆的运行i具有误差在它我的节目剂量不会因为整数值,字符串

userinput2 = INT(的raw_input(“按t退出或选择了号码:”) ) 如果userinput2 ==“T”:

,如果我将其更改为字符串,我曾经有过不接受字符串,如果让弦,它不接受整数

+0

为什么不*按-1退出或选择一个数字*?这可以节省您的决定,如果输入应该是字符串和/或* castable *到int –

+0

问题我的任务说只按t只有 –

我认为这涵盖了你需要的情况:

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

非常感谢它解决了我的问题 –