if语句,查看变量中是否有任何值

时间:2017-11-12 13:04:19

标签: python python-3.x

6并且想知道如何制作一个if语句来检查变量中是否有任何类型的值。

number = random

if number (has a value in it)
    print ("Your variable has a number in it")
elif number (doesn't have a value in it)
    print ("Please input a number in the variable")
else:
    print ("unknown error, restarting")

感谢您对此问题的任何帮助。

2 个答案:

答案 0 :(得分:0)

在这种情况下,变量的值必须是字符串:

var1 = '2333'

if '4' in var1: 
    print('found it') 
else:
    newVariable = var1 + '4'
    print(newVariable)

答案 1 :(得分:0)

检查变量是否包含数字:

var = input("Enter a number")

try:
    int(var)
    print("Value is a number")
except ValueError:
    print("Value is a not a number")

或者,检查变量是否已设置:

var = input("Enter a value")

try:
    var
    print("Variable has a value")
except NameError:
    print("Variable has no value")