【问题标题】:if condition not working properly inside a function python 3 [duplicate]如果条件在函数python 3中无法正常工作[重复]
【发布时间】:2015-06-02 10:18:51
【问题描述】:
这是下面的代码。为什么没有调用test2函数?
即使我输入 1 也不会调用 test2 函数
def test2():
print("here i come")
def test1():
x=input("hey ill take u to next fuction")
if(x==1):
test2()
test1()
【问题讨论】:
标签:
python
function
python-3.x
【解决方案1】:
x=input("hey ill take u to next fuction")
x 将是字符串类型,而不是整数。您应该更改if 语句以比较相同的类型(将x 转换为int,或将1 转换为"1"
【解决方案2】:
因为您将字符串(您的输入)与整数 1 进行比较。所以您需要将输入转换为int,然后进行比较。
由于它可以引发ValueError,您可以使用try-except 来处理它:
def test1():
x=input("hey ill take u to next fuction")
try :
if(int(x)==1):
test2()
except ValueError:
print 'enter a valid number'