How to fix "undefined name" error message in Python? - python-3.x

I am creating a simple calculator with Python as my first "bigger" project.
I am trying to use def function and when i am trying to call that function it gives "undefined name" error message.
while True:
print ("Options: ")
print ("Enter '+' to add two numbers")
print ("Enter '-' to subtract two numbers")
print ("Enter '*' to multiply two numbers")
print ("Enter '/' to divide two numbers")
print ("Enter 'quit' to end the program")
user_input = input(": ")
def calculation (argnum1, argnum2):
argnum1 = float (input("Enter your fist number: "))
argnum2 = float (input("Enter your second number: "))
number = argnum1
number = argnum2
result = argnum1 + argnum2
print (result)
print("-"*25)
return number
return result
if user_input == "quit":
break
elif user_input == "+":
calculation (argnum1, argnum2)
I expect the output of argnum1 + argnum 2 result.

You have needlessly defined your function to take two parameters, which you cannot provide as they are defined inside the function:
def calculation (argnum1, argnum2): # argnum1 and argnum2 are immediately discarded
argnum1 = float (input("Enter your fist number: ")) # argnum1 is defined here
argnum2 = float (input("Enter your second number: "))
# do things with argnum1 and argnum2
...
calculation(argnum1, argnum2) # argnum1 and argnum2 are not defined yet
Note that the body of a function is executed only when the function is called. By the time you call calculation, argnum1 and argnum2 are not defined - and even then, they only get defined in another scope.
Ideally, move the input call outside of your function:
def calculation (argnum1, argnum2):
# do things with argnum1 and argnum2
...
argnum1 = float (input("Enter your fist number: ")) # argnum1 is defined here
argnum2 = float (input("Enter your second number: "))
calculation(argnum1, argnum2)
Note that you should define your function outside the loop. Otherwise, it is needlessly redefined on every iteration. There is also no point in having multiple return statements after one another.
Your code should look like this:
def add(argnum1, argnum2):
result = argnum1 + argnum2
print (result)
print("-"*25)
return result
while True:
print ("Options: ")
print ("Enter '+' to add two numbers")
print ("Enter '-' to subtract two numbers")
print ("Enter '*' to multiply two numbers")
print ("Enter '/' to divide two numbers")
print ("Enter 'quit' to end the program")
user_input = input(": ")
if user_input == "quit":
break
elif user_input == "+":
argnum1 = float (input("Enter your fist number: "))
argnum2 = float (input("Enter your second number: "))
add(argnum1, argnum2)

You can move the function definition out of the while block.
def calculation():
argnum1 = float(input("Enter your fist number: "))
argnum2 = float(input("Enter your second number: "))
result = argnum1 + argnum2
print(result)
return result
while True:
print("Options: ")
print("Enter '+' to add two numbers")
print("Enter '-' to subtract two numbers")
print("Enter '*' to multiply two numbers")
print("Enter '/' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(": ")
if user_input == "quit":
break
elif user_input == "+":
calculation()

Related

Finding the sum of a list created by a user

I am having trouble getting the sum of the list inputted by the user, I have tried multiple ways, I just need help in what I can do to the sum of the list. Thanks, for any help.
import statistics
data=[]
while True:
num = input("Enter a number (type quit to leave): ")
data.append(num)
if num == "quit":
data.remove("quit")
break
def Average(data):
return sum(data) / len(data)
print(*data, sep=", ")
data.sort()
print("The max value entered is: ", max(data))
print("The min value entered is: ", min(data))
print("Sorted list: ", data)
print("First and Last removed: ", (data[1:-1]))
print("The List average is: ", sum(data))
data=[]
while True:
num = input("Enter a number (type quit to leave): ")
data.append(num)
if num == "quit":
data.remove("quit")
break
for i in range(0, len(data)):
data[i] = int(data[i])
print(*data, sep=", ")
data.sort()
print("The max value entered is: ", max(data))
print("The min value entered is: ", min(data))
print("Sorted list: ", data)
print("First and Last removed: ", (data[1:-1]))
print("The List average is: ", sum(data))

Python Try-except doesn't output what expected

print("Give me two numbers, I'll sum them")
print("Enter 'q' to quit")
while True:
num1 = input("Please, enter a number here: ")
if num1 == 'q':
break
num2 = input("Please, enter a number here: ")
if num2 == 'q':
break
try:
sum = int(num1) + int(num2)
except ValueError:
print("'q' entered, program exit 0")
else:
print(sum)
Hi the above program in Python3 works fine when numbers are inputted.
But when I input q, it just exits with no exception.
May you please assist me with this issue?
Thank you very much indeed.
the break statement will exit your loop without printing anything, because your try-except test is after breaks.
Here is what you can do:
print("Give me two numbers, I'll sum them")
print("Enter 'q' to quit")
while True:
num1 = input("Please, enter a number here: ")
if num1 == 'q':
print("'q' entered, program exit 0")
break
num2 = input("Please, enter a number here: ")
if num2 == 'q':
print("'q' entered, program exit 0")
break
if not num1.isdecimal() or not num2.isdecimal():
print('Wrong input, please enter decimal numbers !')
continue
sum = int(num1) + int(num2)
print(sum)

Code running despite no input being given (python)

When the user enters nothing, it is supposed to loop back and ask the question again. It performs correctly with every other type of input.
Here is the code:
string = ""
def str_analysis(string):
while True:
if string.isdigit():
if int(string) > 99:
print(str(string)+ " is a pretty big number!")
break
else:
print(str(string)+ " is a smaller number than expected")
break
elif string.isalpha():
print(string + " is an alphabetical character")
break
elif string == "":
print("")
else:
print(string + " is a surprise! It's neither all alpha nor all digit characters!")
break
print(str_analysis(input("Enter word or integer: ")))
There are a few things in your code that make no sense.
1:
print(str_analysis(input("Enter word or integer: ")))
You are trying to print the output of a function that has no return value
2:
It cant loop back and ask the question again, because the input is not taken inside of the function.
3:
If the string is empty you dont break the code but constantly print newlines.
Here is some code wich I think should do what you wanted:
def str_analasys():
while True:
string = input("Enter word or integer: ")
if string == '':
continue
elif string.isdigit():
if int(string) > 99:
print(str(string)+ " is a pretty big number!")
else:
print(str(string)+ " is a smaller number than expected")
elif string.isalpha():
print(string + " is an alphabetical character")
else:
print(string + " is a surprise! It's neither all alpha nor all digit characters!")
break
str_analasys()
This because when string is empty you are just printing an empty ""
elif string == "":
print("")
# break it here or take input again
# break or string = input()

print outside while prints twice python3

I have this assignment I have been working on
temperatures = []
def decision():
answer = input("Do you want to enter a temperature?" +
"\"y\" for yes. \"n\" for no: ")
getTemp(answer)
def getTemp(answer):
while answer == "y" or answer == "Y":
temp = int(input("Enter a temperature: "))
temperatures.append(temp)
print("\nTemperature Entered!\n")
answer = " "
decision()
print("Temperatures entered: ", temperatures)
def main():
decision()
main()
The problem is when I enter a temperature then press n to exit the while loop, the final output is more than one print statement. For example if I input:(y's == yes)
y
3
y
5
n
the output is
Temperatures entered: [3,5]
Temperatures entered: [3,5]
Temperatures entered: [3,5]
Any help would be great...Thanks
The issue is that getTemp is being called multiple times, due to it calling decision, which in turn calls getTemp. Instead, you should only print the temperatures after you exit the above chain, so you should move the print to after you call decision in main, so main should be:
def main():
decision()
print("Temperatures entered: ", temperatures)
and getTemp should be
def getTemp(answer):
while answer == "y" or answer == "Y":
temp = int(input("Enter a temperature: "))
temperatures.append(temp)
print("\nTemperature Entered!\n")
answer = " "
decision()
You are recursing. If you ended up wanting to enter, say, 500000000 temperatures, you would definitely cause a stack overflow.
Your print executes at the end of each decision() execution. I suggest restructuring your code to not recurse (to save yourself from allocating forever) or at the very least put your print statement in your main.
For example, you could do this
temperatures = []
def decision():
while input("Do you want to enter a temperature?\n" +
"\"y\" for yes. \"n\" for no: ") in "yY":
getTemp()
def getTemp():
temp = int(input("Enter a temperature: "))
temperatures.append(temp)
print("\nTemperature Entered!\n")
def main():
decision()
print("Temperatures entered: ", temperatures)
main()

Save the output of for-loop as a list or tuple

How do I save the output of a for-loop as a list or tuple?
# finding prime numbers in given range
num_range = int(input("Enter a number: "))
print ("Below are the Prime Numbers")
for num in range(2,num_range+1):
# print (num,"is taken as num")
for i in range(2,num):
# print (i, "is taken as i")
if num % i == 0:
break
else:
print (num)
In order to save the prime numbers,check the code below
num_range = int(input("Enter a number: "))
p_num = []
print ("Below are the Prime Numbers")
for num in range(2,num_range+1):
# print (num,"is taken as num")
for i in range(2,num):
# print (i, "is taken as i")
if num % i == 0:
break
else:
p_num.append(num)
print (num)
print the numbers as and when you find OR print the list
print p_num

Resources