验证用户输入程序语法错误

时间:2018-02-12 15:31:55

标签: python-3.x

如何回答这个问题。 一个戏剧性的社会想要记录他们四场演出中每一场演出的门票数量。要求用户输入每次演出的售票数量。该数字必须介于0和120之间。如果输入的数字无效,请输入错误消息,并要求他们重新输入,直到输入有效数字。打印出售的门票总数和演出的平均出勤率。

import re
affirm = False
p = 0
total = 0
for p in range(4):
   p = input("Please enter the total number of tickets sold for the performance.")
while affirm != True:
    try:
        int(p)
    except ValueError:
        print("This is not a number")
    else:
        valid = re.match("[0-120]",p)
        if valid:
            total += p
            affirm = True
        else:
           p = input("Please enter the total number of tickets sold for the performance.") 
average = (total/480) * 100
average = round(average,2)
print("""
The total number of tickets sold is: """,total"""
The average attendance is : """,average)

我的python书并没有真正解释re模块和try除else函数的正确语法。有人可以指出代码是否有任何问题。这是我第一次验证用户输入。

1 个答案:

答案 0 :(得分:0)

你不能使用正则表达式来查看一个数字是否在某个范围之间,即使你这样做,考虑在Python中数字是否介于数字之间是多么容易,这将是愚蠢的:

valid = 0 < p < 120

以下是修复后的代码:

affirm = False
p = 0
total = 0
for p in range(4):
   p = input("Please enter the total number of tickets sold for the performance.")
while affirm != True:
    try:
        int(p)
    except ValueError:
        print("This is not a number")
    else:
        valid = 0 < p < 120
        if valid:
            total += p
            affirm = True
        else:
           p = input("Please enter the total number of tickets sold for the performance.")
average = (total/480) * 100
average = round(average,2)
print("""
The total number of tickets sold is: """,total"""
The average attendance is : """, average)

更多信息:Expressions in Python 3