0

I am a beginner learning Python and trying to write a simple program for adding two numbers together. I understand how to add the two numbers, but I do not understand how to write an if-statement that takes into account if a user tries entering something other than a number. I pasted the code below:

num_1 = float(input("Enter first number: "))
num_2 = float(input("Enter second number: "))

if num_1 and num_2 == float:
    print(num_1 + num_2)
else:
    print("Not a valid number")

For example, if a user enters the word dog an error shows up and says:

ValueError: could not convert string to float: 'dog'

How do I fix this if-statement?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Please look for solutions to this arount the internet. It is totally fine to have and ask questions as a beginner but many of them are answered somewhere already :) You could search for "sanitizing user input in python" – David Wierichs Jun 12 '20 at 20:23
  • You don't necessarily have to look "arount" the Internet, especially when you want to know something that's probably very commonly done because the answer can likely be found right on this site. The trick is often in determining the right terms to search for… – martineau Jun 12 '20 at 21:08

1 Answers1

2

The typical way to handle error cases like this is via try/except:

try:
    num_1 = float(input("Enter first number: "))
    num_2 = float(input("Enter second number: "))
    print(num_1 + num_2)
except ValueError:
    print("Not a valid number")

If you enter something that can't be converted to a float, then the float() function will raise a ValueError, which will immediately stop the thing you're trying to do and jump to the except block.

Samwise
  • 68,105
  • 3
  • 30
  • 44