1

How does one answer this question. 1. A dramatic society wants to record the number of tickets sold for each of their four performances. Ask the user to enter the number of tickets sold for each performance. The number must be between 0 and 120. Print an error message if an invalid number is entered and ask them to re-enter until they enter a valid number. Print the total number of tickets sold and the average attendance for a performance.

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)

My python book didn't really explain the correct syntax for the re module and the try except else function. Can someone point out if there is anything wrong with the code. This was my first go at validating user input.

jercai
  • 35
  • 1
  • 5
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – glibdud Feb 12 '18 at 15:44
  • No need for `re` here. Just assign `int(p)` to a variable in the `try` block and use that variable (say x) to check whether it's in required range: `if 0 <= x <= 120:` inside the `try` block itself. – Keyur Potdar Feb 12 '18 at 15:45
  • Your syntax error is because you forgot a comma after `total` in the second to last line. – glibdud Feb 12 '18 at 15:47

1 Answers1

0

You cannot use regular expression to see whether a number is between a certain range, and even if you did, it would be silly considering how easy it is to check if a number is between numbers in Python:

valid = 0 < p < 120

Here is your code after the fix:

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)

More on: Expressions in Python 3

A. Smoliak
  • 438
  • 2
  • 17