简体   繁体   中英

Running a function inside of an if statement

I have a program that is supposed to show all classes in the external .txt file when the user presses "V", and is supposed to allow the user to lookup a specific class based off of its course code (EX. user types csce101 and it will print "Introduction to computer concepts"). However, I can't get the V and L functions to work properly. As it sits currently, the V function is only working because I called a break... but after it prints all the classes, it asks the user for a course code when it is not supposed to. That is what the L function is supposed to do. I am unsure on how to call a function inside of an if/elif loop. The function name just comes up as undefined. Is it possible with the way I have the code setup?

Python Code:

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 file contents

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

Some general observations:

  • Functions, like any other object, need to be defined before they are referenced/used. You aren't violating this, but you will be if you fill in the rest of your while-loop. Ideally, you'll want a main entry point for your program, so that it's clear in what order things are being executed, and your functions are guaranteed to be defined by the time flow-of-execution reaches the lines on which your functions are called.
  • It would make sense to define one function for each corresponding command type (except for quit). You were on the right track here.
  • A couple questionable/redundant instances of f-strings ( f"{code}" almost certainly doesn't do what you think it should.)
  • Prefer snake_case over camelCase when writing Python source code.
  • Your V command will terminate the loop (and the program) prematurely. What if the user wants to print all courses, then a description?

Here are my suggestions incarnate:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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