I'm having troubles running this program.
It tells me I have a
ValueError: could not convert string to float
The problem is though, that it just skips my input commands and jumps to
print("Invalid Response")
This program works fine on my cellphone but not on my windows 10 laptop.
Any help? Try running it and let me know if it works for you.
def calc(): #The function performing calculation.
if chars == "+":
result = num1 + num2
print (result)
return result
elif chars == "-":
result = num1 - num2
print(result)
return result
elif chars == "*":
result = num1 * num2
print(result)
return result
elif chars == "/":
result = float(num1) / float(num2)
print(result)
return result
else:
print("Invalid or unsupported operation")
cont = ""
def contin():
result = calc()
print("Operate? y/n: ")
cont = input()
if cont == "y":
print(result) # output is: ought to be:
chars = input() #result result
contin_num = float(input())
calc(contin_num) #result operate y/n
print(result, chars, contin_num)
elif cont == "n":
result = 0
print(result)
else:
print ("Invalid response.")
num1 = float(input ())
chars = input ()
num2 = float(input ())
result = 0
while num1 > 0 or num2 > 0:
calc()
contin()
break
if num1 == 0 and num2 == 0:
print("Zero or undefined.")
This is the desired code. I changed a little bit some indentations are wrong in case of contin() function and some logic. Please refer to this if I am wrong in some place do tell me. Thank you
def calc(num1,chars,num2): #The function performing calculation.
if chars == "+":
result = num1 + num2
print (result)
return result
elif chars == "-":
result = num1 - num2
print(result)
return result
elif chars == "*":
result = num1 * num2
print(result)
return result
elif chars == "/":
result = float(num1) / float(num2)
print(result)
return result
else:
print("Invalid or unsupported operation")
cont = ""
def contin(res):
num1 = res
print("Operate? y/n: ")
cont = raw_input()
if cont == "y":
print(num1) # output is: ought to be:
chars = raw_input() #result result
num2 = float(input())
num1=calc(num1,chars,num2) #result operate y/n
print num1
elif cont == "n":
result = 0
print(result)
else:
print ("Invalid response.")
num1 = float(input ())
chars = raw_input ()
num2 = float(input ())
result = 0
while num1 > 0 or num2 > 0:
res = calc(num1,chars,num2)
contin(res)
break
if num1 == 0 and num2 == 0:
print("Zero or undefined.")
Related
def main():
num1 = input("Write a number: ")
op = input("* or / or + or -: ")
num2 = input("Write another number: ")
result = None
if op == "+":
result = float(num1) + float(num2)
print(result)
elif op == "-":
result = float(num1) - float(num2)
print(result)
elif op == "*":
result = float(num1) * float(num2)
print(result)
elif op == "/" and num2 == 0:
result = None
print("You can't divide by zero")
main()
elif op == "/" and num2 != 0:
result = float(num1) / float(num2)
print(result)
while True:
main()
ans = input("Would you like to do another equation: ")
if ans == "yes":
main()
ans = input("Would you like to do another equation: ")
elif ans == "no":
exit()
I get this error even though i already had an elif statement for that case
File "d:\Visual Studio Code\Projects\HelloWorld python\Calculator.py", line 26, in
main()
File "d:\Visual Studio Code\Projects\HelloWorld python\Calculator.py", line 21, in main
result = float(num1) / float(num2)
ZeroDivisionError: float division by zero
The reason you're not catching the zero case is that num hasn't been converted to a float. Consider using try/except instead -- that way you don't need to try to predict whether the operation will fail, you can just let the operation itself tell you. This will also let you catch things like inputs that aren't valid numbers, or operations that aren't one of the valid options.
You can also save time by doing the float conversion as soon as possible -- if you use try/except, this lets you immediately re-prompt the user for valid input. If you return the answer (and let the caller print it) rather than assigning it to a result which you then print, you can easily break the loop once the function succeeds while also making each if block a single concise line.
Note that explicitly re-calling main() isn't necessary as long as it's in a while loop that continues until it's time to break.
def main() -> float:
while True:
try:
num1 = float(input("Write a number: "))
op = input("* or / or + or -: ")
num2 = float(input("Write another number: "))
if op == "+":
return num1 + num2
elif op == "-":
return num1 - num2
elif op == "*":
return num1 * num2
elif op == "/":
return num1 / num2
else:
raise ValueError(f"Invalid operation {op}")
except ZeroDivisionError:
print("You can't divide by zero")
except ValueError as e:
print(e)
while True:
print(main())
ans = input("Would you like to do another equation: ")
if ans == "no":
break
Convert num2 to a float, either before you test it or when you test it:
### ...
elif op == "/" and float(num2) == 0.0:
result = None
print("You can't divide by zero")
main()
elif op == "/" and float(num2) != 0.0:
result = float(num1) / float(num2)
print(result)
newbie to python and I was creating a basic calculator with functions and variables and such, was wondering if there was a way for python to skip the two lines that you enter num1 and num2 in. Currently if you make the opr == cube/square it doesn't ask for a number to cube/square it just goes straight to the lines asking for num1 and num2.
opr = input("Would you like to multiply (*), Divide (/), Subtract (-), Add (+), Cube (cube) or Square (square):")
if opr == "cube":
cube1 = int(input("Enter Number To Cube"))
elif opr == "square":
square1 = int(input("Enter Number To Square"))
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
def cube(num):
return num * num * num
def square(num):
return num * num
if opr == "*":
result = float(num1) * float(num2)
if opr == "/":
result = float(num1) / float(num2)
if opr == "-":
result = float(num1) - float(num2)
if opr == "+":
result = float(num1) + float(num2)
if opr == "cube":
result = cube(cube1)
if opr == "square":
result = square(square1)
print(result)
Any help is greatly appreciated!
You can simply add them in a condition :
elif opr == "*" or opr == "-" or opr == "+" or opr == "/":
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
I'm currently trying to make a small script which makes basic mathematical operations, and I want it to return to the number input depending if the user want or not to make another operation based on another input. I've already tried while loops and defining a function
Here is the code:
print('Hi!,this is a calculator')
#Here's where it should return
num1 = input('Please,enter a number ')
num2 = input('Enter another number ')
while True:
operator = input('Insert an operator +,-,*,/ ')
if operator != "+" and operator != "-" and operator != "*" and operator != "/":
print('Invalid Operator')
else:
if operator == "+":
result = int(num1) + int(num2)
result = str(result)
print('Your result is ' + result)
elif operator == "-":
result = int(num1) - int(num2)
result = str(result)
print('Your result is ' + result)
elif operator == "*":
result = int(num1) * int(num2)
result = str(result)
print('Your result is ' + result)
elif operator == "/":
result = int(num1) / int(num2)
result = str(result)
print('Your result is ' + result)
exit()
#Here's the repeating input
# repeat = input('Do you want to make another operation? Y/N ')
# repeat = repeat.lower()
# if repeat == 'y' or repeat == 'yes':
# else:
# exit()
You almost had it right. You can use a function to do the calculation, and call the function in a loop. If the user is finished, then break the loop.
EDIT: Added a loop to calculate() per the asker's specifications
print('Hi!, this is a calculator')
def calculate():
# loop in case the user entered an incorrect operator
while True:
num1 = input('Please,enter a number ')
num2 = input('Enter another number ')
operator = input('Insert an operator +,-,*,/ ')
if operator != "+" and operator != "-" and operator != "*" and operator != "/":
print('Invalid Operator')
continue # restart the calculation
else:
if operator == "+":
result = int(num1) + int(num2)
result = str(result)
print('Your result is ' + result)
elif operator == "-":
result = int(num1) - int(num2)
result = str(result)
print('Your result is ' + result)
elif operator == "*":
result = int(num1) * int(num2)
result = str(result)
print('Your result is ' + result)
elif operator == "/":
result = int(num1) / int(num2)
result = str(result)
print('Your result is ' + result)
return # Finished with this calculation
# continuously calculate until the user doesn't say yes
while True:
calculate()
repeat = input('Do you want to make another operation? Y/N ').lower()
if repeat != 'y' and repeat != 'yes':
break
Make two functions and put both functions in a loop.
def calculate(n1,n2):
oper = input("Enter operand: ")
#your if-elif block here
....
....
print("Your result is", ....)
def userInput():
num1 = input("Enter first num: ")
num2 = input("Enter second num: ")
return [num1,num2]
while True:
inlist = userInput()
calculate(inlist[0],inlist[1])
answer = input("Do you want another operation?")
if answer == "Y":
continue
else:
exit()
I am trying to find out how to make my code repeat its self 3 times at the end of the set of questions and also I'm trying to make sure my validation is correct so that the input to the questions is only a number.
This is my code...
import random
correct = 0
name = raw_input("Please enter your name: ")
print 'ok',name, 'I need you to answer these 10 math simple maths questions'
for counter in range(10):
num1 = float(random.randint(1, 10))
num2 = float(random.randint(1, 10))
Math = random.choice(["+", "-", "*","/"])
print("Please solve:", num1, Math, num2)
user = int(input(""))
if Math == "+":
answer = num1 + num2
elif Math == "-":
answer = num1 - num2
elif Math == "*":
answer = num1 * num2
elif Math == "/":
answer = num1 / num2
if answer!= int:
print ("Please reenter a number")
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print(name, " You Got", correct, "Out Of 10")
Your answer != int should be if not isinstance(answer, int)
Furthermore, you will get ValueError each time user tries to insert characters.
Because of this, you should edit your code to look like this:
from __future__ import division
import random
for i in xrange(3):
correct = 0
name = raw_input("Please enter your name: ")
print 'ok',name, 'I need you to answer these 10 math simple maths questions'
for counter in xrange(3):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
Math = random.choice(["+", "-", "*","/"])
print("Please solve: {} {} {}".format(num1, Math, num2))
while True:
try:
user = int(raw_input(""))
except ValueError:
print ("Please reenter a number")
continue
break
if Math == "+":
answer = num1 + num2
elif Math == "-":
answer = num1 - num2
elif Math == "*":
answer = num1 * num2
elif Math == "/":
answer = round(num1 / num2, 1)
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print("{} You Got {} Out Of 10".format(name, correct))
As you can see there was a lot things that you needed to change.
import random
score = 0
ops = ['+','-','*']
num1 = random.randint(1,9)
num2 = random.randint(1,9)
operation = random.choice(ops)
print(num1)
print(operation)
print(num2)
user = int(input(""))
if operation == "+":
answer = num1 + num2
elif operation == "-":
answer = num1 - num2
elif operation == "*":
answer = num1 * num2
if user == answer:
print("correct")
score = score + 1
else:
print("Incorrect")
print (score)
You can simply add a for loop that iterate 10 times over your code.
import random
score = 0
ops = ['+','-','*']
for i in range(10):
num1 = random.randint(1,9)
num2 = random.randint(1,9)
operation = random.choice(ops)
print(num1)
print(operation)
print(num2)
user = int(input(""))
if operation == "+":
answer = num1 + num2
elif operation == "-":
answer = num1 - num2
elif operation == "*":
answer = num1 * num2
if user == answer:
print("correct")
score = score + 1
else:
print("Incorrect")
print (score)