【问题标题】:About Python syntax [duplicate]关于 Python 语法 [重复]
【发布时间】:2016-01-01 07:56:08
【问题描述】:
def get_input():

    '''
    Continually prompt the user for a number, 1,2 or 3 until
    the user provides a good input. You will need a type conversion.
    :return: The users chosen number as an integer
    '''
    #pass # REPLACE THIS WITH YOUR CODE

    n = input ("Enter the number 1,2 and 3? ")

    while n > 0 and n < 4:
        print("Invalid Input, give the  number between 1 to 3")
        n = input ("Enter the number 1,2 or 3? ")
    return (n)


get_input()

我没有得到答案,它只是不工作,我正在寻找这样的答案,

Give me one of 1,2 or 3: sid
Invalid input!
Give me one of 1,2 or 3: 34
Invalid input!
Give me one of 1,2 or 3: -7
Invalid input!
Give me one of 1,2 or 3: 0
Invalid input!
Give me one of 1,2 or 3: 2

Process finished with exit code 0

【问题讨论】:

  • 你的代码会吐出一个错误TypeError: unorderable types...,当你问一个包含错误和回溯的问题时,它只是不工作通常不是很丰富,甚至如果你转换你的代码会崩溃,如果用户输入一个不能转换为 int 的字符串,你应该使用 try/except

标签: python python-3.x user-input


【解决方案1】:

input() 内置函数返回一个 str 类型的值。

正如函数 get_input() 声明后的 (doc) 字符串中所指定的那样:

您需要进行类型转换。

因此,您必须将其包装在 int() 中以将其转换为整数 int。

n = int(input("Enter the number 1,2 or 3? "))

然后你可以使用比较运算符来评估是否是in接受值的限定范围:

   # Your comparisons are mixed.
   # You can use the in operator which is intuitive and expressive
   while n not in [1, 2, 3]:
        print("Invalid Input, give the  number between 1 to 3")

        # remember to wrap it in an int() call again
        n = int(input ("Enter the number 1,2 or 3? "))
    return (n)

如果您提供数字,这将非常有效:

Enter the number 1,2 and 3? 10
Invalid Input, give the  number between 1 to 3
Enter the number 1,2 and 3? -1
Invalid Input, give the  number between 1 to 3
Enter the number 1,2 and 3? 15
Invalid Input, give the  number between 1 to 3
Enter the number 1,2 and 3? 104
Invalid Input, give the  number between 1 to 3

但如果你提供单个字符或字符串(类型str),你会得到一个错误:

Enter the number 1,2 and 3? a

ValueError: invalid literal for int() with base 10: 'a'

这超出了问题的范围,但您可以want to look into it。

不管怎样,你的 while 条件让我失望了..


您似乎将Python 2 与通过__future__ 导入的print_function 一起使用。 (否则不同类型之间的比较会在while 语句中引发TypeError)。

检查您的 python python -V [在命令行中] 的版本并:

如果使用 python 2 而不是 input() 使用 raw_input():

n = int(raw_input("Enter the number 1, 2, 3: ")

如果我错了,而您确实在使用Python 3.x,请按照说明使用int(input())。

【讨论】:

  • 它的 Python 3.3,谢谢伙计。让我看看它是否有效,
  • 啊,不太确定3.3 中的这些行为。您可能应该获得最新版本,这样您就不会感到困惑。
  • 它工作正常,除了它不起作用,给我 1,2 或 3 之一:sid 无效输入!
  • 是的,对于输入字符串的情况,您需要执行一些exception handling。
猜你喜欢
  • 1970-01-01
  • 2014-10-28
  • 2012-08-11
  • 2020-05-15
  • 1970-01-01
  • 2017-07-23
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多