[英]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
一些一般性观察:
f"{code}"
几乎肯定不会做你认为应该做的事情。)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.