How to break a while loop in python? - python

Here I m making a small calculator. accepting two numbers and one operator this will be easy while I'm using function but in this I'm using the while condition statement but there is a error it will not breaking while every operation it will ask to user that it will want to any operation again in 'Y' for yes and 'N' for no but There is an error it will not changing the value of n. Below is my program:
n = 1
def again(number):
print('value of n in again fucntion', n)
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
number = 1
return number
elif calc_again.upper() == 'N':
number = 0
print('value of n after say no', number)
return number
else:
again(n)
while n > 0:
print('while n value', n)
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
again(n)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
again(n)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
again(n)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
again(n)
else:
print('You have not typed a valid operator, please run the program again.')
Can anybody please help me for solving this. Thanks in advance.

You use the local variable number in again, but use n outside. You have to assign the return value of again to n.
def again():
while True:
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
number = 1
return number
elif calc_again.upper() == 'N':
number = 0
print('value of n after say no', number)
return number
n = 1
while n > 0:
print('while n value', n)
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
else:
print('You have not typed a valid operator, please run the program again.')
n = again()

If you want to break your loop, then simply use break where you want the loop to stop.
Edit:
Your loop can be like:
while n > 0:
print('while n value', n)
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
if again(n) == 0:break
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
if again(n) == 0:break
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
if again(n) == 0:break
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
if again(n) == 0:break
else:
print('You have not typed a valid operator, please run the program again.')

There is no need to store a value n
Change the while loop to while True:
Change the again function to return a Boolean.
use the following syntax when calling the again function.
if not again():
break
There is no need to store a value n
Change the while loop to while True:
Change the again function to return a Boolean.
use the following syntax when calling the again function.
if not again():
break
The final code will be something like this.
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
return True
elif calc_again.upper() == 'N':
return False
else:
return again()
while True:
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
else:
print('You have not typed a valid operator, please run the program again.')
break
if not again():
break

You can simplify your code as follow, and to avoid unnecessary recursion in the code:
operations = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"/": lambda x, y: x / y,
"*": lambda x, y: x * y
}
continue_calculation = ""
while True:
calc_again = input('''Do you want to calculate again?Please type Y for YES or N for NO.''')
if calc_again == "n" or calc_again == "N":
break
operation = input('''Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
try:
print(operations[operation](number_1, number_2))
except:
print('You have not typed a valid operator, please run the program again.')

Related

compare list with input

def calculate():
operator = input("What operator do you wanna use(*,/,+,-)? ")
possible_op = ["*", "+", "-", "/"]
if not operator == possible_op:
calculate()
number_1 = float(input("What is your first number? "))
if number_1 != float:
calculate()
number_2 = float(input("What is your second number? "))
if number_2 != float:
calculate()
if operator == "+":
print(number_1 + number_2)
elif operator == "-":
print(number_1 - number_2)
elif operator == "*":
print(number_1 * number_2)
elif operator == "/":
print(number_1 / number_2)
else:
print("Wrong Input")
calculate()
again()
def again():
print("Do you wanna calculate again? ")
answer = input("(Y/N) ").lower()
if answer == "y":
calculate()
elif answer == "n":
exit
else:
print("Wrong Input")
again()
calculate()
Does anyone have an idea why my code always asks the operator questions again and again even if there was a right operator? Do i have to change the name of the list and the input getting compared or
There are quite a few things wrong in this code, but you've managed to use what you know and are in the right tracks so rather than giving you a solution I'll just review it for now.
Mostly, I'd recommend to keep your calculate function simple and handle the looping (rather than recursion) somewhere else.
def calculate():
operator = input("What operator do you wanna use(*,/,+,-)? ")
possible_op = ["*", "+", "-", "/"]
if not operator == possible_op: # this will never be true because operator is a string, use `not in`
calculate() # you probably don't want to run calculate again, maybe return early
number_1 = float(input("What is your first number? "))
if number_1 != float: # number_1 is a float it's not the `float` type so always True
calculate() # return
number_2 = float(input("What is your second number? "))
if number_2 != float: # same as number_1 above
calculate() # return
if operator == "+": # this block is good, simple and to the point
print(number_1 + number_2)
elif operator == "-":
print(number_1 - number_2)
elif operator == "*":
print(number_1 * number_2)
elif operator == "/":
print(number_1 / number_2)
else:
print("Wrong Input") # here you also want to retry
calculate() # but not by recursing
again() # and definitely not call again
def again():
print("Do you wanna calculate again? ")
answer = input("(Y/N) ").lower()
if answer == "y":
calculate()
elif answer == "n":
exit # what is this exit ?
else:
print("Wrong Input")
again() # also don't recurse this, loop if you want
calculate()

Python: How to easily make specific string characters the only possible input

I'm a beginner to coding, and I'm still doing my "first" calculator, and I was wondering how to make only 5 characters ("-" "+" "/" "x" "^") into the only possible input the user can answer, or it will result in a message saying "Invalid", sorry for my limited knowledge about this, it's also my first post here, thanks in advance! This is what I did so far -
try:
number_1 = float(input("Insert number 1 here: "))
sign = str(input("+ - / x ^: "))
number_2 = float(input("Insert number 2 here: "))
except ValueError:
print("Invalid")
exit()
if sign != "-" "+" "/" "x" "^":
print("Invalid")
exit()
elif sign == "-":
print(number_1 - number_2)
elif sign == "+":
print(number_2 + number_1)
elif sign == "/":
if number_2 == 0:
print("Invalid")
exit()
print(number_1 / number_2)
elif sign == "x":
print(number_1 * number_2)
elif sign == "^":
print(number_1 ** number_2)
else:
print("Invalid")
You can use the power of functions! Make a function that repeatedly asks for user input until they give you something valid!
def ask_float(title):
while True:
try:
return float(input(title))
except ValueError:
print("Invalid choice. Try again!")
def ask_sign():
while True:
sign = input("+ - / x ^: ").strip()
if sign in ("+", "-", "/", "x", "^"):
return sign
print("Invalid choice. Try again!")
Now in your code you can do:
number_1 = ask_number("Insert number 1 here: ")
sign = ask_sign()
number_2 = ask_number("Insert number 2 here: ")

PYTHON 'result' is not defined File "<string>", line 64, in <module> File "<string>", line 40, in cont

def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
result = number_1 + number_2
print(number_1, "+", number_2, "=", result)
elif operation == '-':
result = number_1 - number_2
print(number_1, "-", number_2, "=", result)
elif operation == '*':
result = number_1 * number_2
print(number_1, "*", number_2, "=", result)
elif operation == '/':
result = number_1 / number_2
print(number_1, "/", number_2, "=", result)
else:
print('You have not typed a valid operator, please run the program again.')
return result
def cont():
calc_again = input("Do you want to continue?")
if calc_again.upper() == 'Y':
Tempresult = result
cntr = 0
while cntr == 0:
num3 = int(input("Enter next number: "))
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
if operation == '+':
result1 = Tempresult + num3
print(result1)
else:
print('hi')
else:
print('See you later.')
calculate()
cont()
Your program is throwing error because result is local variable of calculate() . In order to access it in cont() , you have to make it global .
def calculate():
#global variable
global result
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
result = number_1 + number_2
print(number_1, "+", number_2, "=", result)
elif operation == '-':
result = number_1 - number_2
print(number_1, "-", number_2, "=", result)
elif operation == '*':
result = number_1 * number_2
print(number_1, "*", number_2, "=", result)
elif operation == '/':
result = number_1 / number_2
print(number_1, "/", number_2, "=", result)
else:
print('You have not typed a valid operator, please run the program again.')
return result
def cont():
global result
calc_again = input("Do you want to continue?")
if calc_again.upper() == 'Y':
Tempresult = result
cntr = 0
while cntr == 0:
num3 = int(input("Enter next number: "))
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
if operation == '+':
result1 = Tempresult + num3
print(result1)
else:
print('hi')
else:
print('See you later.')
#variable declaration
result=None
calculate()
cont()
The result variable is local. Define the result variable globally. And, use global result inside the function implementation, to instruct the function not to create a new variable result, rather update the global variable.
Here is a hint.
result = 0 # default value
def function(n1, n2, operation):
global result
if operation == '+':
result = n1 + n2
return result
else:
return 0
Digressing a bit from the question, give a thought about the following code (python3+):
def function(n1, n2, operation):
if operation == '+':
print(f'{n1} + {n2} = {n1+n2}')
return n1 + n2
else:
return 0

How to make a calculator in Python 3

I need to create a calculator in Python that can perform all of these tasks. I have gotten this far with my code to do addition, subtraction, multiplication, and division. Can someone show me what to add to my code to add log, power, Pythagorean theorem, and factorial to my calculator? These are all the requirements for my calculator below.
Each mathematic operation needs to be its own function/method:
Addition - Takes up to 5 arguments,
Subtraction - - Takes 3 arguments,
Multiplication - Takes 4 arguments,
Division - Takes 2 arguments,
Log - Takes 1 argument,
Raise a number to a power ex. X squared,
Solve Pythagorean theorem,
Factorial
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
else:
print('You have not typed a valid operator, please run the program again.')
# Add again() function to calculate() function
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
calculate()
It's just the ideas of your requested functions. I added some of them to your calculator. You can also change the hints that you want to show to the user.
PS: Better to use while for the calculator loop.
import math
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
! for factorial
log for logarithm(number, base)
hypot for Pythagorean
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
elif operation == '!':
print(math.factorial(number_1))
print(math.factorial(number_2))
elif operation == 'log':
print(math.log(number_1, number_2))
elif operation == 'hypot':
print(math.hypot(number_1, number_2))
else:
print('You have not typed a valid operator, please run the program again.')
# Add again() function to calculate() function
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
calculate()
I updated the answer based on the comment; you want to take a variable number of inputs from a user like n numbers. I used add() for your situation to answer your exact issue and removed additional codes.
def add(numbers_list):
return sum(numbers_list)
if __name__ == "__main__":
while(True):
number_of_inputs = int(input('Number of inputs? '))
numbers = [float(input(f'Please enter a number({i + 1}): ')) for i in range(number_of_inputs)]
print(add(numbers))

What does getting a string index out of range error mean?

I am making a calculator in python 3, and I made a function to check for letters in the input. When it runs the letter check though, it gives me an error of string index out of range. Here is the code:
while True:
num = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
op = input("What operation would you like to use(+,-,*,/,**): ")
num1 = input("What is the first number you want to use: ")
length1 = len(num1)
lc1 = 0
def letterCheck1():
global num1
global length1
global lc1
while lc1 <= length1:
if num1[lc1] in num:
num1 = input("No letters, just numbers: ")
else:
lc1 = lc1 + 1
while True:
letterCheck1()
if len(num1) == 0:
num1 = input("Actually enter something: ")
continue
else:
break
num2 = input ("What is the second number you want to use: ")
length2 = len(num2)
lc2 = 0
def letterCheck2():
global num2
global length2
global lc2
while lc2 <= length2:
if num2[lc2] in num:
num2 = input("No letters, just numbers: ")
else:
lc2 = lc2 + 1
while True:
while True:
if op == "/" and num2 == "0":
num2 = input("It is impossible to divide a number by 0. Try again: ")
continue
else:
break
letterCheck2()
if len(num2) == 0:
num2 = input("Enter more than 0 numbers please: ")
continue
else:
break
if op == "+":
print (float(num1) + float(num2))
elif op == "-":
print (float(num1) - float(num2))
elif op == "*":
print (float(num1) * float(num2))
elif op == "/":
print (float(num1) / float(num2))
elif op == "**":
print (float(num1) ** float(num2))
again = input("Would you like to do another problem? 1(Yes), 2(No): ")
while True:
if again != "1" or again != "2":
again = input("Please enter 1(Yes), or 2(No): ")
continue
else:
break
if again == "1":
continue
elif again == "2":
leave = input("You are about to exit, do you want to continue? 1(Yes), 2(No): ")
while True:
if leave != ("1" or "2"):
leave = input("Please enter 1(Yes), or 2(No): ")
continue
else:
break
if leave == '1':
continue
elif leave == '2':
break
Indexing from 0 to len(num1) - 1. Fix this
while lc1 < length1
and this
while lc2 < length2
Here is a much cleaner way to do it:
def get_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
# not a float, try again
pass
# division is the only operation that requires more than a one-liner
def op_div(a, b):
if b == 0:
print("Dividing by 0 makes the universe explode. Don't do that!")
return None
else:
return a / b
# dispatch table - look up a string to get the corresponding function
ops = {
'*': lambda a,b: a * b,
'/': op_div,
'+': lambda a,b: a + b,
'-': lambda a,b: a - b,
'**': lambda a,b: a ** b
}
def main():
while True:
op = input("What operation would you like to use? [+, -, *, /, **, q to quit] ").strip().lower()
if op == "q":
print("Goodbye!")
break
elif op not in ops:
print("I don't know that operation")
else:
a = get_float("Enter the first number: ")
b = get_float("Enter the second number: ")
res = ops[op](a, b)
print("{} {} {} = {}".format(a, op, b, res))
if __name__=="__main__":
main()

Categories

Resources