【问题标题】:Convert variable from int to str in a while loop? [duplicate]在while循环中将变量从int转换为str? [复制]
【发布时间】:2016-12-03 02:02:15
【问题描述】:

我正在阅读Python Crash Course这本书,在其中一个练习中遇到了一点小问题。基本上,它要求您创建一个 while 循环,告诉用户输入他们的年龄,然后它会根据他们的年龄返回票的价格。这应该重复,直到用户键入“退出”。非常简单,除了我对如何将输入从整数(他们的年龄)转换为字符串(“退出”)感到困惑。每当我尝试键入 quit 时,我都会收到错误消息:“int() 以 10 为底的无效文字:'quit'”。这是我目前所拥有的:

age_prompt = "\nWrite in your age: "
age_prompt += "\nType 'quit' to exit "

while True:
    age = int(input(age_prompt))
    if age < 3:
        print("Your ticket is free.")
    elif age < 12:
        print("Your ticket is $10")
    else:
        print("Your ticket is $15")

    if age == 'quit':
        break

【问题讨论】:

    标签: python string loops while-loop integer


    【解决方案1】:

    您需要测试变量是否为"quit"转换为整数(因为"quit" 显然不是数字,所以Python 正确地抱怨)。

    你可以这样做:

    while True:
        age = input(age_prompt)
        if age == 'quit':
            break
    
        try:
            age = int(age)
            if age < 3:
                print("Your ticket is free.")
            elif age < 12:
                print("Your ticket is $10")
            else:
                print("Your ticket is $15")
        except ValueError:
            print("Invalid input. Please enter a valid number or 'quit'")
    

    【讨论】:

    • 如果再输入quit以外的其他内容,这仍然可能导致ValueError
    • 非常正确,我现在就更正一下。
    • 还可以通过添加 isNumeric() 检查年龄来避免可能的错误,如果没有,则“继续”循环。
    【解决方案2】:
    age_prompt = "\nWrite in your age: "
    age_prompt += "\nType 'quit' to exit "
    
    while True:
        try:
            age = input(age_prompt)
            age = int(age)
            if age < 3:
                print("Your ticket is free.")
            elif age < 12:
                print("Your ticket is $10")
            else:
                print("Your ticket is $15")
    
        except ValueError:
            if age == 'quit':
                break
    

    检查它是否是一个int。如果不是,请检查它是否'退出'

    【讨论】:

    • 您在这里使用异常有什么特别的原因吗? OP 是 python 的新手,所以这可能不是最好的推荐。
    • @kirkpatt 刚接触 Python 是人们应该了解异常处理的更多原因
    • 异常对于编写 python 代码来说是非常基础的。它们并不复杂,而且很有必要
    • 我的意思是,根据 OP 所处的水平,最好不要在解决其他问题时尝试引入新概念。问题提到了 Python Crash Course,其中有一个关于异常的部分,所以他们会到达那里。
    • 太棒了,谢谢!是的,我几天前才开始学习,所以所有这些对我来说都是新的。
    【解决方案3】:

    您必须使用单独的变量(或例外 - 没有示例)

    while True:
        ui = input(age_prompt)
        if ui == 'quit':
            break
    
        age = int(ui)
        if age < 3:
            print("Your ticket is free.")
        elif age < 12:
            print("Your ticket is $10")
        else:
            print("Your ticket is $15")
    

    【讨论】:

    • 如果用户键入“quit”,您仍然会在int(ui) 上收到异常。
    • @whrrgarbl 已修复愚蠢的复制粘贴错误
    【解决方案4】:

    从对input() 的调用中接收作为字符串的用户输入。在您的示例中,您直接将input() 的输出转换为整数:

    age = int(input(age_prompt))
    

    将输入转换为整数后,您不能再将整数与字符串"quit" 进行比较,因为它们不能直接比较。您可以在转换为整数之前处理输入字符串。

    # read user input as a string
    user_input = input(age_prompt)
    
    if user_input == "quit":
        quit()
    elif user_input == SOME_OTHER_COMMAND:
        other_command()
    else:
        # try to convert input into an integer
        try:
            age = int(user_input)
        except ValueError:
            print "Input '%s' is invalid!"
            quit()
        if age < 3:
            ...
    

    【讨论】:

      【解决方案5】:

      试试这个:

      age_prompt = "\nWrite in your age: "
      age_prompt += "\nType 'quit' to exit "
      
      while True:
              age = raw_input(age_prompt)
      
              if age == 'quit':
                  break
              else:
                  age = int(age)
                  if age < 3:
                          print("Your ticket is free.")
                  elif age < 12:
                          print("Your ticket is $10")
                  else:
                          print("Your ticket is $15")
      

      【讨论】:

      • 我认为 OP 正在使用 python3,因为他使用 input() 而不是 raw_input() 并且他还使用了 print() 函数
      • 你是对的!我只是在使用python2.7,并没有意识到他正在使用python3。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-03
      • 2015-02-16
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      相关资源
      最近更新 更多