Python 避免使用/覆盖全局变量(以简单示例)
这是一个简单的程序: 询问用户想要多少张票 计算车票的费用 然后询问是否可以继续购买 我如何才能改变我做事的方式,而不必覆盖requestedTickets和costOfTickets全局变量? (如果用户回复“n”拒绝购买确认,则在确认功能中会覆盖它们。)Python 避免使用/覆盖全局变量(以简单示例),python,Python,这是一个简单的程序: 询问用户想要多少张票 计算车票的费用 然后询问是否可以继续购买 我如何才能改变我做事的方式,而不必覆盖requestedTickets和costOfTickets全局变量? (如果用户回复“n”拒绝购买确认,则在确认功能中会覆盖它们。) 我正在努力学习最佳实践。为了避免在这样一个简单的情况下使用全局函数,让函数返回它们生成的所有数据,并将它们需要的所有数据作为参数。这应该是一个简单的重构,下一步就是使用类。面向对象编程。 TICKETPRICE = 10 ticketsRe
我正在努力学习最佳实践。为了避免在这样一个简单的情况下使用全局函数,让函数返回它们生成的所有数据,并将它们需要的所有数据作为参数。这应该是一个简单的重构,下一步就是使用类。面向对象编程。
TICKETPRICE = 10
ticketsRemaining = 100
userName = input("What is your first name?: ")
print("There are " + str(ticketsRemaining) + " tickets remaining.")
def ticketsWanted(userName):
numOfTicketsWanted = input(
"Hey {} how many tickets would you like? : ".format(userName))
return int(numOfTicketsWanted)
requestedTickets = ticketsWanted(userName)
def calculateCost():
ticketQuantity = requestedTickets
totalCost = ticketQuantity * TICKETPRICE
return totalCost
costOfTickets = calculateCost()
def confirm():
global requestedTickets
global costOfTickets
tickets = requestedTickets
totalCost = calculateCost()
print("Okay so that will be " + str(tickets) +
" tickets making your total " + str(totalCost))
confirmationResponse = input("Is this okay? (Y/N) : ")
while confirmationResponse == "n":
requestedTickets = ticketsWanted(userName)
costOfTickets = calculateCost()
print("Okay so that will be " + str(requestedTickets) +
" tickets making your total " + str(costOfTickets))
confirmationResponse = input("Is this okay? (Y/N) : ")
confirm()
def finalStage():
print("Your order is being processed.")
finalStage()
TICKETPRICE = 10
ticketsRemaining = 100
userName = input("What is your first name?: ")
print("There are " + str(ticketsRemaining) + " tickets remaining.")
def ticketsWanted(userName):
numOfTicketsWanted = input(
"Hey {} how many tickets would you like? : ".format(userName))
return int(numOfTicketsWanted)
def calculateCost(n_tickets):
totalCost = n_tickets * TICKETPRICE
return totalCost
def confirm(userName):
n_tickets = ticketsWanted(userName)
totalCost = calculateCost(n_tickets)
print("Okay so that will be " + str(n_tickets) +
" tickets making your total " + str(totalCost))
confirmationResponse = input("Is this okay? (Y/n) : ")
while confirmationResponse == "n":
n_tickets = ticketsWanted(userName)
costOfTickets = calculateCost(n_tickets)
print("Okay so that will be " + str(n_tickets) +
" tickets making your total " + str(costOfTickets))
confirmationResponse = input("Is this okay? (Y/n) : ")
def finalStage():
print("Your order is being processed.")
confirm(userName)
finalStage()