I can’t convert a string to an integer correctly with the code below.
I take lang input as a string. I want to accept any input, because if I restrict the input to integers, then any letter entered by the user will cause an error.
This code:
lang=[]
def chooseLang():
global lang
while lang !='1' and lang != '2':
print ('Select (1 or 2):')
lang=input()
return lang
def convertStr(lang):
ret=int(lang)
return ret
#-----------------------Program-----------------------
chooseLang()
convertStr(lang)
c=2+lang
print (c)
… causes this error:
in <module> c=2+lang
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Trying do everything in one function has the same effect:
lang=[]
def chooseLang():
global lang
while lang !='1' and lang != '2':
print ('Select (1 or 2):')
lang=input()
return lang
ret=int(lang)
chooseLang()
c=2+lang
print (c)
What am I doing wrong?
You forgot to use the returned value from convertStr() function in the first example:
In your second example
ret = int(lang)is unreachable due toreturn langbefore it.Example