RecursionError: maxium recursion depth exceeded - python

I'm new to stack overflow this is my second question so please bear with me. I'm creating a simple calculator program. Here's the code:
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
print("what do you want to do?")
print("1.Add:")
print("2.Subtract:")
print("3.Multiply:")
print("4.Divide:")
choice = input("Enter a number 1-4 for your operation: ")
def operation():
if choice == '1':
print(num1,"+",num2,"=", add(num1, num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1, num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1, num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1, num2))
else:
print("I SAID A NUMBER 1-4 YOU DUMBASS!")
return(operation(), input())
operation()
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another one: "))
whenever I put a number greater than 5 it uses the else statement and loops the print statement over and over for a couple of seconds then print "recursion error: maximum recursion depth exceeded. I know that by putting the return statement inside the function, the function then loops itself over and over. I then tried to add the input to prompt the user for another input but I guess this isn't the right syntax. Can someone post the right syntax for this code or is there a more concise way of doing this? Thank you any help is appreciated.

The problem is in your else clause:
else:
print("I SAID A NUMBER 1-4 YOU DUMBASS!")
return(operation(), input())
Notice that you call operation again, but you haven't changed the choice at all, so operation will run again with the same choice you had before (over and over until you hit the recursion limit).
At this point, you're probably tempted to do:
choice = input(...)
return operation()
However, that won't work either as choice is a global variable and if you try to modify it in the function, you'll get an UnboundLocalError.
You could declare global choice within operation, but that's suboptimal. A better design would be to pass the choice as an argument to operation:
choice = int(input("Enter a number 1-4 for your operation: "))
def operation(choice):
if choice == 1:
print(num1,"+",num2,"=", add(num1, num2))
elif choice == 2:
print(num1,"-",num2,"=", subtract(num1, num2))
elif choice == 3:
print(num1,"*",num2,"=", multiply(num1, num2))
elif choice == 4:
print(num1,"/",num2,"=", divide(num1, num2))
else:
print("I SAID A NUMBER 1-4 YOU DUMBASS!")
choice = int(input())
return operation(choice)
operation(choice)
Finally, even once you get this part working, you'll have additional problems depending on python2.x or 3.x. On python2.x, input will be returning numbers, not strings, so your equality tests (choice == '1') will never pass. On python3.x, the equality tests will work out just fine (because your choice will be a string), but the math equations will break (you can't multiply 2 strings together).
I've fixed that in the example above -- But remember not to use input in production code for python2.x as it's a huge security risk.

That call is before input so it is calling and calling and calling again. This menu with choices is usually placed inside a while loop.

There are two problems in your code, one is you are comparing a string with integer and the next one with out changing the value of option you are calling the same function, so it keeps on calling itself never ending, so the compiler giving you recursion error.

Related

Do i have to create nested loops or can i do it with the try function?

Can someone explain to me why is asks for an input the second time someone enters an operator and a number?
It is an calculator and i want to except the Valueerror the sedcond time but the code always repeats twice and doenst exit the try function.
Can someone please help me in the right direction?
import locale
## Defining the calculator functions
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
## Asking for the first user input
while number_2 = None :
try:
operation, number_2 = input('''
Starting at zero
Please enter an operator and a number
Enter: ''').split()
continue
except ValueError:
print('Please put a space between the operator and the number!')
else:
break
##Making the input calculatable
number_1 = float(0)
number_2 = float(number_2)
## Calculating the outcome
i = 0
while i < 1:
if operation == '+':
number_1 = add(number_1, number_2)
print('Answer is: ', round(number_1, 4))
elif operation == '-':
number_1 = subtract(number_1, number_2)
print('Answer is: ', round(number_1, 4))
elif operation == '*':
number_1 = multiply(number_1, number_2)
print('Answer is: ', round(number_1, 4).format)
elif operation == '/':
number_1 = divide(number_1, number_2)
print('Answer is: ', round(number_1, 4))
else:
print("Invalid input")
## Asking for the second number
try:
operation, number_2 = input('''
Starting at the previous outcome
Please enter an operator and a number
Enter: ''').split()
except ValueError:
print('nee gap')
number_2 = float(number_2)
if operation == 'q':
break
enter image description here
You've written continue in the first try section, which means, if the condition is satisfied, it'll continue the loop again, and check for number_2 and if the input is correct, again it will continue the loop. So try deleting the continue statement, if the error is occured, it'll directly go to except section
Also, you've to write == to compare the values in while number_2 == None
And you've to define number_2 and operation before using it in while loop. It'll give you error that number_2 is not defined
result=0
while True:
a=input("Enter operator and number= ")
if len(a)>=2 and a[0] in ["+","-","*","/"]:
h=int(a[1::])
if a[0]=="+":
result+=h
elif a[0]=="-":
result-=h
elif a[0]=="*":
result*=h
elif a[0]=="/":
result/=h
else:
print("choose only from +-/*")
else:
print("invalid input")
ch=input("Enter more?")
if ch=='n':
break
print(f"The result is {result}")
Here, the user has to input both parameters as well as the number, I'm taking it as a string because you can traverse it later on and can seperate the operator and number. Initial result is 0. As the user puts the input, we'll traverse the string and seperate number and operator, (say "+9") operator will be <input>[0] and number will be int(<input>[1::]). Now we have seperated the numbers. Let's check for operator using if condition and calculate according. Hope this answer satisfies your aim, if not let me know your aim, I'll surely design a new one

how to make a conditional loop and a divison by zero is invalid

How to make a conditional loop and ("Divison by zero is invalid")
could not find an answer that works I searched for the past day or so
[: https://i.stack.imgur.com/CfcFo.png][1]
The answer is to use while loop:
print("Welcome to the amazing calculator!\n\n")
loop = True
while(loop):
print("--------------------------------------------")
one = float(input("Enter the first number:"))
two = float(input("And now the second one:"))
print("Choose what you want to do with those two numbers: \n")
print("Add -> '+'\n Substract -> '-'\n Multiply -> '*'\n # And so on...\n")
sign = input("So which action do you need? ")
# Now, here you check all conditions etc. I'm not writing this for you ;)
# In order to use the MATCH keyword you need at least python 3.10
match sign:
case "/":
if two == 0:
print("You cannot divide by ZERO!")
else:
print(f"Result of division: {one / two}")
case "+":
print("And so on...")
# If you don't have python 3.10 installed, just use if/else like you did in your code
if sign == "/":
if two == 0:
print("You cannot divide by ZERO!")
else:
print(f"Result of division: {one / two}")
# And when user wants to exit the program
else:
print("Exiting program....")
loop = False
I hope my answer was sufficient and now you know, how to program the best calculator ever known to humanity :D

Don't know how to use methods created

I'm super new to Python and programming in general. I am following an example off of youtube on how to make a simple calculator but I wanted to add my ideas and functionalities. More or less I want to make it very versatile.
This is the part that is not working out for me. I don't know how to make it work using the two methods I created
def main():
while True:
Num1()
num1 = int.num1()
Num2()
num2 = int.num2()
# Executing the specified calculations with the 'Operation' function (row 13)
Operation(num1, num2)
# --> followed by another nested while asking if the user wants to make another calculation
I want the app to read everywhere that if the user types "exit" it will exit, even if it's asking for a number so I created 2 methods to do so because it wasn't working dealing with the loops and user input directly from main()
def Num1():
while True:
num1 = input("What is the first number? ")
if num1.isdigit():
break
elif num1 == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
continue
def Num2():
while True:
num2 = input("What is the second number? ")
if num2.isdigit():
break
elif num2 == "exit":
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
continue
The problem is that I get this error and I get it but I just don't know how to go about it.
Traceback (most recent call last):
File "C:/Users/Albert/PycharmProjects/HelloWorld - First Py'
Apps/SimpleCalculator.py", line 131, in <module>
main()
File "C:/Users/Albert/PycharmProjects/HelloWorld - First Py'
Apps/SimpleCalculator.py", line 109, in main
Operation(num1, num2)
NameError: name 'num1' is not defined
I see few general errors in your code:
You call function Num1() for entering num1, but num1 is the local
variable. So you can see and use it only in Num1() function. Same
with num2. So, I suggest to use Num1 and Num2 but to return the num1
and num2.
I recommend to use 1 function, there is no need to use 2.
Looks like with num1 = int.num1() you want to convert num1() to int. This is wrong. Correct will be something like num1 = int(num1).
This will convert num1 from string to int and save it to num1. But
better to use different names for strings and int's: num1 =
int(num1_str). And when you use bracket num1(), this means you call
num1 function to complete. But num1 is not a function, so it's not
callable.
You use converting strings to int two times. In programming, when you see two code, which is just copy/paste, you better to make a
function for it. Here we have the function, so just insert
converting to int in function.
Don't forget about indentation. This is the most important thing in Python. In other languages, you use something like {} to define
the beginning and the end of some logical block. But in Python, it
all depends on indentation.
So, using this, it can look like this way:
def main():
while True:
# just call NumEntering - one general function for entering numbers,
# and give to it attribute - message for user.
num1 = int(NumEntering("What is the first number? "))
num2 = int(NumEntering("What is the second number? "))
# Executing the specified calculations with the 'Operation' function (row 13)
Operation(num1, num2)
And the function:
def NumEntering(message): # message - this what function get from outer function.
while True:
num_str = input(message) # show given message
if num_str.isdigit():
return int(num_str) # convert to int and return to outer function
elif num_str == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
continue
case sensitivity, you defined Num1() & Num2() not num1() & num2()
There's plenty wrong with your code.
DRY Do not Repeat Yourself. There's no need to have two functions when they do the same thing. Delete Num2 in its entirety. It's useless.
Num1 isn't returning a value. We want the function to ask the user for a number (which it does), exit if the user inputs "exit" (also done) and return the number entered by the user (not done).
Function names start with a lowercase letter and are descriptive. Num1 does neither, so let's change it to ask_number.
All the problems identified above can be fixed by replacing Num1 and Num2 with the following ask_number function.
def ask_number():
while True:
num = input("What is the first number? ")
if num.isdigit():
return int(num) #This line fixes problem 2
elif num == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
Your main method isn't assigning the return value of your function into the variables.
Fix it by replacing your old code
Num1()
num1 = int.num1()
Num2()
num2 = int.num2()
with
num1 = ask_number()
num2 = ask_number()
We're calling the ask_number function twice and assigning its return value to num1 and num2.
The problem was that Num1() and Num2() asked the questions, but didn't do anything with them. Also, the num1 and num2 that were defined were variables local to the function, so you couldn't access them from the main() function. You should have added "return numX" instead of break and assigned Num1() to num1, which allows you to capture the user's input in a variable accessible by the main() function.
This is what your code should have looked like:
import time
def Num1():
while True:
num1=input("What is the first number? ")
if num1.isdigit():
return int(num1)
elif num1 == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
def Num2():
while True:
num2=input("What is the first number? ")
if num2.isdigit():
return int(num2)
elif num2 == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
def Operation(num_1, num_2):
# code for Operation function
pass
def main():
while True:
num1=Num1()
num2=Num2()
Operation(num1, num2)
if __name__=="__main__": main()
Disclaimer: I'd ask for some clarification, but I don't have the SO privileges yet.
Can you make sure your indentation is correct when you're running the program? For instance, your while loops shouldn't be on the same indentation level as your function definitions.
Also, are you functions all in this file SimpleCalculator.py? If so, you will need to have an additional line to call your methods, since right now they're only being declared.
if __name__ == '__main__':
# And the following line will call your main function which you defined previously
main()
Better yet, just remove your main() function and replace it with the more Pythonic syntax:
if __name__ == '__main__':
while True:
Num1()
Num2()
Also, since you're calling Num1() and Num2() and they're handling the inputs, you don't need to set num1 = int.num1() or num = int.num2() (which both give me errors) or the like. If you want to have the values to be returned to the main method for handling, you'll need to do return num1 when you check if num1.isdigit():, and in your main method set firstNumberInput = Num1()
Hope this helps!
It may just be that you have posted your code with omissions but there are several points to address.
The functions Num1 and Num2 do not return anything. Although the value num1 is assigned within the function, it is not accessible outside that function's scope.
int does not have a method "num1" so calling int.num1() should be replaced with int(num1())
Creating 2 nearly identical functions creates a lot more work for yourself and makes the code hard to change, you could create a more general function.
def getnum():
while True:
mynum = input("What is the first number? ")
if mynum.isdigit():
break
elif mynum == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
return mynum
def main():
while True:
num1 = int(getnum())
num2 = int(getnum())

I have created a simple calculator program in python, the output seems to trouble me

# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
Hi,
Hi,
Hi, below is a simple python code for calculator, the output seems to be no as expected
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
The specific issue you're encountering is missing from your post, but running your code and entering integers along the way does indeed always land in the last else block and an "Invalid input" error message.
I'm guessing you're running Python 2, in which case the problem stems from the fact that you are comparing the value of choice to a string, but the input() function will return an int (if that's what the user typed in).
To solve this problem, you can either change your if blocks to compare choice with ints, or use the raw_input() function, that will always return a string.
The Problem is int(input("Enter first number: ")) the input is converted into an int, but you are comparing against str as choice == '1'.

Why is my code returning my else: statement?

When i run through my calculator, it gives the following results;
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4):3
Enter first number: 1
Enter second number: 5
Invalid! Input
Can anyone explain to me why it is responding with my else if statement, i'v checked the code many times, plus i have copied paste the code directly, as is, after much frustration, yet it yields the same result?
# A simple calculator that can add, subtract, multiply and divide.
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# Take input from the user
print ("Select operation.")
print ("1.Add")
print ("2.Subtract")
print ("3.Multiply")
print ("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid! Input")
You're using Python 2, where input() evaluates what is entered; so when you enter 2, for instance, choice contains the int 2. Try entering '2' into your current code (including the quotes). It'll act as you expect entering 2 to act.
You should use raw_input() on Python 2 and input() on Python 3. If you want your code to be compatible with both, you can use the following code, after which you can always just use input():
try:
input = raw_input # Python 2
except NameError: # We're on Python 3
pass # Do nothing
You can also use the six package, which does this and many other Python 2/3 compatibility things.
In Python 3 input() does what raw_input() does in Python 2, and Python 2's input() is gone.

Categories

Resources