值不存储在python程序中

时间:2014-06-06 17:13:46

标签: python validation loops input storage

我正在输入验证章节中从我的教科书中练习编程练习。我被要求编写一个程序,如果座位部分不是A,B或C,则将用户循环回输入。一旦选择了一个部分,它会要求用户输入该部分中售出的票数(直到它是正确的,每个部分的最大值不同。最后是计算该部分的收入。如果值正确,我的代码运行正常,但是一旦我输入了错误的代码,然后重新输入它,因为它不计算收入。我认为这是因为没有存储这些值。

以下是代码:

def main():
section = input('Enter desired seating section: ')

while section != 'A' and section != 'B' and section != 'C':
    print('That is invalid, enter A, B, or C')
    section = input('Enter desired seating section: ')

tickets = int(input('Enter the amount of tickets sold: '))

if section == 'A':
    if tickets >= 0 and tickets <= 300:
        getSectionA(tickets)
    else:
        while tickets < 0 or tickets > 300:
            print('Invalid, enter a value from  0 to 300')
            tickets = int(input('Enter amount of tickets sold: '))

elif section == 'B':
    if tickets >= 0 and tickets <= 500:
        getSectionB(tickets)
    else:
        while tickets < 0 or tickets > 500:
            print('Invalid, enter a value from 0 to 500')
            tickets = int(input('Enter amount of tickets sold: '))
elif section == 'C':
    if tickets >= 0 and tickets <= 200:
        getSectionC(tickets)
    else:
        while tickets < 0 or tickets > 200:
            print('Invalid, enter a value from 0 to 200')
            tickets = int(input('Enter amount of tickets sold: '))

def getSectionA(numberA):
revA = numberA * 20
print('Your section revenue is', revA)


def getSectionB(numberB):
revB = numberB * 15
print('Your section revenue is', revB)


def getSectionC(numberC):
revC = numberC * 10
print('Your 5section revenue is', revC)


main()

3 个答案:

答案 0 :(得分:1)

仅当在第一个输入上检查数字边界的getSectionA条件成功时,才会调用

if和类似的内容。进入else后,即使getSectionA循环结束,也不会再回复while

考虑重写代码,以便在getSectionAif部分调用else

if section == 'A':
    if tickets >= 0 and tickets <= 300:
        getSectionA(tickets)
    else:
        while tickets < 0 or tickets > 300:
            print('Invalid, enter a value from  0 to 300')
            tickets = int(input('Enter amount of tickets sold: '))
        getSectionA(tickets)

或者更好的是,整合逻辑,以便 no if no else。

if section == 'A':
    while tickets < 0 or tickets > 300:
        print('Invalid, enter a value from  0 to 300')
        tickets = int(input('Enter amount of tickets sold: '))
    getSectionA(tickets)

或者更好的是,编写一个将为您执行输入解释逻辑的函数,这样您就不必为每个部分重写它:

def get_value(message, min_value, max_value):
    while True:
        value = int(input(message))
        if min_value <= value <= max_value:
            return value
        else:
            print("Invalid, enter a value from {} to {}".format(min_value, max_value))

#later, in `main` after getting the seating section
prompt = "Enter the amount of tickets sold: "

if section == "A":
    getSectionA(get_value(prompt, 0, 300))
if section == "B":
    getSectionB(get_value(prompt, 0, 500))
if section == "C":
    getSectionC(get_value(prompt, 0, 200))

更好的是,将特定于每个部分的所有信息存储在一个字典中,因此您不需要为每个部分编写单独的函数和ifs:

#in `main` after getting the seating section
max_seats = {"A": 300, "B": 500, "C": 200}
cost_per_ticket = {"A": 20, "B": 15, "C": 10}
tickets = get_value("Enter the amount of tickets sold: ", 0, max_seats[section])
print("Your section revenue is", tickets * cost_per_ticket[section])

答案 1 :(得分:0)

问题是你的'getSection'函数是在调用它们的代码之后编写的。如果你在while循环之前剪切并超过'getSection'函数,它运行正常!

答案 2 :(得分:0)

间距不正确,因此有点难以阅读。既然你在学习,我会给你一些提示。

你有不必要的功能。你不需要一个简单乘法的函数。

通常你会使用switch语句而不是所有的if语句,python没有开关,但它有一个字典。

无需多次调用相同的输入函数。创建循环,使它们包含初始输入调用。这可以减少很多代码。

我真的很喜欢我的风格。你的代码工作正常,并没有任何问题。我只是想告诉你如何压缩代码并节省时间使其过于复杂化。

import sys

def calculateRevenue(section=None, tickets=None):
    """Calculate the revenue for a seating section.

    Args:
        section (str): Seating Section values (A, B, C)
        tickets (int): Number of seats sold.
    """

    while section != "A" and section != "B" and section !="C":
        if section != None: # Check if user input has been given
            print("Invalid Selection!")
        section = input('Enter desired seating section (A, B, C): ')
    # end section validation

    section_info = {
                  "A": [300, 20],
                  "B": [500, 15],
                  "C": [200, 10],
                  }.get(section)

    while tickets == None or tickets < 0 or tickets > section_info[0]:
        if tickets != None: # Check if user input has been given
            print("Invalid value! There are not that many seats available for that section!")
        tickets = int(input('Enter the amount of tickets sold: '))            
    # end tickets validation

    result = tickets * section_info[1]
    return result
# end main

def main():
    section = None
    tickets = None

    # Parse command line arguments
    cmd_line_len = len(sys.argv)
    if cmd_line_len >= 2:
        section = sys.argv[1]
    if cmd_line_len >= 3:
        tickets = int(sys.argv[2])

    result = calculateRevenue(section, tickets)
    print('Your section revenue is ', result)
# end main

if __name__ == "__main__":
    main()

这将使您的代码可重用,并且您可以在命令行上使用它。