【问题标题】:If statements to find age in a list如果语句在列表中查找年龄
【发布时间】:2018-03-12 19:26:18
【问题描述】:

我做了三个输入(名字、姓氏和年龄)并将它们放入一个文件中。最后一部分是如果年龄超过 18 岁,则使用此信息打印出某人的输入。我曾尝试使用字典,但不知何故我做错了。我可以使用列表或文件吗?我该怎么做才能使用使用该年龄的 if 语句来确定是否应打印详细信息。示例如下。

def details():
    c = input('Press 1 to enter details, press 2 to browse users or press 3 to check age')
    if c == '1':
        firstname = input('Please enter your firstname')
        surname = input('Please enter your surname')
        age = input('Please enter your age')
        myfile=open('details.txt', 'at')
        myfile.write(firstname + '\n')
        myfile.write(surname + '\n')
        myfile.write(age + '\n')
        myfile.close()
        detail2 = {'Fname': firstname, 'Sname': surname, 'Age': age}
        details()
    elif c == '2':
        detail2 = {'Fname': firstname, 'Sname': surname, 'Age': age}
        read()
    elif c == '3':
        detail2 = {'Fname': firstname, 'Sname': surname, 'Age': age}
        read18()
    else:
        details()
def read():
    myfile=open('details.txt', 'rt')
    x = myfile.read()
    print(x)
def read18():
    for item in detail2:
        if Age> 18:
            print('Over 18') 
        elif Age< 18:
            print('Under 18')
"""I need to know what to do so this will print the details. Just using over or under 18 as a starting point"""

details()

【问题讨论】:

    标签: python list file if-statement input


    【解决方案1】:

    您试图在 read18() 中使用局部变量 detail2,但它超出了范围。您可能希望打开文件并读取现有详细信息以评估您的“if”循环条件。

    【讨论】:

      【解决方案2】:

      好的,我认为您的代码可以进行一些改进。

      1. 如果你继续调用 details(),你最终会达到允许的最大递归的限制。为此,您可以将代码放入 while True: 循环并调用 break 来中断它
      2. input() 返回一个字符串,但年龄通常是一个数字(integer),因此最好使用int() 将字符串转换为整数。可以直接在input() -> age = int(input('Please enter your age: '))上使用
      3. 既然您有一个list 用户,您应该使用list 来跟踪他们。如果每个用户都有名字、姓氏和年龄,您调用使用字典来保存每个用户的数据,然后将此字典添加到您的所有用户列表中
      4. 对于写入/读取文件,Python 有一个内置的 with 语句,它将为您关闭文件
      5. 如果要快速保存列表/字典,可以使用 JSON

      如果您将使用所有这些建议,您可以获得类似于此的代码:

      import json
      
      FILE_SAVEFILE = "details.json"
      
      list_persons = []  # list with user's data
      
      def data_save():
          """
          Saves user's data into FILE_SAVEFILE
          """
          with open(FILE_SAVEFILE, 'wt') as f:
              json.dump(list_persons, f)
      
      def data_load():
          """
          Loads data into list_persons from FILE_SAVEFILE
          """
          global list_persons
          with open(FILE_SAVEFILE, 'rt') as f:
              list_persons = json.load(f)
      
      while True:
          c = input('Press 1 to enter details, press 2 to browse users or press 3 to check age: ')
          if c == "1":
              new_person_data = {
                  "firstname": input('Please enter your firstname: '),
                  "surname": input('Please enter your surname: '),
                  "age": int(input('Please enter your age: ')),
              }
              list_persons.append(new_person_data)
              data_save()
              continue
          if c == "2":
              data_load()
              for dict_user in list_persons:
                  print('Firstname: ' + dict_user["firstname"])
                  print('Surname: ' + dict_user["surname"])
                  print('Age: ' + str(dict_user["age"]))
              continue
          if c == "3":
              for dict_user in list_persons:
                  str_agestr = " is over 18" if dict_user["age"] > 18 else " is under 18"
                  print(dict_user["firstname"] + " " + dict_user["surname"] + str_agestr)
              continue
      

      【讨论】:

        【解决方案3】:

        可以对您的代码进行许多改进,实际上 E. Aho 的答案使用了其中的一些,但如果您是 python 新手,它们可能会有点令人困惑。 稍微调整你的代码并添加一些 cmets:

        def details():
            c = input('Press 1 to enter details, press 2 to browse users or press 3 to check age: ')
            if c == '1':
                firstname = input('Please enter your firstname: ')
                surname = input('Please enter your surname: ')
                age = input('Please enter your age: ')
                myfile=open('details.txt', 'at')
        
                # write data as a single record
        
                myfile.write(firstname + ',' + surname + ',' + age + '\n')
                myfile.close()
                details()
        
            elif c == '2':
                read()
            elif c == '3':
                read18()
            else:
                details()
        
        def read():
            myfile=open('details.txt', 'r')
        
            # read file line by line
        
            x = myfile.readlines()
            for item in x:
                print (item.strip()) #Strip newline
            myfile.close()
        
        def read18():
            myfile=open('details.txt', 'r')
            x = myfile.readlines()
            for item in x:
        
                # split each line into component parts, splitting on comma separator and strip newline
        
                firstname,surname,age = item.strip().split(',')
                detail2 = {'Fname': firstname, 'Sname': surname, 'Age': int(age)}
                if detail2['Age'] > 17:
                    print('Over 18 via Dict')
                else:
                    print('Under 18 via Dict')
        
                # or dispense with the dictionary
        
                if int(age) > 17:
                    print(firstname,surname,'at',age,'is 18 or over')
                else:
                    print(firstname,surname,'at',age,'is under 18')
            myfile.close()
        """I need to know what to do so this will print the details. Just using over or under 18 as a starting point"""
        
        details()
        

        【讨论】:

        • 每次我尝试浏览用户时都会出现错误消息,并在底部显示“年龄未定义”。即使我先添加用户然后浏览用户,错误消息也是一样的。知道如何摆脱这个吗?
        • 我假设您在某处出错,因为浏览函数read() 没有引用变量age 它只打印item
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多