Hey I'm really new to python but I've done some c++ and Javascript programing, I just can't see why my variable x isn't holding its value.
Thanks for the help and have a nice day!
a = input("How much xp? :\n")
x = int(a)
w = 100
z = 1
h = 0
def Call():
global a
print "\n"
print x
print "\n"
print "Would you like to Continue ? \n Y/N \n"
j = raw_input("")
if j == "Y":
print "Call \n"
a = input("How much xp? :\n")
Level()
elif j == "N":
return 0
else:
return 0
def Level():
global x
global w
global z
global h
if x >= w:
z = z + 1
print "Your level is " + str(z)
h = x % w
x = x + h
w = w + 50
Call()
else:
print "Your level is " + str(z)
Call()
Level()
2 Answers 2
You define x at the very beginning of your code, which I presume is to convert a into an integer so you can do operations with it:
x = int(a)
When you ask for the amount of experience you want in your Call() function:
a = input("How much xp?\n")
x is never changed, because the assignment x = int(a) doesn't automatically happen again!
You need to reassign x after you reassign a:
a = input("How much xp?\n")
x = int(a)
But keep in mind that it's generally bad programming practice to use global variables and that there really isn't any need for some of them in your program. For example, a is just a temporary variable designed to hold a string that turns into x, while variables like x can be passed in as arguments.
Also, I'd definitely recommend using some more descriptive variables in your code. This isn't high school algebra: variables can be any length, so you should explain that a is something like input_string, x is something like experience, and j is something like response.
Comments
The problem is in your Call() function. The user input is associated with variable 'a', which you do not use in the rest of the program. It appears as if you mean to have associated it with variable 'x', instead.
This is my suggested solution:
1. Insert global x at the start of the Call() function, so you can modify it from within the function.
2. Replace
a = input("How much xp?\n")
x = int(a)
with
x = input("How much xp?\n")
(twice, in the first line and also in your Call() function)
Here is a short Python program that achieves a similar purpose. I tried to preserve your naming system as much as possible.
w = 100
z = 1
h = 0
while True:
x = input("How much xp? :\n")
if x >= w:
z = z + 1
h = x % w
x = x + h
w = w + 50
print "Your level is " + str(z)
if raw_input("Would you like to continue?\nY/N\n") != "Y":
break
Notes:
- I tried to use structures familiar to Javascript and C++, which you know.
- The input() function (in python2) does not need to be converted to int, because the type is automatically determined based on the input text.
a = input("How much xp? :\n"); x = int(a)...