Python 3.6.2循环不像我想的那样工作

2024-04-28 23:48:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在为我的GCSE课程写一个代码,我的for循环也包含了if-else语句。 我已经做了一个类似的代码在程序的早期,它的工作非常好,但由于某种原因,这部分没有,我想知道是否有人可以帮助我。你知道吗

我想做的是做一个测验类型的程序,我需要帮助的部分是选择用户想做的主题。 用户必须输入他们喜欢的主题,但是如果他们输入错误的主题,或者输入无效的内容,那么程序应该允许用户再次输入。 到目前为止,如果您第一次正确输入主题,程序将进入下一阶段。 但是,如果第一次输入错误,它将要求用户重试。但如果第二次输入正确,它将再次要求用户重试。我不想让程序让用户再次键入主题,即使当用户正确键入主题时它应该是有效的,但我希望程序继续到下一阶段。你知道吗

可用主题:

subjects = []

algebra = ("algebra")
computing = ("computing")

subjects.append(algebra)
subjects.append(computing)

我需要帮助的部分:

with open("student_file.csv", "a+") as studentfile:
    studentfileReader = csv.reader(studentfile, delimiter = ',')
    studentfileWriter = csv.writer(studentfile, delimiter = ',')

print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
ChosenSubject.lower()

for i in range(2): 
    if ChosenSubject in subjects:
        print("\n")
        break

    else:
        print("\nPlease try again.")
        ChosenSubject == input("What subject would you like to do?")
        ChosenSubject.lower()

if ChosenSubject in subjects:
    print("working")

else:
    print("You keep typing in something incorrect.\nPlease restart the program.")

Tags: csv代码用户in程序主题forif
3条回答

这不是一个最佳的解决方案,但由于你的学习,我会尽量保持接近你的解决方案。您的问题是调用ChosenSubject.lower()不会更改ChosenSubject中的实际值。你知道吗

下面是一个工作示例:

print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")

subjects = ["algebra", "computing"]
for i in range(2): 
    if ChosenSubject.lower() in subjects:
        print("\n")
        break

    else:
        print("\nPlease try again.")
        ChosenSubject = input("What subject would you like to do?") #not '=='


if ChosenSubject.lower() in subjects:
        print("working")

else:
    print("You keep typing in something incorrect.\nPlease restart the program.")

这来自doc

This method returns a copy of the string in which all case-based characters have been lowercased.

for循环只是在对象集合上迭代。考虑一个列表my_list = ['a', 'b', 'c']。在my_list上使用for循环的每次迭代中,它都按顺序获取一个元素,而不重复。range(2)等价于[0, 1]。你知道吗

试试这个:

print("Available subjects:\n-Algebra\n-Computing\n")


for i in range(2): 
    # `i` is 0 on first iteration and 1 on second. We are not using `i` anywhere since all we want is to loop :) 
    chosen_subject = input("What subject would you like to do? ")

    if chosen_subject.lower() in subjects:
        print("\n")
        break

if chosen_subject.lower() in subjects:
    print("working")

else:
    print("You keep typing in something incorrect.\nPlease restart the program.")

在else块中,可能需要将“==”替换为“=”。你知道吗

你是想让用户试两次还是一直问直到他们回答正确?(后者是我从你的问题中推断出来的,因此我建议使用continue)

相关问题 更多 >