我有这个代码,但每当我输入一个词,比如cow,它就会停止工作



每当我运行此代码时,它都不允许cow之类的输入。我已经包含了术语float,因为我想要数字和单词输入。我可以输入数字,但不能输入单词。有人知道我哪里错了吗?

我的输出应该是:

你想输入多少个字符串:3

输入字符串1:2

输入字符串2:-4

输入字符串3:cow

输入的正数数量为:1


def main():
global countervalue
countervalue=0
string=int(input("How many strings do you want to enter? "))
for num in range(1,string+1):
value=float(input("Enter string %a: "%num))
IsPos(value)
print("No of positive whole numbers entered is:",countervalue)
def IsPos(val):
global countervalue
if val.is_integer() and val>=0:
countervalue+=1
return countervalue;
main()

我认为您只需要通过转换为float并捕获生成的异常来测试输入值是否为数字:

def main():
global countervalue
countervalue = 0
string = int(input("How many strings do you want to enter? "))
for num in range(1, string+1):
value = input("Enter string %a: " % num)
IsPos(value)
print("No of positive whole numbers entered is:", countervalue)
def IsPos(val):
global countervalue
try:
fval = float(val)
if fval.is_integer() and fval >= 0:
countervalue += 1
except ValueError:
pass
return countervalue
main()

按要求输出

相关内容

最新更新