繁体   English   中英

在 if 语句中运行函数

[英]Running a function inside of an if statement

我有一个程序应该在用户按下“V”时显示外部 .txt 文件中的所有类,并且应该允许用户根据其课程代码查找特定类(例如,用户键入 csce101 和它将打印“计算机概念简介”)。 但是,我无法让 V 和 L 功能正常工作。 就目前而言,V 函数仅在工作,因为我调用了一个中断……但是在它打印所有类之后,它会在不应该的时候要求用户提供课程代码。 这就是L函数应该做的。 我不确定如何在 if/elif 循环中调用函数。 函数名称只是未定义。 我的代码设置方式有可能吗?

蟒蛇代码:

while True:
    command = input("(V)iew, (L)ookup, or (Q)uit: ")

    if command == "v":
        break
    elif command == "l":
        print(f"{code}")
    elif command == "q":
        print("Goodbye!")
        quit()
    else:
        print("Invalid command")

def getCourses():
    courses = {}
    with open("assignments/assignment-19/courses.txt") as file:
        for line in file:
            data = line.split(':')
            code = data[0].strip()
            className = data[1].strip()
            courses[code] = className
        return courses

def getDescription(courseList):
    code = input("Enter course code: ").strip().lower()
    if code in courseList:
        print(f"{courseList[code]}")
    else:
        print(f"Sorry {code} is not in our system")


courseList = getCourses()
for classes in courseList:
    print(f"{classes}: {courseList[classes]}")


getDescription(courseList)

.txt 文件内容

csce101: Introduction to Computer Concepts
csce102: General Applications Programming
csce145: Algorithmic Design 1
csce146: Algorithmic Design 2
csce190: Computing in the Modern World
csce201: Introduction to Computer Security
csce204: Program Design and Development
csce205: Business Applications Programming

一些一般性观察:

  • 与任何其他对象一样,函数需要在被引用/使用之前定义。 您并没有违反这一点,但是如果您填写其余的 while 循环,您就会违反这一点。 理想情况下,您需要一个程序的主要入口点,以便清楚执行事物的顺序,并且保证您的函数在执行流到达您的函数所在的行时被定义叫。
  • 为每个相应的命令类型定义一个函数是有意义的(退出除外)。 你在这里走在正确的轨道上。
  • 几个有问题/冗余的 f 字符串实例( f"{code}"几乎肯定不会做你认为应该做的事情。)
  • 在编写 Python 源代码时,更喜欢snake_case不是camelCase
  • 您的V命令将提前终止循环(和程序)。 如果用户想打印所有课程,然后是描述怎么办?

以下是我的建议:

def get_courses():
    courses = {}
    with open("assignments/assignment-19/courses.txt", "r") as file:
        for line in file:
            data = line.split(":")
            code = data[0].strip()
            class_name = data[1].strip()
            courses[code] = class_name
    return courses

def display_courses(courses):
    for key, value in courses.items():
        print(f"{key}: {value}")

def display_description(courses):
    code = input("Enter course code: ").strip().lower()
    if code in courses:
        print(courses[code])
    else:
        print(f"Sorry, \"{code}\" is not in our system.")


def main():

    courses = get_courses()
    
    while True:
        command = input("(V)iew, (L)ookup or (Q)uit: ").lower()

        if command == "v":
            display_courses(courses)
        elif command == "l":
            display_description(courses)
        elif commany == "q":
            print("Goodbye!")
            break
        else:
            print("Invalid command.")
    # 'main' ends here

main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM