【问题标题】:(Python) What is wrong in my code causing my program to crash with relation to line 33(Python)我的代码有什么问题导致我的程序崩溃与第 33 行有关
【发布时间】:2022-12-04 07:48:03
【问题描述】:

程序会第一次运行,但在第二次循环中有时会崩溃。我注意到它可能与第 33 行有关,可以在其中选择礼帽。 错误:“IndexError:列表索引超出范围”

import random

def playloop(): # creating a loop to play again if wanted
    print('\nDo you want to try for a different color? Y or N')

    while True:
        newGame = input()
        if newGame.upper() == 'N' or newGame.upper() == 'NO':
            print('\nEnjoy your manicure! Thanks for playing.')
            # exit game
            exit()
        elif newGame.upper() == 'Y' or newGame.upper() == 'YES':
            print('\nGreat! Let\'s go again.')
            seasons() # going back to seasons function as they have already established they wear nail polish.
        elif newGame.upper() != ('N', 'NO', 'Y', 'YES') or newGame.isalnum():
            print('\nPlease enter a valid input. Y or N.')
            # proceed back to start to enter correct input
            continue

#creating the topper list
toppers = ['holographic', 'flakies', 'glitter', 'microshimmer']

def topper(): #topper function (this is what makes a nail polish pretty!)
    print('\nDo you want a nail polish topper?')
    while True:
        topper = input() #getting input
        # random number between 1-3 for topper grab
        randomTop = random.randint(1,4)
        if topper.upper() == 'N' or topper.upper() == 'NO':
            print('A clear glossy top coat it is!')
            break
        elif topper.upper() == 'Y' or topper.upper() == 'YES':
            print('The topper you should use is ' + toppers[randomTop] + '.')
            break
        elif topper.upper() != ('N', 'NO', 'Y', 'YES') or topper.isalnum():
            print('\nPlease enter a valid input. Y or N.')
            continue
    playloop() # going to playloop to continue or exit game

#creating the color lists for the seasons
#each list has 7 colors
springColors = ['peach', 'light pink', 'mint green', 'baby blue', 'nude', 'soft yellow', 'lavender']
summerColors = ['white', 'yellow', 'bright red', 'orange', 'fuchsia', 'turquoise', 'royal blue']
fallColors = ['brown', 'mustard yellow', 'burnt orange', 'hunter green', 'mauve', 'maroon', 'black']
winterColors = ['white', 'black', 'dark grey', 'ruby red', 'dark purple', 'emerald green', 'dark blue']

# creating the season type functions, using the randomColor int to pick from the lists
def spring(randomColor): #spring
    # generate the random color from the list
    print('\nThe color you should pick is ' + springColors[randomColor] + '.')
    topper()
    
def summer(randomColor): #summer
    # generate the random color from the list
    print('\nThe color you should pick is ' + summerColors[randomColor] + '.')
    topper()

def fall(randomColor): #fall
    # generate the random color from the list
    print('\nThe color you should pick is ' + fallColors[randomColor] + '.')
    topper()
    
def winter(randomColor): #winter
    # generate the random color from the list
    print('\nThe color you should pick is ' + winterColors[randomColor] + '.')
    topper()

def seasons():
    print('\nWhat season is it? Spring, Summer, Fall, Winter?')
    
    while True:
        curSeason = input() #getting season input
        # random number between 1-7 for color grab
        randomColor = random.randint(1,8)
        if curSeason.lower() == 'spring':
            spring(randomColor)
        elif curSeason.lower() == 'summer':
            summer(randomColor)
        elif curSeason.lower() == 'fall':
            fall(randomColor)
        elif curSeason.lower() == 'winter':
            winter(randomColor)
        elif curSeason.lower() != ('spring', 'summer', 'fall', 'winter') or curSeason.isalnum():
            print('\nPlease enter a valid season. Spring, Summer, Fall, Winter')
            continue

# starting the program function
def start():
    print('\nDo you wear nail polish: Y or N?') # basic question to start program

    while True:
        userPref = input() # getting input
        if userPref.upper() == 'N' or userPref.upper() == 'NO':
            #convert input to upper and accept n or no
            print('\nI think you\'re playing the wrong game.')
            # exit game
            exit()
        elif userPref.upper() == 'Y' or userPref.upper() == 'YES':
            #convert input to upper and accept y or yes
            print('\nTime for more questions.')
            seasons() #bring in the next function for seasons
        elif userPref.upper() != ('N', 'NO', 'Y', 'YES') or userPref.isalnum():
            # catching invalid input
            print('\nPlease enter a valid input. Y or N.')
            # proceed back to start to enter correct input
            continue
        


print('Welcome to Lisa\'s Midterm Project!')
print('Nail Polish Picker Game') # intro

start()

由于如果用户愿意,程序可以中断退出,因此预计程序可以无限循环直到他们准备好退出。虽然第一个循环工作正常,但随后的试验崩溃了。特别是“fall/autumn”选项似乎总是在第二次迭代时导致崩溃。

任何帮助表示赞赏。 :)

【问题讨论】:

    标签: python index-error


    【解决方案1】:
    toppers = ['holographic', 'flakies', 'glitter', 'microshimmer']
    
    randomTop = random.randint(1,4)
    print('The topper you should use is ' + toppers[randomTop] + '.')
    

    toppers 是一个包含四个项目的列表。 Python 列表的索引从零开始,因此有效索引为 0-3。

    但是您要从 1 到 4 中随机选择一个数字。如果您碰巧选择了 4,那就超出了范围。

    使用random.randint(0,3)

    更好的是,使用random.choice(toppers),这样您根本不必担心索引值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      • 2018-10-15
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      相关资源
      最近更新 更多