首页 > 解决方案 > What is wrong with my code? Python. Trying to make a gamelist game

问题描述

I am learning python and want to learn from my mistake instead of just look at the course answer to this task.

I am trying to make a gamelist game. We have a list gamelist = [1,2,3] and the user will then get the opportunity to change a value in the list. The user will be able to choose between 0-2 (index position in the list) and after the user will be able to input a value. After this iteration, the gamelist will update.

My problem:

Code:

def userindextry():
    User_input = 'u'
    index_range = range(0,3)
    range_check = False
    while User_input.isdigit() == False and range_check == False:
        User_input = input('Please enter a number: ')
        if User_input.isdigit() == True:
            if int(User_input) not in index_range:
                User_input.isdigit() == False
                range_check == False
                print('not in range')
            else:
                print('You choosed', User_input)
                break
            
        
        else:
            print('Number please')
    return(int(User_input))


def uservalue():
    input_value = input('Please enter a value: ')
    return(input_value)

and

def game():
    gamelist = [1,2,3]
    while True:
        userindex = userindextry()
        userV = uservalue()
        for i in range(len(gamelist)):
            number = gamelist[i]
            if number == userindex:
                gamelist[number] = userV
        cmd = input('Do you want to quit? Enter \'q\'!')
            
        if cmd == 'q':
            print('You did now Quit')
            break
        else:
            pass
        print(gamelist)

game()

What is going wrong with my code?

标签: python

解决方案


def game():
    gamelist = [1, 2, 3]
    while True:
        userindex = userindextry()
        #print("userindex", userindex)
        userV = uservalue()
        #print("userV", userV)
        for i in range(len(gamelist)):
            number = gamelist[i]
            if i == userindex:
                gamelist[i] = userV
        cmd = input('Do you want to quit? Enter \'q\'!')
        if cmd == 'q':
            print('You did now Quit')
            break
        else:
            pass
    print(gamelist)

您的错误在 game() 函数中。研究我写的带有更正的 game() 的重写(有两个更正)。您将索引与提取的值进行了比较。您将看到更正后的代码有两个修复:

    if i == userindex:
        gamelist[i] = userV

推荐阅读