简体   繁体   中英

How do you deny an input, re ask it, and ONLY retain that value

Hello Stack community,

I used an if or statement while asking an input from the user, if the user inputs a value outside of my if or statement then I display a message saying "Please enter a valid number from 1 to 500", that brings up another input request to the user.

So I have accomplished 2/3 of my goal. I have denied the original input, I have re-asked it, however I cannot find a way to retain only the new value after re-asking the user. Instead my program holds onto the original user input which was outside of the needed parameters, then it also holds onto the new input after being re-asked and combines them into one value. This is on Python IDLE 3.6.

The exact question: How do you erase the original input value from the user input, and only retain the new value after being re-asked?

Here is my code:

def main():

    resultsA = int(input("Please enter how many seats you sold is section A:"))
    if resultsA < 1 or resultsA > 300:
                int(input("Please enter a valid number from 1 to 300:"))


    resultsB = int(input("Please enter how many seats you sold is section B:"))
    if resultsB < 1 or resultsB > 500:
                int(input("Please enter a valid number from 1 to 500:"))


    resultsC = int(input("Please enter how many seats you sold is section C:"))
    if resultsC < 1 or resultsC > 200:
                int(input("Please enter a valid number from 1 to 200:"))


    finalResultA = 20*resultsA
    finalResultsB = 15*resultsB
    finalResultsC = 10*resultsC
    trulyFinal = finalResultA + finalResultsB + finalResultsC

    print ("Congratulations, here is your total revenue from tickets: $",trulyFinal)

Here is a screen shot of what is happening in the shell: 在此输入图像描述

You can use an infinite loop to keep asking the user for a valid input until the user enters one. Note that you should also use a try-except block to ensure that the user enters a valid integer:

while True:
    try:
        resultsA = int(input("lease enter how many seats you sold is section A:"))
        if 1 <= resultsA <= 300:
            break
        raise RuntimeError()
    except (ValueError, RuntimeError):
        print("Please enter a valid number from 1 to 300.")

And since you're going to ask the same question for different section of seats, you can store the pricing of different sections in a dict, and then iterate through the sections to ask the question while calculating the total revenue:

pricing = {'A': 20, 'B': 15, 'C', 10}
availability = {'A': 300, 'B': 500, 'C', 200}
trulyFinal = 0
for section in pricing:
    while True:
        try:
            seats = int(input("lease enter how many seats you sold is section %s:" % section))
            if 1 <= seats <= availability[section]:
                trulyFinal += pricing[section] * seats
                break
            raise RuntimeError()
        except (ValueError, RuntimeError):
            print("Please enter a valid number from 1 to %d." % availability[section])

print ("Congratulations, here is your total revenue from tickets: $", trulyFinal)

You can easily make a function that accomplishes your task with a try/except block in it:

def int_input(prompt, lower, higher, bad_input='bad input:'):
  while True:
    try:
      r = int(input(prompt))
      if r < lower or r > higher:
        raise ValueError('enter a number between {} and {}'.format(lower, higher))
    except ValueError as e:
      print(bad_input, e)
    else:
      return r

Then use it in your code:

resultsA = int_input(
    'enter no. of seats sold in section A',
    1,
    200,
    'invalid input'
)

Try this one:

def main():

    resultsA = int(input("Please enter how many seats you sold is section A:"))
    while(resultsA < 1 or resultsA > 300):
        resultsA = int(input("Please enter a valid number from 1 to 300:"))


    resultsB = int(input("Please enter how many seats you sold is section B:"))
    while(resultsB < 1 or resultsB > 500):
        resultsB = int(input("Please enter a valid number from 1 to 500:"))


    resultsC = int(input("Please enter how many seats you sold is section C:"))
    while(resultsC < 1 or resultsC > 200):
        resultsC = int(input("Please enter a valid number from 1 to 200:"))


    finalResultA = 20*resultsA
    finalResultsB = 15*resultsB
    finalResultsC = 10*resultsC
    trulyFinal = finalResultA + finalResultsB + finalResultsC

    print ("Congratulations, here is your total revenue from tickets: $",trulyFinal)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM