(Scroll down for changes)
I know many have probably already asked this, but i have looked at a few solutions to other people's questions and whatever i have tried has not worked. I am very new to coding and i have to code a calculator for school. I have the following code which accepts input for numbers from the user:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
When i enter a letter however, I get the following error message:
Traceback (most recent call last): File "python", line 40, in ValueError: could not convert string to float: 'd'
Can someone help me to be able to make it so that it only accepts numbers? Here is the rest of my code:
import time
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
def power(x, y):
return x ** y
print("Welcome to the Calculator App!\n")
print("Select operation.\n")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.To the Power of\n")
choice = input("Enter choice(1, 2, 3, 4 or 5):")
while choice not in ("1","2","3","4","5"):
print("Invalid Input")
choice = input("Enter choice(1, 2, 3, 4 or 5):")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
while choice == '5' and num1 >= 1000000000:
print("\nFirst number too high\n")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
while choice == '5' and num2 >= 30:
print("\nSecond number too high")
num2 = float(input("Enter second number: "))
while choice == '4' and num2 == 0:
print("\nCannot divide by zero")
num2 = float(input("Enter second number: "))
if choice == '1':
print(" ")
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(" ")
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(" ")
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(" ")
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == '5':
print(" ")
print(num1,"**",num2,"=", power(num1,num2))
else:
print("\nInvalid input")
time.sleep(10)
This is my code for that section now:
num1 = float(input("Enter first number: "))
while True:
try:
num1 = float(input("Enter first number: "))
except ValueError:
print("Please enter only a number")
continue
else:
break
When i run that and deliberately enter the letter g, I get the following error message:
Traceback (most recent call last):
File "python", line 32 in <module>
ValueError: could not convert string to float: 'g'