在函数中使用函数-Python

时间:2018-12-01 00:39:19

标签: python function loops

我只是想知道是否有人可以帮助我解决这个问题。我目前正在为大学比赛设计一个计分程序,这是我学校项目的一部分。

现在,我在单个.py文件中有一个主菜单,但在另一个.py文件中有注册学生的功能。到目前为止,我已经设法将函数调用到主菜单程序中并按照我期望的方式工作。但是,我经历的一件事是该函数只会不停地循环自身并且不会停止。

因此,我在注册学生功能的末尾调用了主菜单功能。这样做的作用是允许您注册学生(然后将其姓名附加到文本文件中),然后将您发送回主菜单,以供用户选择其他操作。

如果我然后尝试再次输入1,它会显示一个很长的回溯列表,最后出现一个错误:

ModuleNotFoundError: No module named 'Function_1_reg_student.py';
    'Function_1_reg_student' is not a package.

我如何获得允许我注册学生的程序,可能会问用户是否要注册另一个学生,或者如果用户拒绝则返回主菜单?

如果这没有道理,我深表歉意。我对此非常陌生,并且发现很难解释我的处境以及我想做什么!

下面是我的两个文件:

Main_menu.py:

def main_menu():
    print(""" Welcome to the main menu.              
    |  (1.)     Register a student|                      
    |  (2.)     Score a student   |                                         
    |  (3.)     Leaderboard       |                                             
    |  (4.)     Quit              |
    """)

    while True:
        answer=input("Please enter a number between 1-4: ")
        if answer=="1":
            from Function_1_reg_student.py import reg_solo
            continue
        elif answer=="2":
            print ("Call function 2")
            continue
        elif answer=="3":
            print ("Call function 3")
            continue
        elif answer=="4":
            print ("Quit")
            continue
        else:
            print("ERROR MESSAGE: Please enter in a number from 1 to 4")
            continue

main_menu()

Function_1_reg_student.py:

def reg_solo():
   while True:
      studentname=input("Please enter student name ")
      studentsurname=input("Please enter surname ")
      print("Name: "+studentname+" "+studentsurname)
      text_file=open("solo_students_reg.txt","a")


text_file.write(studentname+":"+studentsurname+":"+"0"+":"+studentname[:3]+    studentsurname[:3]+":"+"\n")
      text_file.close()
      print(studentname+" "+studentsurname+" has been registered")
      from MAIN_MENU.py import main_menu
reg_solo()

1 个答案:

答案 0 :(得分:1)

在导入模块或从模块导入时不包括文件扩展名。

执行以下操作:

from Function_1_reg_student import reg_solo

不是这样的:

from Function_1_reg_student.py import reg_solo
相关问题