写入for循环中的文件,未定义def

问题描述 投票:0回答:2

在Python中,这不能循环多次,也无法在def中找到ID号。每次尝试运行程序时,都会出现错误“ NameError:未定义名称'askname'”,并且在文本文件中仅保留最新数据-我希望#def new_booking的输出是连续将数据保留在文件中,但实际输出是将数据保留在文件中仅一句话-我希望#def pre_booked的输出是从文件中提取数据,但实际输出是“ NameError:名称'askname'未定义”]

import random

# total=0
# people=0
total1 = 0
total2 = 0


# mini bar
def mini_bar():
    mini_bar_total = 0
    print("£50 for the Bar")
    askbar = input("Would you like a mini bar? Y/N")
    if askbar.upper() == "Y":
        mini_bar_total = mini_bar_total + 50
    return mini_bar_total


# breakfast
def breakfast(people, asknights):
    breakfast_total = 0
    print("£25 for breakfast")
    askdinner = input("Would you like dinner? Y/N")
    if askdinner.upper() == "Y":
        breakfast_total = (people * 25) * asknights
        print("total: £", breakfast_total)
    return breakfast_total


# dinner
def dinner(people, asknights):
    dinner_total = 0
    print("£25 for Dinner")
    askdinner = input("Would you like dinner? Y/N")
    if askdinner.upper() == "Y":
        dinner_total = (people * 25) * asknights
    return dinner_total


# number customers
def num_customers():
    customer_total = 0
    print("£50 an Adult")
    askadult = int(input("How many adults? "))
    customer_total = askadult * 50
    print("total: £", customer_total)
    print("£25 a Child")
    askchild = int(input("How many children? "))
    customer_total = (askchild * 25) + customer_total
    print("total: £", customer_total)
    return customer_total, askadult, askchild


# number of nights (multiplier)
def num_nights(customer_total):
    nights_total = 0
    waiting = True
    while waiting == True:
        try:
            asknights = int(input("How many nights are you staying for? "))
            nights_total = customer_total * asknights
            print("total: £", nights_total)
            break
        except ValueError:
            print("invalid input!")
    return nights_total, asknights


# New Booking *********
def new_booking():
    askname = str(input("Please enter your name? "))
    idnumber = random.randint(100, 999)
    customer_total, numAdults, numChild = num_customers()
    Num_people = numAdults + numChild
    nights_total, asknights = num_nights(customer_total)
    askbar = mini_bar()
    askbreakfast = breakfast(Num_people, asknights)
    askdinner = dinner(Num_people, asknights)
    total = askdinner + askbreakfast + askbar + asknights
    detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner)
    for i in detailslist:
        f = open('newbooking.txt', 'w')
        f.write(str(detailslist) + '\n')
        print(i)
    print("your total amount is: £", total)
    print("your Name & ID number is: ", askname, idnumber)

# Pre booking ***** is not defind
def pre_booked():
    name = input("enter your name or ID number: ")
    if name == (askname) or (idnumber):
        detailslist = [idnumber, askname, askadult, askchild, asknights, askbar, askbreakfast, askdinner]
        for i in detailslist:
            print(i)
        print("total: £", total)

# main menu, start of program.
def main_menu():
    print("##################### WELCOME TO BAY HOTEL ###########################")
    print('''Please see what is available at the Hotel,\nAdult Prices per night: £50pp,\nChild price: £25pp,\nMiniBar price: £50 per room,\nBreakfast: £20pp,\nDinner: £25pp''')
    while True:
        prebook = input("Have you booked? Y/N")
        if prebook.upper() == "N":
            new_booking()
        elif prebook.upper() == "Y":
            pre_booked()


main_menu()

- I expect the output of #def new_booking to be Keep data in files continuously but the actual output is keep data in files just one sentence
- I expect the output of #def pre_booked to be Extract data from file but the actual output is "NameError: name 'askname' is not defined"
python
2个回答
0
投票

我认为这是因为您在文件中写入数据的方式。

使用文件有3个步骤:

1)打开文件

2)读取[从] /写入[至]​​

3)关闭文件

第三步是您未处理的步骤。

您想在文件中写入一个列表,并且每次迭代都在打开该文件。一次可以这样做不是一个好主意(打开和关闭文件都有开销)。

我更改了您的某些new_booking函数,并将其写在这里:

# New Booking *********
def new_booking():
    askname = str(input("Please enter your name? "))
    idnumber = random.randint(100, 999)
    customer_total, numAdults, numChild = num_customers()
    Num_people = numAdults + numChild
    nights_total, asknights = num_nights(customer_total)
    askbar = mini_bar()
    askbreakfast = breakfast(Num_people, asknights)
    askdinner = dinner(Num_people, asknights)
    total = askdinner + askbreakfast + askbar + asknights
    detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner)

    # I handled opening and closing file with [python with statement]
    # It close files automatically at the end
    with open('newbooking.txt', 'w') as f:    
        for i in detailslist:
            f.write(str(detailslist) + '\n')
            print(i)
    print("your total amount is: £", total)
    print("your Name & ID number is: ", askname, idnumber)


0
投票

这里的问题是,您尚未在pre_booked()函数中实际定义askname,因此您无法与其进行比较。在new_booking()中,您要使用askname = str(input("Please enter your name? "))来输入用户名,但是在pre_booked()情况下,您不需要输入用户名,因此您必须先从某个位置获取值才能在其中使用它。

[看到您将new_booking()保存到文件中,您可能希望像这样从文件中加载数据:

accounts = []
with open(r"<FILEPATH", "r") as booking_file:
   for line in booking_file:
       accounts.append(line)

在new_booking函数中,最好将所有相关数据逐行放置,甚至使用字典,这样您以后就可以确定哪些值属于同一行,而不是将所有值都写到自己的行中。因此,您可能需要这样做:

with open('newbooking.txt', 'w') as booking_file:    
    f.write(detailslist)

然后,您可以逐行阅读,并且可能使用” eval()”来从字符串中获取列表或字典,或者至少您知道一行中的值稍后会归为一体。

您可能还想考虑在预订文件中使用“ a”作为附加,而不是使用w进行写入,具体取决于您是要在文件中还是多个预订值。

© www.soinside.com 2019 - 2024. All rights reserved.