Repeating a python script in a specific point - python

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

Related

Calculator not working if you enter a letter instead of a number

My Calculator is half working. I really put my brain in it but I cant figure out why its not working. Can someone help me?
number1 = input("Enter first number: ")
number2 = input("Enter second number: ")
operator = input("Enter the operation character: ")
result = number1 + operator + number2
if operator == '+':
result = int(number1) + int(number2)
elif operator == '-':
result = int(number1) - int(number2)
elif operator == '*':
result = int(number1) * int(number2)
elif operator == '/':
result = int(number1) / int(number2)
if number1.isdigit() == True:
print (result)
elif number2.isdigit() == True:
print(result)
else:
print("Enter a number.")
It's printing the calculated value, but if you enter a letter instead of a number.
For example:
Enter a first number: 5
Enter a second number: f
Now it should print "enter a number". But im getting this message istead
ValueError: invalid literal for int() with base 10: 'a'
if number1.isdigit() == True:
print (result)
elif number2.isdigit() == True:
print(result)
**else:
print("Enter a number.")**
You have lines like these:
if operator == '+':
result = int(number1) + int(number2)
Before lines like these:
if number1.isdigit() == True:
print (result)
elif number2.isdigit() == True:
print(result)
else:
print("Enter a number.")
So, if operater is indeed a +, Python will try to evaluate int(number1) + int(number2) and fail if number1 or number2 is not the string representation of a number.
This raises a ValueError (as it should) and a raised exception that isn't caught in a try .. except .. block will cause your program to terminated. You cannot continue with uncaught exceptions.
Either you should check first and then try to convert these strings, or you should catch the exception.
Also, you seem to expect your code to continue running after the mistake is made, so you'll need some sort of loop that keeps the program running until the user enters some input that makes sense.
I am not sure that I understood what you what but I think this solves the problem
number1 = input("Enter first number: ")
number2 = input("Enter second number: ")
operator = input("Enter the operation character: ")
result = number1 + operator + number2
if number1.isdigit() == True and number2.isdigit() == True:
if operator == '+':
result = int(number1) + int(number2)
elif operator == '-':
result = int(number1) - int(number2)
elif operator == '*':
result = int(number1) * int(number2)
elif operator == '/':
result = int(number1) / int(number2)
print (result)
else:
print("Enter a number.")
If you are just starting on coding, I suggest you to use this as a reason to search and learn on some few important concepts that will help you to get going.
First, you must validate your inputs before doing anything else with them. In your case, validate that your first and second numbers are actually valid integers, right after they are input. As it is the same validation to be done on both, you can create a function so you can reuse the logic.
def input_number():
num = input("Enter a number: ")
if num.isdigit():
return int(num)
else:
print("Invalid number.")
return input_number()
Here, I check if the input is valid (isdigit is true), and then I return the value already converted to int. If it is not, I call the same function again, and repeat the process. This is called recursion.
You should also validate the operator, because it is only valid among a few options.
def input_operator():
while True:
op = input("Enter the operation character: ")
if op in ["+", "-", "*", "/"]:
return op
else:
print("Invalid operator.")
Here I used a different technique. It is called while statement, and it will repeat the execution inside it until the condition is not True, or until it is explicitly broken (in this case, with a return statement).
Now, you have to add both function definitions on top of your code, then adjust you logic accordingly.
number1 = input_number()
operator = input_operator()
number2 = input_number()
if operator == "+":
result = number1 + number2
elif operator == "-":
result = number1 - number2
elif operator == "*":
result = number1 * number2
elif operator == "/":
result = number1 / number2
print (result)

ZeroDivisionError: float division by zero even though i had a specific elif statement for that case

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)

Calculator to execute loop until "exit"

I got to do this calculator on python 3 that must execute on loop until the user types exit. Besides, programming ahead of the user typing invalid characters, such as letters when asked to type an operator or a number.
I must use while, if... However, I cannot use import.
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator != "+" or "-" or "*" or "/":
print ("You must enter an operator")
break
no1 = input("Enter a number: ")
no2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else :
output = int(num1) / int(num2)
print("The result is " + str(result))
print("See you soon!")
I expect it to actually not stop when we enter anything but an operator, I want it to loop back to:
operator = input("Give me an operator or \"exit\" to stop : ")
You will find below this your code that work as expected, however lets start with general rules.
Be attentif, when you declare a variable, use the same elsewhere in your code.
Test, simple part of your code before trying to do a script. You condition to test operator was totally broken.
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator not in [ "+", "-", "*" , "/"]: #<== here you condition is wrong ,do this instead
print ("You must enter an operator")
continue
try:
num1 = int(input("Enter a number: ")) #
num2 = int(input("Enter a number: ")) # <== both of this variable are not use else where ,rename to be consitdnt with the rest of your code
except ValueError:
print("Please enter an integer")
if operator == "+":
output = num1 + num2
elif operator == "-":
output = num1 - num2
elif operator == "*":
output = num1 * num2
else :
output = num1 / num2
print("The result is " + str(output)) #<=== here also, results was not defined
print("See you soon!")
Put a generic else statement which will continue with the next iteration.
if condition1 :
//logic
elif condition2 :
//logic
else:
continue
Your problem is that you are doing:
if operator != "+" or "-" or "*" or "/":
And what that is really doing, is that:
if operator != "+" or 45 or 42 or 47: (ASCII representation of these characters)
What this means, is that the condition is true no matter what, because or n where N is not 0, would pass any time.
You want:
if operator != "+" and operator != "-" and operator != "*" and operator != "/":
You want an AND gate.
Also, I noticed you are saying no1 = input(...) then doing int(num1) instead of int(no1).
As for jumping back to input, you use continue
Final code:
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator not in [ "+", "-", "*" , "/"]: # credit to Florian Bernard for this line :)
print ("You must enter an operator")
continue
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else:
output = int(num1) / int(num2)
print("The result is " + str(output)) # this was previously str(result) but result is was not defined
print("See you soon!")
BUT! if you are feeling new today, you can use the walrus operator introduced in PEP 572 and available from python 3.8
while (operator := input("Give me an operator or \"exit\" to stop : ")) != "exit":
if operator not in [ "+", "-", "*" , "/"]: # credit to Florian Bernard for this line :)
print ("You must enter an operator")
continue
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else:
output = int(num1) / int(num2)
print("The result is " + str(output))
print("See you soon!")
EDIT:
Edited the final code to use continue, previous version was.
Also added a python 3.8 implementation.
EDIT2:
Just correcting some stuff, making sentences truer.

First app error IndentationError: expected an indented block

I just started learning python and I made a simple calculator and I'm trying to make it restart but I get this error
> F:\newb\venv\Scripts\python.exe F:/newb/python.py File
> "F:/newb/python.py", line 4
> what = input("Choose your operation:")
> ^ IndentationError: expected an indented block
>
> Process finished with exit code 1
My code:
# Calculator
def main():
what = input("Choose your operation:")
number = float( input("Whats ur number 1?") )
number2 = float( input("Whats ur number 2?") )
if what == "+":
result = number + number2
print("Result: " + str(result))
elif what == "-":
result = number - number2
print("Result: " + str(result))
elif what == "*":
result = number * number2
print("Result: " + str(result))
elif what == "/":
result = number / number2
print("Result: " + str(result))
else:
print(" Choose a correct operation ")
restart = input("do you wish to start again?").lower()
if restart == "yes":
main()
else:
exit()
It was working before I added def main(): and the restart code at the bottom
In Python, indentation is like the brackets in other languages. To mark code blocks, the entire block needs to be indented, so in Python, unlike most other languages, whitespace is important. Please have a read of this resource if you'd like to learn more.
I've fixed your code in the below statement, if you're looking to understand how to indent a main function:
def main():
# You need to everything that belongs to the main function indent here, like so!
what = input("Choose your operation:")
number = float( input("Whats ur number 1?") )
number2 = float( input("Whats ur number 2?") )
if what == "+":
result = number + number2
print("Result: " + str(result))
elif what == "-":
result = number - number2
print("Result: " + str(result))
elif what == "*":
result = number * number2
print("Result: " + str(result))
elif what == "/":
result = number / number2
print("Result: " + str(result))
else:
print(" Choose a correct operation ")
# notice we de-indent here, so that we end the main function.
# add in a main line to start the code once
main()
restart = input("do you wish to start again?").lower()
if restart == "yes":
main()
else:
exit()
Although I would recommend making a 'main' function in the following way instead (referenced here:
def perform_calculation():
what = input("Choose your operation:")
number = float( input("Whats ur number 1?") )
number2 = float( input("Whats ur number 2?") )
../ # rest of your code
# notice we de-indent here, so that we end the perform_calculation() function.
# The following only runs if you run the file directly:
if __name__ == "__main__":
perform_calculation()
restart = input("do you wish to start again?").lower()
if restart == "yes":
perform_calculation
else:
exit()

ValueError when trying to convert strings to floating point

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.")

Categories