【问题标题】:Python: How to create a range for input() [duplicate]Python:如何为 input() 创建一个范围
【发布时间】:2017-03-24 04:19:16
【问题描述】:

我正在编写一些简单的 Python 代码,但是,我还是个新手,遇到了一个我无法解决的问题。

name = raw_input("What is your name? ")

maths = int(input("Enter your maths test result: "))
psychology = int(input("Enter your psychology test result: "))
economics = int(input("Enter your economics test result: "))
IT = int(input("Enter your IT test result: "))
religion = int(input("Enter your religion test result: "))
biology = int(input("Enter your biology test result: "))
average = (maths + psychology + economics + IT + religion + biology)/6
print "Your average test score is: ", average
minimum = min(maths, psychology, economics, IT, religion, biology)
print "Your lowest score is: ", minimum
maximum = max(maths, psychology, economics, IT, religion, biology)
print "Your highest score is: ", maximum

上面的代码允许用户输入他们的测试结果,并返回他们的平均分、最低分和最高分。但是,我需要创建一个范围,以便用户无法输入任何低于 0 或高于 100 的结果,尽管我自己或在线尝试查找后仍不确定如何执行此操作。

感谢您就我的问题提供任何帮助,谢谢。

【问题讨论】:

    标签: python input range


    【解决方案1】:

    创建一个检查用户输入的函数,该函数仅在输入有效时返回,例如:

    def ask_user(msj, start=0, end=100):
        while True:
            try:
                n = int(raw_input(msj))
                if start <= n <= end:
                    return n
            except ValueError:
                pass
            print("invalid input, try again")
    

    并使用而不是int(input(...))

    【讨论】:

    • 我可能会做def ask_user(msg, start=0, end=100):
    • @cricket_007 好主意,我加了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 2018-05-13
    • 2010-10-07
    • 2012-03-05
    • 1970-01-01
    • 2015-12-07
    • 2021-05-25
    相关资源
    最近更新 更多