Change variable because of variable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Change variable because of variable?

I'm working on a program in which a variable changes depending on another variable but it stays as the defined text. how do I fix it/do something similar to it but with the same effect? heres a example of what I mean: name = "Jeff" name2 = 0 def change(): if name2 == 1: name = "Steve" elif name2 == 0: name = "Bob" output is jeff

26th Mar 2018, 9:19 PM
error505
5 Answers
+ 1
Maybe to obvious but i don't see it in your code, what about: - A return statement? Or - A print statement of name? And by the way, if you check if the code is 1 and it is not, in this case you already know its 0 then. I dont know if its clean code but i guess you can just say: name = "Jeff" number = 0 def changeNameOnNumber(number) if number == 1: return "Steve" else return "Bob" I am not to familiar with python but later on in your program you can just call it like this: name = changeNameOnNumber(number) print(name) Hope this helps :)
26th Mar 2018, 9:37 PM
***
*** - avatar
+ 2
Yep, it definitely should! Just one problem though, you would need to indent the if and elif statements within the function, as Python doesn't allow for the use of curly brackets (also you would need to add the colon for declaring the statements within the function). d:
26th Mar 2018, 9:45 PM
Faisal
Faisal - avatar
+ 1
The reason that the value of name is not changing is because you set the if/elif statements within a function, which does not get called anywhere in the code. Try calling the function as change() anywhere in the code, and it should run and change the value of name to "Bob".
26th Mar 2018, 9:39 PM
Faisal
Faisal - avatar
+ 1
Good call Faisal, i guess my code example should work then :)
26th Mar 2018, 9:41 PM
***
*** - avatar
0
i hope this answers your question abit: name = "bob" name2 = 0 def a(): if name2 == 1: name = "sam" elif name2 == 0: name = "simeon" return name print(name) print(a()) print(name)
27th Mar 2018, 2:48 PM
Markus Kaleton
Markus Kaleton - avatar