pythonpython-3.xvalidationinput

Reject letters and only allow number inputs @ enter first and second number in Python 3.x


Trying to only allow number inputs in python 3.x no letters and ask user to input a number if they enter a letter. I have two numbers that need to be entered and need it to reject singlarily as they are entered.

print ('Hello There, what is your name?') # String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname)# String responds "Nice to meet you" and input the users name that was entered
print() #adds a space
print ('We want to some math today!') # String tells user we want to do some math today
print() # adds a space
num1,num2 = float(input("Enter first number")), float(input("Enter second number"))
sum = num1+num2
if sum  >100 : # Determines if users inputs when added together are  > 100
 print('They add up to a "Big Number" ') # If inputs are > 100 prints "They add up to a big number"
 # and the users name
elif sum <=100 : # Determines if the users inputs when added are = to or <100
 print ('They add up to' ,(sum))

Solution

  • You need a while loop to continuously accept a valid input which in your case is a numerical one.

    Another thing is that you need to check if the entered input is numerical or not, in that case you can use Python's inbuilt isdigit() function to do it.

    Lastly, type cast your input to float or int while you add the both to avoid str related errors.

    print ('Hello there, what is your name?') # String asks the user for their name
    myname = input() #string
    print ('Nice to meet you, '+ myname) # String responds "Nice to meet you" and input the users name that was entered
    print() #adds a space
    print ('We want to some math today!') # String tells user we want to do some math today
    print() # adds a space
    
    i = False
    while i == False:
        num1 = input("Enter first number: ")
        if num1.isdigit():
            i = True
        else:
            i = False
    
    print() # adds a space
    
    j = False
    while j == False:
        num2 = input("Enter Second number: ")
        if num2.isdigit():
            j = True
        else:
            j = False
    
    sum = float(num1) + float(num2)
    if sum  > 100 : # Determines if users inputs when added together are  > 100
        print('They add up to a "Big Number" ') # If inputs are > 100 prints "They add up to a big number"
     # and the users name
    
    elif sum <= 100 : # Determines if the users inputs when added are = to or <100
        print ('They add up to' ,(sum))
    

    Let me know, if that worked for you!