2

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:

  • I am able to change index position 2 and 1 but not 0.
  • And I can do it in the sequence [2][1] but I cant change the gamelist if I got the other way around.

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?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69

2 Answers2

2
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)

Your errors are in the game() function. Study the rewrite of game() I wrote with the corrections (there are two corrections). You compared an index with the extracted value. You will see that the corrected code has two fixes:

    if i == userindex:
        gamelist[i] = userV
Mukherjee
  • 486
  • 1
  • 3
  • 11
1

Your function userindextry() returns a number of 0 to 2.

Your function game() compares this return of 0 to 2 to the value in your gamelist = [1,2,3] - it does not contain 0 -> so 0 can not be changed. The content of gamelist are initially integers but after you replace them with something from userindextry they contain a mix of strings and integers.

I have reworked your code a lot, maybe this will make it more clear.

def get_user_index():
    allowed_nums= range(0,4)
    while True:
        number = input('Please enter a number, 0 to quit: ')
        try:
            n = int(number)
            if n in allowed_nums:
                return n
            print(f"Number must be one of: ", ' '.join(map(str, allowed_nums)))
        except Exception:
            print("Not a number!")

def get_value():
    return input('Please enter a value: ') or get_value() # hack-ish

Game:

def game():
    gamelist = [1,2,3]
    while True:
        index = get_user_index() # will return 0, 1, 2
        if index == 0: 
            print('\nGood bye.\n')
            break

        value = get_value() # will return a string

        found_it = False
        for idx, old in enumerate(gamelist):
            if index == old:
                found_it = True
                print(f"# Replacing pos #{idx} old value '{old}' ({type(old)}) "
                      f"with '{value}' ({type(value)}) ")
                gamelist[idx] = value
        if not found_it:
            print("This place was already set earlier.")
    print(gamelist)

game()

Output of a run with all cases done at least once:

Please enter a number, 0 to quit: 1
Please enter a value: Vlaue1
# Replacing pos #0 old value '1' (<class 'int'>) with 'Vlaue1' (<class 'str'>)
Please enter a number, 0 to quit: 32
Number must be one of:  0 1 2 3
Please enter a number, 0 to quit: sadfg
Not a number!
Please enter a number, 0 to quit: 1
Please enter a value: oo
This place was already set earlier.
Please enter a number, 0 to quit: 2
Please enter a value: V2
# Replacing pos #1 old value '2' (<class 'int'>) with 'V2' (<class 'str'>)
Please enter a number, 0 to quit: 3
Please enter a value: V3
# Replacing pos #2 old value '3' (<class 'int'>) with 'V3' (<class 'str'>)
Please enter a number, 0 to quit: 0

Good bye.

['Vlaue1', 'V2', 'V3']

HTH

You might want to read through Asking the user for input until they give a valid response to get a better idea how to safely get input from users.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69