SyntaxError:编译单个python语句时发现多个语句

2024-09-27 00:22:14 发布

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

endFlag = False
while endFlag == False:
     fruits= ['apple','cherry','banana','kiwi', 'lemon','pear', 'peach','avocado']
     num = int(input('please select a fruit with the number associated with it   ' ))
     if num == 0:
            print (fruits[0])
     elif num ==1:
            print(fruits[1])
     elif num == 2:
           print(fruits[2])
     elif num == 3:
            print(fruits[3])
     elif num == 4:
           print(fruits[4])
     elif num == 5:
          print(fruits[5])
      elif num == 6:
         print (fruits[6])
    elif num == 7:
        print(fruits[7], ',please enjoy your fruit!')
    else:
print('enter another fruit please, that one is not available')
VendingMachine = input("would you like to repeat the program again? Yes/No  ")
if VendingMachine == 'N':
   endFlag = True

这段代码显示“SyntaxError:编译单个语句时发现多个语句”,我需要帮助,因为我不知道为什么


Tags: thefalseinputifwith语句numprint
1条回答
网友
1楼 · 发布于 2024-09-27 00:22:14

问题可能是您最后所做的识别操作。if、elif和else应具有相同的标识

此外,还可以对代码进行如下改进:

#put fruits outside the loop so it only runs once
fruits= ['apple','cherry','banana','kiwi', 'lemon','pear', 'peach','avocado']
endFlag =  False

while not endFlag:
    num = int(input('please select a fruit with the number associated with it')

    if num >= 0 and num<len(fruits): #You can also use try/except here
        print(fruit[num])
    else:
        print('enter another fruit please, that one is not available')

    VendingMachine = input("would you like to repeat the program again? Yes/No ")

    if VendingMachine[0] == 'N': #if user input is 'No' your code fails
        endFlag = True

相关问题 更多 >

    热门问题