我有一个输入语句,但我想让它计算输入了多少个整数,单词也可以输入到这个输入中



**我想输入一系列数字和单词,并对所有正整数进行计数

这就是我的输出应该是的样子

例如

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

输入字符串1:57

输入字符串2:4

输入字符串3:-22

输入字符串4:cow

输入的正整数数量:2

这是我目前写的代码**


def main():
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))
print("No of positive whole numbers entered is:",IsPos(val)) 

def IsPos(val):
counterVal=0;
for whole_number in value:
if val.is_integer() and val>=0:
counterVal+=1
return counterval;
main()

您可以使用try/except块:

def main():
num = int(input("How many strings do you want to enter? "))
count = 0
for i in range(num):
try:
if float(input(f"Enter string {i+1}: ")) >= 0:
count +=1
except ValueError:
pass
print(f"No of positive whole numbers entered is: {count}") 

输出:

How many strings do you want to enter? 3
Enter string 1: 1
Enter string 2: -1
Enter string 3: cow
No of positive whole numbers entered is: 1

相关内容

  • 没有找到相关文章