simple python calculator won't run - python

Ok, what is wrong with my code? I press run and it doesn't give me anything. at get_num it says "too many positional arguments" and after that its just having issues. I'm not sure what I'm doing wrong.
it says "no value for num 1 argument in function to call" and "no value for num 2 argument in function to call" "unused variable answer"
def main(): #control
operation()
get_num(operation)
if operation == "+":
answer = addition()
elif operation == "*":
answer = multiplication()
elif operation == "-":
answer = subtraction()
else:
answer = division()
def operation(): #prompts the user to enter a mathematical symbol & returns that symbol
print("Enter one of the symbols when asked what operation you would like to preform")
operation = input("Would you like to multiply (*), add (+), subtract (-), or divide(/)? ")
return operation
def get_num(): #prompts the user to enter a single integers & returns that value
print("Enter two numbers you would like to calculate")
num1 = float(input("What is the first number you want to calculate? "))
num2 = float(input("What is the second number you want to calculate? "))
return num1
return num2
def addition(num1, num2): #performs addition of the 2 numbers & returns the sum
addition = num1 + num2
return addition
def subtraction(num1, num2): #performs subtraction of the second number from the first & returns the difference
subtraction = num1 - num2
return subtraction
def multiplication(num1, num2): #performs multiplication of the 2 numbers & returns the product
multiplication = num1 * num2
return multiplication
def division(num1, num2): #if the second number is not zero, performs division of the first number (numerator) by the second number (denominator) and returns the quotient; if the second number is zero, doe not perform the division, but displays a message and returns a zero
division = num1 / num2
return division
if num2 == "0":
print("Error, cannot divide by 0")
def show_answer(answer): #displays the answer from the operation
if operation == '*':
print("The answer for your problem is", multiplication)
elif operation == '-':
print("The answer for your problem is", subtraction)
elif operation == '+':
print("The answer for your problem is", addition)
elif operation == '/':
print("The answer for your problem is", division)
else:
print("error")

Hey your program is written in neat manner but you need to pass the variable to the function ..... You can't define global variable like this

First of all you wrote get_num(operation) but then your function has 0 arguments: def get_num():

Area for improvement:
Python is a scripting language, so you must call the main() function at the bottom to kick it off
use raw_input("message") rather than input("mesage") and convert it yourself using operator = str(raw_input("message"))
You are calling get_num(operation) but operation() is a function, not a value. Maybe you should store the return value of get_num(operation) into a variable like operator = get_num(operation)
Here is how I would make some improvements to your code:
def main(): #control
operator = operation()
nums = get_num()
if operator == '+':
answer = addition(nums[0], nums[1])
elif operator == '*':
answer = multiplication(nums[0], nums[1])
elif operator == '-':
answer = subtraction(nums[0], nums[1])
elif operator == '/':
answer = division(nums[0], nums[1])
else:
raise ValueError("'" + operator + "' Operand not recognized")
# Display result
answer = str(answer)
print(str(nums[0]) + operator + str(nums[1]) + " = " + answer)
def operation(): #prompts the user to enter a mathematical symbol & returns that symbol
print("Enter one of the symbols when asked what operation you would like to preform")
operator = raw_input("Would you like to multiply (*), add (+), subtract (-), or divide(/)? ")
# Convert it to a string
return str(operator)
# NOTE - no need to pass the operator
def get_num(): #prompts the user to enter a single integers & returns that value
print("Enter two numbers you would like to calculate")
num1 = float(raw_input("What is the first number you want to calculate? "))
num2 = float(raw_input("What is the second number you want to calculate? "))
# NOTE - Return as an array rather than 2 return statements
return [num1, num2]
def addition(num1, num2): #performs addition of the 2 numbers & returns the sum
addition = num1 + num2
return addition
def subtraction(num1, num2): #performs subtraction of the second number from the first & returns the difference
subtraction = num1 - num2
return subtraction
def multiplication(num1, num2): #performs multiplication of the 2 numbers & returns the product
multiplication = num1 * num2
return multiplication
def division(num1, num2): #if the second number is not zero, performs division of the first number (numerator) by the second number (denominator) and returns the quotient; if the second number is zero, doe not perform the division, but displays a message and returns a zero
# NOTE - Throw an error if denominator is 0
if num2 == 0:
raise ValueError("Divistion by zero")
division = num1 / num2
return division
# Remember to call main() to kick off the program
main()

Here are some of the problems I see with your question/code:
Your code is poorly indented. I can't really try your code because of all of this weird indentions you have.
Your function call must have the same amount of argument like when you defined it func(x, y) must always be declared with 2 variables like func('Hello', 'World')
returnreturns a data but doesn't save itself. You must assign the value to a variable if you have a use for that data.
You don't quite understand local and global scopes of variables
Anyway avoid asking "why is my code not working" questions
Try this code:
def main(): #control
operation = operate()
num1, num2 = get_num()
if operation == "+":
answer = addition(num1, num2)
elif operation == "*":
answer = multiplication(num1, num2)
elif operation == "-":
answer = subtraction(num1, num2)
elif operation == "/":
answer = division(num1, num2)
else:
print ("Invalid Operation")
show_answer(answer)
def operate(): #prompts the user to enter a mathematical symbol & returns that symbol
print("Enter one of the symbols when asked what operation you would like to preform")
operation = input("Would you like to multiply (*), add (+), subtract (-), or divide(/)? ")
return operation
def get_num(): #prompts the user to enter a single integers & returns that value
print("Enter two numbers you would like to calculate")
num1 = float(input("What is the first number you want to calculate? "))
num2 = float(input("What is the second number you want to calculate? "))
return num1, num2
def addition(num1, num2): #performs addition of the 2 numbers & returns the sum
addition = num1 + num2
return addition
def subtraction(num1, num2): #performs subtraction of the second number from the first & returns the difference
subtraction = num1 - num2
return subtraction
def multiplication(num1, num2): #performs multiplication of the 2 numbers & returns the product
multiplication = num1 * num2
return multiplication
def division(num1, num2): #if the second number is not zero, performs division of the first number (numerator) by the second number (denominator) and returns the quotient; if the second number is zero, doe not perform the division, but displays a message and returns a zero
try:
division = num1 / num2
return division
except ZeroDivisionError:
print ("Error, cannot be divided by 0")
def show_answer(answer):
print ("The answer for your problem is", answer)
main()
You can also just change your else-if statement for your divison to check whether the value of num2 is 0:
elif operation == '/':
if num2 == 0:
return ('Error, cannot be divided by 0')
else:
answer = division(num1, num2)

Related

Why does my if-statement always evaluate to True? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 months ago.
I have the following code:
print('''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer\n''')
while 1 > 0:
function = input("Enter the type of function you want to do:\n")
if function == 'addition' or 'Addition' or 'ADDITION' or 'aDDITION' or '+' or 'add':
num1 = int(input("Enter your number:\n"))
num2 = int(input("Enter your number:\n"))
total = num1 + num2
print('Your answer is ' + str(total))
continue
elif function == 'subtraction' or 'Subtraction' or 'SUBTRACTION' or 'sUBTRACTION' or '-' or 'subtract':
num1 = int(input("Enter the number you want to subtract from:\n"))
num2 = int(input(f"Enter the number you want to subtract from {num1}:\n"))
total = num1 - num2
print('Your answer is' + str(total))
continue
elif function == 'multiplication' or 'multiply' or '*' or 'Multiply' or 'MULTIPLY':
num1 = int(input("Enter the number you want to multiply:\n"))
num2 = int(input(f"Enter the number you want to multiply {num1} wit:\n"))
total = num1 * num2
print('Your answer is' + str(total))
continue
elif function == 'divide' or 'DIVIDE' or '/':
num1 = int(input("Enter the number you want to divide:\n"))
num2 = int(input(f"Enter the number you want to divisor for {num1}:\n"))
total = num1 / num2
print('Your answer is' + str(total))
continue
elif function == 'stop' or 'STOP' or 'Stop' or 'sTOP':
break
else:
print('Can\'t understant what you want to do please write your choice in the format below\n' + '''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer''')
I have a infinite loop which asks you to enter a function. And I have if-elif-else statements to see, which function the user inputed. I want the function the user inputed to be the one that gets activated, but for a reason it always does addition. Any help is appreciated!
In python a string can get evaluated as a boolean. An empty string returns False and a non-empty one returns True.
Example:
print(bool("A non empty string"))
Output:
True
Example:
print(bool("")) # <---- Empty String
Output:
False
In the if statements you have, you wrote:
if function == 'addition' or 'Addition' or 'ADDITION' or 'aDDITION' or '+' or 'add':
...
Python first checks if function equals "addition" then if not it continues to the next condition and that is simply "Addition". Since there is no comparison or anything like that it simply gets evaluated to True and, thus the if statement becomes True, because you used or (So only one of the conditions have to be True.)
To fix this you have to add function == ... to your every check as such:
if function == 'addition' or function == 'Addition' or function == 'ADDITION' or function == 'aDDITION' or function == '+' or function == 'add':
...
To make this more readable you can use the in keyword and check if function is in the tuple as such:
if function in ('addition', 'Addition', 'ADDITION', 'aDDITION', '+', 'add'):
...
And to make this even better you can upper case the function and check if function is ADDITION only not every combination like "Addition", "aDdition"...
This is how you do it:
if function.upper() in ('ADDITION', '+', 'ADD'):
...
And here is the full working code (I also did a little bit of cleaning):
print('''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer\n''')
while True:
function = input("Enter the type of function you want to do:\n").upper()
if function in ('ADDITION', '+', 'ADD'):
num1 = int(input("Enter your number:\n"))
num2 = int(input("Enter your number:\n"))
total = num1 + num2
print(f'Your answer is {total}')
continue
elif function in ('SUBTRACTION', '-', 'SUBTRACT'):
num1 = int(input("Enter the number you want to subtract from:\n"))
num2 = int(input(f"Enter the number you want to subtract from {num1}:\n"))
total = num1 - num2
print(f'Your answer is {total}')
continue
elif function in ('MULTIPLICATION', '*', 'MULTIPLY'):
num1 = int(input("Enter the number you want to multiply:\n"))
num2 = int(input(f"Enter the number you want to multiply {num1} wit:\n"))
total = num1 * num2
print(f'Your answer is {total}')
continue
elif function in ('DIVISION', '/', 'DIVIDE'):
num1 = int(input("Enter the number you want to divide:\n"))
num2 = int(input(f"Enter the number you want to divisor for {num1}:\n"))
total = num1 / num2
print(f'Your answer is {total}')
continue
elif function == 'STOP':
break
else:
print('Can\'t understand what you want to do please write your choice in the format below\n' + '''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer''')

I'm creating a (very crude) calculator and would like to know what's wrong with this code

# Pick the numbers you'd like to use
number1 = (input('What is the first number?\n'))
number2 = (input('What is the second number?\n'))
# Choose what to do with those numbers
Choice = input('Would you like to add, subtract, multiply or divide?\n ')
# Where the calculating happens, if it doesn't go through the error message asking you to use numbers will happen
try :
# Converting the numbers from str into float, if this doesnt happen it means numbers were not used
num1 = float(number1)
num2 = float(number2)
if Choice is add :
answer = num1 + num2
elif Choice is subtract :
answer = num1 - num2
elif Choice is divide :
answer = num1/num2
elif Choice is multiply
answer = num1 * num2
print(answer)
# The error message if the numbers you gave werent in numeric form
except :
print('Please choose proper numbers in numeric form instead of letter/words')
This is the code, the issue I get is:
'File "main.py", line 13
elif Choice is subtract :
^
SyntaxError: invalid syntax'
Any help would be appreciated, thanks :). (If this code just wouldn't work at all, please lmk. Im currently going through a book on how to code and thought this would be fun to try since I just learned about booleans and variables)
I think you mean to do this:
if Choice == 'add':
answer = num1 + num2
elif Choice == 'subtract':
answer = num1 - num2
elif Choice == 'divide':
answer = num1/num2
elif Choice == 'multiply':
answer = num1 * num2
Be careful with indentation. If you have a single if / elseif / elseif / elseif / else chain, each condition should be at the same indent level, and each body should match its condition plus one indent (typically 4 spaces or 1 tab).
To compare a string captured from the user with input() to a literal string, you would do:
if Choice == 'add':
You need to specify the quotation marks around 'add', otherwise it would try to reference a variable called add, which isn't defined.
For == vs is when checking the string, see Why does comparing strings using either '==' or 'is' sometimes produce a different result?

Is this an efficient calculator in Python?

Is this an efficient calculator in Python?
def calculator():
print("\nBasic Calculator.\n")
num_1 = input("Enter your first number: ")
operation = input("Enter your operation: ")
num_2 = input("Enter your second number: ")
if operation == ("+"):
sum = float(num_1) + float(num_2)
print ("The answer is:",(sum))
elif operation == ("-"):
sum = float(num_1) - float(num_2)
print ("The answer is:",(sum))
elif operation == ("*"):
sum = float(num_1) * float(num_2)
print ("The answer is:",(sum))
elif operation == ("/") and num_2 == ("0"):
print ("\nYou cannot divide by zero.")
elif operation == ("/"):
sum = float(num_1) / float(num_2)
print ("The answer is:",(sum))
else:
print("Invalid Operation.")
restart = input("\nDo you want to enter another equation? Yes or No?").lower()
if restart == ("yes"):
calculator()
else:
print ("\nEnding Program.")
quit()
calculator()
You can use eval()
a = 1
b = 2
operation = '/'
print(eval(f'{a} {operation} {b}'))
0.5
Handle shenanigans by users:
a = 1
b = 0
operation = '/'
try:
print(eval(f'{a} {operation} {b}'))
except Exception as exp:
print(exp)
Here is another basic example:
operations = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
}
try:
x, sign, y = input("Enter expression separated by whitespace(ex: 2 + 3): ").split()
if sign == '0':
break
else:
print(operations[sign](int(x), int(y)))
except (ValueError, KeyError, ZeroDivisionError):
print("Something went wrong, check your input")
It's decent, but reviews of working code belong on CodeReview.SE, not here.
Call the result variable result instead of sum, that obviously only is meaningful for addition.
As per AlexanderLekontsev's answer, you don't need a huge big if...else ladder that always computes result and prints the output. A dispatch dictionary to (binary or unary) lambda function is better. You could have all the functions be binary, and default arg2=None, that way you can handle unary functions.
You're assuming the user types in valid floats in response to num_1, num_2. But what if they press return? or type pi or e? or 'help' or :-D etc. You should catch the exception ValueError: could not convert string to floatand display the user's invalid input back to them, "expected a number"(/"operator").
You only need num_2 if operation is a binary not a unary operation, but future stuff like sqrt, log, log10, trigonometrics (sin, cos, tan), hyperbolics and their inverses (arc-fns) are all unary operations. Just something to keep in mind for the future. Don't hardwire your parser to one expected input sequence.
Inputting numbers could get more complicated in future. What if you wanted to support both hexadecimal 7e8 and float/general/exponential notation 7e8? You might need multiple try...except clauses. You might add a HEX mode in future. But then you'll need to generalize from num1 to say arg1, and if arg1 == HEX then enable(/toggle) hex mode, and recurse/loop.
Suggest printing print("Invalid Operation: must be +,-,*,/,..."), this actually tells the user which operations are legal. So: % isn't, neither is ^, neither is log, cos, sqrt etc.
So if you implement the above, you can support things like e^x
Supporting parentheses would require recursion.
Try this:
def calculate(num1, num2, operator):
operator = operator.strip()
if operator.strip() in ['+', '-', '*', '/']:
if operator == '/' and eval(num2) == 0:
return None
try:
result = eval(f'float({num1.strip()}) {operator} float({num2.strip()})')
except:
return ""
return result
num1 = '3'
num2 = '5'
operator = '+'
result = calculate(num1, num2, operator)
if result == '':
print('Wrong expression !')
elif result == None:
print('Dive bye zero !')
else:
print(f'The answe is {result} !')
Your code is alright but we can improvise by using eval()
print(" Basic Calculator ")
i = ""
while i != 'exit':
i = input(" Enter the expression to evaluate or type 'exit' to exit : ")
print(eval(i))
Here is a very clean and short calculator script:
num1 = float(input("Enter a number: "))
op = (input("Enter an operation: "))
num2 = float(input("Enter another number: "))
if op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "^":
print(num1 ** num2)
else:
print("error, you did not enter a supported operation")
Also if you were wondering ** means ^ or to the power of.
Try this:
this calculator will take several inputs, and you can choose to clear the values or to delete it before computing the result.
values_collector = [] #empty list for all values
multi = 1
total = 0
index = 0
print('''For addition press the +,
For Subtraction press the -
For division press the /
For Multiplication press the *''')
entries = int(input('Enter the number of the values you want to compute: '))
signs = input('Enter the sign: ')
while index < entries:
my_input = int(input('Enter your values: '))
values_collector.append(my_input)
index +=1
to_remove = input('Do you want to remove any values, enter Y for yes and N for no ').upper()
if to_remove == 'Y':
values_re=[]
x = 0
no_to_remove = int(input('How many variables do you want to remove: '))
while x < no_to_remove:
my_removed = int(input('Enter your values: '))
values_re.append(my_removed)
x +=1
for y in values_re:
values_collector.remove(y)
my_clear = input("Do you want to clear all the values press Y for yes and N for No ").upper()
if my_clear == 'Y':
values_collector.clear()
print('There is no values to compute because its cleared')
elif my_clear == 'N':
if signs == '+':
for x in range(len(values_collector)):
total +=values_collector[x]
elif signs == '-':
for x in range(len(values_collector)):
total -=values_collector[x]
elif signs == '*':
for x in range(len(values_collector)):
multi *=values_collector[x]
total = multi
elif signs == '/':
for x in range(len(values_collector)):
multi /=values_collector[x]
total = multi
print('The computation of all the values {} is {}'.format(values_collector, total))
enter code here

The same operator is used even after choosing a different one

The code uses operator that was chosen in the previous play even after choosing a different operator after opting to play again.
I've checked the functions again and still can't find where exactly the problem is.
import random
print "Welcome!"
def get_choice():
print "What are we practicing? \n1. Addition (+) \n2. Subtraction (-) \n3. Multiplication (*) \n4. Division (/)"
option = raw_input('> ')
while option != '+' and option != '-' and option != '*' and option != '/':
print "You typed %r which is not valid. Please enter \'+, -, *,or /\'" %(option)
option = raw_input('>')
return option
operation = get_choice()
def ask_question (operation):
numbers = []
for y in range(0,2):
x = random.randint(1,100)
numbers.append(x)
num1 = numbers[0]
num2 = numbers[1]
print num1, operation, num2
response = int(raw_input('>'))
return num1, num2, response
num1, num2, response = ask_question(operation)
def check_response(response):
if operation == '+':
answer = num1 + num2
elif operation == '-':
answer = num1 - num2
elif operation == '*':
answer = num1 * num2
else:
answer = num1 / num2
i = 0
if response == answer:
print "Correct!"
elif response != answer:
while i < 2:
print "Wrong! Try again: \n%r + %r" %(num1, num2)
i += 1
response = raw_input()
if response != answer and i >= 2:
print "Sorry. You run out of chances."
check_response(response)
def repeat():
while True:
print "Do you want to play again?"
again = raw_input('>')
if again == 'y' or again == 'Y':
get_choice()
ask_question(operation)
check_response(response)
else:
break
repeat()
Welcome! What are we practicing?
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
*
18 * 4
72 Correct! Do you want to play again?
y
What are we practicing?
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
+
94 * 83
The reason it gets stuck on one operation is you are not catching any return value from get_choice() when you call it within repeat(). I adjusted the raw_input() to input() so I could get it to work (I'm on python 3.X, and you should upgrade also since 2.X will be discontinued this year!), and it seems to work fine for me now:
def repeat():
while True:
print("Do you want to play again?")
again = input('>')
if again == 'y' or again == 'Y':
operation = get_choice() # you need to assign "operator" to the return value
ask_question(operation)
check_response(response)
else:
break
repeat()
Sample output:
Welcome!
What are we practicing?
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
> +
82 + 72
>154
Correct!
Do you want to play again?
>y
What are we practicing?
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
> -
57 - 28 # the sign did in fact change to -
>

Multiple inputs are needed for a basic calculator before resetting

My program is almost complete but I can't seem to allow the...
"Would you like to do more calculations? Enter (Y) for yes, or any ""other character for no. "
...output from going through without first entering my selection (e.g. "Y" or any other character") numerous times.
Output
I would really appreciate some help!
"""My First Program!!!"""
# Modules:
import time # Provides time-related functions
# Delayed text to give it a "Turing" feel
def calculator_print(*args, delay=1):
print(*args)
time.sleep(delay)
# Operations:
def add(num1, num2):
# Returns the sum of num1 and num2
return num1 + num2
def sub(num1, num2):
# Returns the difference of num1 and num2
return num1 - num2
def mul(num1, num2):
# Returns the product of num1 and num2
return num1 * num2
def div(num1, num2):
# Returns the quotient of num1 and num2
try:
return num1 / num2
except ZeroDivisionError:
# Handles division by zero
calculator_print("Division by zero cannot be done. You have broken the universe. Returning zero...")
return 0
def exp(num1, num2):
# Returns the result of num1 being the base and num2 being the exponent
return num1 ** num2
# Run operational functions:
def run_operation(operation, num1, num2):
# Determine operation
if operation == 1:
calculator_print("Adding...\n")
calculator_print(num1, "+", num2, "=", add(num1, num2))
elif operation == 2:
calculator_print("Subtracting...\n")
calculator_print(num1, "-", num2, "=", sub(num1, num2))
elif operation == 3:
calculator_print("Multiplying...\n")
calculator_print(num1, "*", num2, "=", mul(num1, num2))
elif operation == 4:
calculator_print("Dividing...\n")
calculator_print(num1, "/", num2, "=", div(num1, num2))
elif operation == 5:
calculator_print("Exponentiating...\n")
calculator_print(num1, "^", num2, "=", exp(num1, num2))
else:
calculator_print("I don't understand. Please try again.")
def main():
# Ask if the user wants to do more calculations or exit:
def restart(response):
# uses "in" to check multiple values,
# a replacement for (response == "Y" or response == "y")
# which is longer and harder to read.
if response in ("Y", "y"):
return True
else:
calculator_print("Thank you for calculating with me!")
calculator_print("BEEP BOOP BEEP!")
calculator_print("Goodbye.")
return False
# Main functions:
# Title Sequence
calculator_print('\n\nThe Sonderfox Calculator\n\n')
calculator_print(' ----LOADING----\n\n')
calculator_print('Hello. I am your personal calculator. \nBEEP BOOP BEEP. \n\n')
while True: # Loops if user would like to restart program
try:
# Acquire user input
num1 = (int(input("What is number 1? ")))
num2 = (int(input("What is number 2? ")))
operation = int(input("What would you like to do? \n1. Addition, 2. Subtraction, 3. Multiplication, "
"4. Division, 5. Exponentiation \nPlease choose an operation: "))
except (NameError, ValueError): # Handles any value errors
calculator_print("Invalid input. Please try again.")
return
run_operation(operation, num1, num2)
# Ask if the user wants to do more calculations or exit:
restart_msg = input("Would you like to do more calculations? Enter (Y) for yes, or any "
"other character for no. ")
if not restart(str(input(restart_msg))): # uses the function I wrote
return
main()
If this is really your first program, that's truly impressive!
So, I've pasted the code we want to focus on below:
restart_msg = input("Would you like to do more calculations? Enter (Y) for yes, or any other character for no. ")
if not restart(str(input(restart_msg))): # uses the function I wrote
return # Stop the program
In the first line, the computer prompts for an input with "Would you like to do more calculations?" (and so on). It then stores that first input in the variable restart_msg. Then, in the second line, you call restart(str(input(restart_msg))). Since that contains a call to input() and passes restart_msg as the only parameter, the computer prompts for an input by outputting whatever you just entered. It stores that entry in a string, and passes it to restart().
It seems like this is your intention in the second line:
if not restart(str(restart_msg)):
That way, the computer converts the first input you entered to a string by passing it through str(), and passes that through your restart function.
This is a pretty ambitious project, good luck!
You are asking for an input of an input. restart_msg = input() and then you do input(restart_msg).
Also note that there's no need to transform the input to string with str() as in python3 input() already returns a string.

Categories