需要For循环以允许用户退出

时间:2019-04-29 00:40:14

标签: python python-3.x for-loop

我对python还是很陌生,所以我知道我的代码有点难看。 本质上,我正在为课程搜索创建一个模拟数据库。我试图允许用户输入“退出”以退出提示,或者只是输入另一门课程,这将为他们提供所需的直接信息。

我已经尝试了while循环以及启动循环,但是对于如何配置代码我有些困惑。到目前为止,这是我可以使用的最接近的功能,但是显然,“中断”将只允许对提示进行一次额外的迭代,而不是允许用户输入任意多次的信息。 >

courseInfo = {"CS101": {"room": "3004", "Name": "Haynes", "Time": "8:00 a.m."}, "CS102": {"room": "4501", "Name": "Alvarado", "Time": "9:00 a.m."}, 
    "CS103": {"room": "6755", "Name": "Rich", "Time": "10:00 a.m."}, "NT110": {"room": "1244", "Name": "Burke", "Time": "11:00 a.m."}, 
"CM241": {"room": "1411", "Name": "Lee", "Time": "1:00 p.m."} }

courseInfo = {k.lower(): v for k, v in courseInfo.items()} 

for courseNumber in courseInfo:    
    courseNumber = input("\nEnter the course number: ").lower()
    print("\nThe course information for coourse # ",courseNumber, "is as follows:")
    print("Room #:", courseInfo[courseNumber] ["room"])
    print("Instructor: ",courseInfo[courseNumber] ["Name"])
    print("Time: ", courseInfo[courseNumber] ["Time"])
    done = input("\nEnter the course number or enter exit to leave: ")
    if done != "exit":
    print("\nThe course information for coourse # ",courseNumber, "is as follows:")
    print("Room #:", courseInfo[courseNumber] ["room"])
    print("Instructor: ",courseInfo[courseNumber] ["Name"])
    print("Time: ", courseInfo[courseNumber] ["Time"])
    break
else:
    print("Program terminated normally")
    break

2 个答案:

答案 0 :(得分:0)

使用while循环:

def get_input():
    return input("Course nr or exit: ")

user_input = get_input()
while user_input.lower() != 'exit':
    print("Some info: ", courseInfo.get(user_input, "course not found"))
    user_input = get_input()

这会将输入分配给user_input,虽然它不等于'exit',但是它将首先打印出相关信息,然后将user_input重新分配给下一个输入,它将然后再次检查。

请注意,我修改了字典访问权限。使用dict.get(key[, default])可以阻止KeyError。如果dict.get(key[, default])的第一个参数不在dict中,它将返回Nonedefault自变量。 如果您想在用户输入无效的课程号时打印有关所有可用课程的信息,则可以使用if语句,如下所示:

if user_input in courseInfo:  # checks if courseInfo has a key user_input
    print("Some info:", courseInfo[user_input])  # if it does, print the relevant info
else:  # otherwise:
    print("These are the available courses:", ', '.join(courseInfo.keys()))  # print out the available courses (or whatever you want)

此外,请小心使用for ... elsewhile ... else循环。这种语法对于Python来说是非常独特的,并且经常会引起混乱,因为程序员可以在实际输入else块时做出两个完全合理但互斥的假设。

答案 1 :(得分:0)

courseInfo = {"CS101": {"room": "3004", "Name": "Haynes", "Time": "8:00 a.m."}, "CS102": {"room": "4501", "Name": "Alvarado", "Time": "9:00 a.m."}, 
    "CS103": {"room": "6755", "Name": "Rich", "Time": "10:00 a.m."}, "NT110": {"room": "1244", "Name": "Burke", "Time": "11:00 a.m."}, 
"CM241": {"room": "1411", "Name": "Lee", "Time": "1:00 p.m."} }

# Use this to keep the loop going
exit_flag = False

courseNumber = input("\nEnter the course number: ").strip().upper()
while not exit_flag:
    # Always assume the user will enter something not in the dict
    course = courseInfo.get(courseNumber, None)
    if course:
        print("\nThe course information for course # ",courseNumber, "is as follows:")
        print("Room #:", courseInfo[courseNumber] ["room"])
        print("Instructor: ",courseInfo[courseNumber] ["Name"])
        print("Time: ", courseInfo[courseNumber] ["Time"])
    else:
        print("\nCourse not found")

    courseNumber = input("\nEnter another course number or enter exit to leave: ").strip().upper()
    if courseNumber == "EXIT":
        exit_flag = True