how to change a value in a key-value inside a function?

Question:

I am trying to make it easier on myself so I can ask for a user input, while having it formatted nicely on one line, so I made this: (IGNORE THE # LINES UNTIL THE PARAGRAPH BELOW)

1  vars = {'strt': ''}
2
3  def inp(decidvar, msg):
4#        (/ 3 /)  (/1)
5
6#       ( / 1)
7    print(msg)
8
9#    (/ 3 /)  (/ 2 /)
10   decidvar = input('≥ ')
11
12   inp(vars['strt'], "do you want to learn the rules? (y/n)")
13#       (/ 3 /)            (/   /   1   /   /)
14
15   if vars['strt'] == 'y':
16     rules()

I am trying to make the console ask a question (1), ask for an input (2), and put the input in the variable in the key-value list (3) (so all the variables are in a single line), all in line 12. but the vars[‘strt’] thing stays equal to ” instead of ‘y’ or ‘n’.

How could I fix this so it works like I want it to?

Asked By: Matthias Jungheim

||

Answers:

The issue in your code is that you’re passing vars[‘strt’] as a parameter to the inp function in line 12, but the inp function doesn’t modify the value of the decidvar parameter that is passed to it. Instead, it creates a new local variable decidvar in line 10 and assigns the user input to that variable. This local variable is then discarded when the function returns, leaving the vars[‘strt’] variable unchanged.

To fix this, you could modify the inp function to accept the dictionary and key as separate parameters, and then update the dictionary in the function:

def inp(dic, key, msg):
    print(msg)
    dic[key] = input('≥ ')

inp(vars, ‘strt’, "do you want to learn the rules? (y/n)")

With this modification, the inp function now takes the dictionary and key as separate parameters, updates the dictionary with the user input, and returns, leaving the dictionary updated with the new value.

Then, you can call this function in line 12 to update the value of vars[‘strt’]:

inp(vars, 'strt', "do you want to learn the rules? (y/n)")

This should update the value of vars[‘strt’] with the user input, and allow you to use it in subsequent code.

Answered By: mark steven
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.