-1

Whenever I run this code it doesn't allow inputs such as cow. I have included the term float as I would like number and word input. I can enter numbers but not words. Has anyone got an idea where I am going wrong?

my output should look like :

How many strings do you want to enter:3

Enter string 1: 2

Enter string 2:-4

Enter string 3:cow

No of positive numbers entered is: 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()
Barbra
  • 11
  • 2

1 Answers1

0

I think you just need to test whether the input value is a number or not by converting to float and catching the resulting exception:

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()

Output as requested

quamrana
  • 37,849
  • 12
  • 53
  • 71