为什么输入名称循环保持无限并且不让其余代码运行?

时间:2018-12-04 04:48:34

标签: python

这是我计算学生的gpa的代码,由于某种原因,当您输入学生ID时,它会直接返回到询问姓名。

gradeA = 4

gradeB = 3

gradeC = 2

gradeD = 1

gradeF = 0

#loop to keep asking for the right input
rerun = "Yes"
while rerun == "Yes":
    option = input ("Are you a student?: ")
    while option != "No" and option != "Yes":
        option = input ("Are you a student? Yes or No?: ")

    name = input ("Enter name: ")
    iD = int ( input ("Enter ID: "))

while iD < 1 or iD > 9999:
    iD = int ( input ("Enter valid ID: "))

#loop to ask for right input for credits

credit = int ( input ("\nNumber of credits for class: "))
while credit < 1 or credit > 7:
    credit = int ( input ("Enter vaid number of credits: "))

#input course name
course = input("\nName of course: ")

grade = input("\nEnter grade for course: ")

我认为这里是代码混乱的时候,我可能是错的,但是谁能帮助我弄清楚为什么输入名称和ID的循环是无限的。

#loop to ask for right grade entry
while grade != "A" and grade != "B" and grade != "C" and grade != "D" and 
grade != "F":
    grade = input("Enter valid grade: ")

因此,其余代码将无法运行。

if grade == "A":
    message = "Congragulations, keep it up!"
    gpa = float(gradeA)
elif grade == "B":
    message = "You passsed!"
    gpa = float(gradeB)
elif grade == "C":
    message = "You made it but do better!"
    gpa = float(gradeC)
elif grade == "D":
    message = "Near FAILING!"
    gpa = float(gradeD)
else:
    message = "You failed."
    gpa = float(gradeF)

print(" ")
print("="*60)
print("Name: ", format(name, ">45s"))
print("\nID: ", format(iD, "46d"))
print("="*60)
print("\nCourse: ", format(course, ">44s"))
print("\nCredit: ", format(credit, "39d"))
print("Final grade: ", format(grade, ">34s"))
print("GPA: ", format(gpa, "44.1f"))
print(" ")
print(message)

#loop to ask if another student will use the program
rerun = input ("Will you perform another student lookup? Yes or No? ")

2 个答案:

答案 0 :(得分:0)

这里:

while option == "Yes":
    name = input ("Enter name: ")
    iD = int ( input ("Enter ID: "))

您永远不会为代码提供跳出while循环的选项。我对为什么需要while循环感到困惑,只需使用if语句即可:

if option == "Yes":
    name = input ("Enter name: ")
    iD = int ( input ("Enter ID: "))

答案 1 :(得分:0)

原因是option的值为Yes,因此它将继续循环直到条件变为false。

while option == "Yes":
    name = input ("Enter name: ")
    iD = int ( input ("Enter ID: "))

使用if条件仅输入一次,而不是while循环。

gradeA = 4

gradeB = 3

gradeC = 2

gradeD = 1

gradeF = 0

#loop to keep asking for the right input
rerun = "Yes"
while rerun == "Yes":
    option = input ("Are you a student?: ")
    while option != "No" and option != "Yes":
        option = input ("Are you a student? Yes or No?: ")


    #Insert whole code before this, have trimmed the code
    rerun= input("Will you perform another student?Yes or No?: ")