我如何继续循环执行相同的程序,以便用户可以输入任意数量的内容?

时间:2019-04-06 20:09:16

标签: python python-3.x loops input

因此,我对python还是很陌生,我正在尝试创建一个程序,用户可以在该程序中输入a-g范围内的音乐和弦,然后接收有关该和弦的信息,例如什么音符使和弦。我所坚持的是让用户无需重新启动程序即可了解另一个和弦。因此,一旦他们完成输入后,我希望能够再次提出输入问题。

我真的没有做太多尝试,因为我不知道从哪里开始。

chord = input('What chord would you like to find out about? (A-G) ')
if chord.upper() == 'D':
    print(f"The D chord is made up of three notes: {d_chord}")
elif chord.upper() == 'G':
    print(f"The G chord is made up of three notes: {g_chord}")

所以基本上,当用户完成转换后,我希望它循环回到顶部,以便他们可以再次使用而无需重新启动程序

1 个答案:

答案 0 :(得分:0)

将您的代码包装到无限while循环中:

while True:
    chord = input('What chord would you like to find out about? (A-G) ')
    if chord.upper() == 'D':
        print(f"The D chord is made up of three notes: {d_chord}")
    elif chord.upper() == 'G':
        print(f"The G chord is made up of three notes: {g_chord}")

如果只想运行特定次数,可以将for循环与range一起使用:

for i in range(0,5): # loop will run 5 times
    chord = input('What chord would you like to find out about? (A-G) ')
    if chord.upper() == 'D':
        print(f"The D chord is made up of three notes: {d_chord}")
    elif chord.upper() == 'G':
        print(f"The G chord is made up of three notes: {g_chord}")