Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
初学者、Python、if语句_Python - Fatal编程技术网

初学者、Python、if语句

初学者、Python、if语句,python,Python,这是一本书中的一个简单例子。很好,但我有个问题, 如何让这个程序看到我输入的是字母而不是数字?如果我使用数字,它工作正常,但是如果我输入一个字母,程序就会崩溃。我知道当一个程序得到一个原始输入时,它需要检查它是一个数字还是另一个符号,但我不知道最简单的解决方案是什么 使用一些简单的字符串方法,如下所示: num=float(raw_input('Enter a number: ')) if num <0: print "-" elif num>0: print "+"

这是一本书中的一个简单例子。很好,但我有个问题,
如何让这个程序看到我输入的是字母而不是数字?如果我使用数字,它工作正常,但是如果我输入一个字母,程序就会崩溃。我知道当一个程序得到一个原始输入时,它需要检查它是一个数字还是另一个符号,但我不知道最简单的解决方案是什么

使用一些简单的字符串方法,如下所示:

num=float(raw_input('Enter a number: '))
if num <0:
    print "-"
elif num>0:
    print "+"
else:
    print "0"
方法1: 尝试检查输入是否为数字。这适用于负数和正数,但不适用于1.1、1.2等数字:

方法2: 单独使用if语句可以使用isdigit函数。 但是,这对负数不起作用,例如-1将返回False

方法3: 下面是另一种检查给定字符串是否为数字的方法:

if userInput.isdigit():
    #your code here
else:
    Print("Not a digit")
另外,下次尝试包含一个包含错误的日志,并添加一些更多的标记,如integer、string和if语句

资料来源:


使用“是”来判断输入值是否为浮点值

12.345如何。是数字吗?是的!显然,它给出了错误的答案。
try:
   val = int(userInput)
   #code here
except ValueError:
   print("That's not an int!")
if userInput.isdigit():
    #your code here
else:
    Print("Not a digit")
import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
    print("Given string is number")
else:
    print("Given string is not a number")
num=raw_input('Enter a number: ')
if num is float:
    num = float(num)
    if num <0:
        print "-"
    elif num>0:
        print "+"
    else:
        print "0"
else:
    #do something