The results are:
Original position: 0
New position: 2
New position: 4
I asked elsewhere why the increment isn’t 3, and was told in order to change the increment variable’s value (didn’t even know increment was a variable) I have to execute code to change it. I tried several things, but I don’t understand it at all. I would appreciate any help.
if I told you I would pay you $1000 dollars if you worked an 8 hour shift on Monday, $2000 on Wednesday, and $3000 on Friday, then you could say that your pay varies depending on the day that you work, correct? So, we can say that your pay is variable. The same holds for x_increment as highlighted by the if/elif/else conditional statements. It varies as a function of the alien_0[‘speed’] value.
Your friend is correct. Unless you explicitly change the value of alien_0[‘speed’], it will remain its original value the next time the if/elif/else conditional statement is encountered (either by way of a function call or some loop, etc.)
Others have already really answered your basic question, but you can avoid having to rerun the code each time, by changing the variable x_increment into a function (which seems more suitable instead of a fixed variable):
alien_0 = {'x-position': 0,
'y-position': 25,
'speed': 'medium'}
print(f'Original position: {alien_0["x-position"]}')
def x_increment():
match alien_0["speed"]:
case "slow": return 1
case "medium": return 2
case _: return 3
Then do
alien_0['speed'] = 'fast'
alien_0['x-position'] += x_increment() # note: now called as function of the speed
print(f"New position: {alien_0['x-position']}")
Now the speed will be taken into account as if by magic
Thanks for the reply. I don’t know how to actually set x-increment again though. Maybe it’s very simple, but I just don’t know. I had no idea I’d run into this problem lol.
This might be a good time to re-evaluate the book you’re using. From the code that’s shown here, it looks like the author is expecting you to understand concepts like this already. It could be that you aren’t in the target audience for the book (teaching someone’s first programming language is different, because it’s necessary to teach the basic idea of programming, as well as the actual language). Or perhaps it will help to review previous exercises (assuming this isn’t the first one!) and make sure you understand them more fully.
Thanks for the reply. I was thinking if I forgot something, but I feel like I haven’t forgotten this, but I’ll take a look back. I think the book is fine for a beginner so far. Of course it’s not going to have all the answers I need. People on the internet have helped me (there’s no way I’d have understood some of the for loop stuff from the book without help from people on the internet). For this example I thought it was abrupt not to give the result.
I don’t mind much doing some research on my own/asking questions, I just don’t like the way this problem was presented if it’s a curveball.