Reputation: 3
Here is my python program
def try_ec(argument):
try:
int(argument)
except:
argument = input("Please enter a valid value: ")
a = []
score = 0
first = input("First Number: ")
try_ec(first)
first = int(first)
second = input("Second Number: ")
try_ec(second)
second = int(second)
I am trying to get an integer from the user and i am using try and except if the user enters a string by mistake. However my code is giving this error. How do I make the code correct?
Upvotes: 0
Views: 170
Reputation: 594
you might use recursion call method to convert it into Int
.
def try_ec(argument):
try:
return int(argument)
except:
inpt = input("Please enter a valid value: ")
try_ec(inpt)
a = []
score = 0
first = input("First Number: ")
first = try_ec(first)
second = input("Second Number: ")
second = try_ec(second)
Upvotes: 0
Reputation: 20430
That is because you mutate a locale variable. First's value never changes.
Consider the following example
a = 5
def mut(arg):
arg = 6
mut(a)
print(a) // 5
This is because arg is ia local copy of the argument that was passed in, it lives only in that functions scope.
And here is how we could do it,
a = 5
def mut(arg):
arg = 6
return arg
a = mut(a)
print(a) // 6
By returning the new computed value and assigned it to our initial variable.
Upvotes: 1
Reputation: 128
You must use while loop to check the process until it is correct.
For example:
def take_int_input(text):
while True:
argument = input(text)
try:
return int(argument)
except:
print("Please enter a valid value!")
first = take_int_input("First Number: ")
second = take_int_input("Second Number: ")
Upvotes: 0