如果条件不正常工作内部函数python 3 [英] if condition not working properly inside a function python 3

查看:104
本文介绍了如果条件不正常工作内部函数python 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是下面的代码。test2函数不会被调用为什么?
即使我输入1,test2函数也不会被调用:

This is the following code.The test2 function doesnt get invoked why? Even if i enter 1 the test2 fuction is not called

def test2():
    print("here i come")
def test1():
    x=input("hey ill take u to next fuction")
    if(x==1):
      test2()
test1()


推荐答案

比较一个字符串(你的输入)和1是一个整数。所以你需要将输入转换为 int ,然后比较它。

Because you are comparing a string (your input) with 1 that is a integer.So you need to convert the input to int and then compare it.

另外,因为它可以增加 ValueError ,所以可以使用 try - 除来处理:

Also as it can raise ValueError you can use a try-except to handle that :

def test1():
    x=input("hey ill take u to next fuction")
    try :
       if(int(x)==1):
          test2()
    except ValueError:
       print 'enter a valid number'

这篇关于如果条件不正常工作内部函数python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆