If I run the following code while NOT indenting the print and input lines, my code works. Here is an example of code that works
def add(a, b):
try:
return float(a) + float(b)
except ValueError:
return print('Not a number')
print ("The first number you want to add?")
a = input("First no: ")
print ("What's the second number you want to add?")
b = input("Second no: ")
result = add(a, b)
print(result)
However if I indent the input and print lines I get a message that A is not defined
def add(a, b):
try:
return float(a) + float(b)
except ValueError:
return print('Not a number')
print ("The first number you want to add?")
a = input("First no: ")
print ("What's the second number you want to add?")
b = input("Second no: ")
result = add(a, b)
print(result)
Traceback (most recent call last):
File "/Users/jlangdon/PycharmProjects/untitled/Stuff.py", line 16, in <module>
result = add(a, b)
NameError: name 'a' is not defined
Process finished with exit code 1
.............Why can't I indent print and input? Thanks
Because the a and b in result = add(a, b) are not defined. You need to provide actual values to that function.
Example:
def add(a,b):
try:
return float(a) + float(b)
except ValueError:
print('Not a number')
print ("The first number you want to add?")
a = input("First no: ")
print ("What's the second number you want to add?")
b = input("Second no: ")
result = add(12.3,45.6)
print(result)
If you don't indent then:
a = input("First no: ")
Creates a, and:
b = input("Second no: ")
Creates b
If you indent a and b are not created, and here:
result = add(a, b)
You have an error.
That's because... a is not defined. How could it be? The first thing your code does is:
result = add(a,b)
But a has no value, nor does b. add never even gets called.
because a and b are defined inside the result function when you don't indent. which will only have to be seen as a variable defined only when the program run inside the function result, but result requires two parameters a and b which should be defined outside the function as main variable not inside. thats why the
Traceback (most recent call last):
File "/Users/jlangdon/PycharmProjects/untitled/Stuff.py", line 16, in
result = add(a, b)
NameError: name 'a' is not defined
Related
When I prompt the console to ask the user to input a number for the calculator, I want to check if what the user input is a number. In the first_input() I used a if else condition to check if what the user input was a number. Although if false the function is called again to prompt the user to type a number, it returns none once i try calculating it into my calculator, why is this and how can I properly return the number properly after the user fails to input a number?
# Operations variable
oper = "+-*/"
# Calculates basic operations
def calc(x, op, y):
for i in oper:
if i == str(op):
return eval(str(x) + op + str(y))
# Main function that controls the text-based calculator
def console_calculator():
def first_input():
x = input('Type your first number: ')
if x.isnumeric():
return x
else:
print('Please type in a number')
first_input()
def operation_input():
operat = input('Type one of the following, "+ - * /": ')
return operat
def next_input():
y = input('Type your next number: ')
return y
answer = calc(first_input(), operation_input(), next_input())
print(answer)
console_calculator()
I'd suggest a try/except block. This way it will return the integer itself especially since you're already turning them into strings in the eval block.
x = input('Type your first number: ')
try:
return int(x)
except ValueError:
print('Please type in a number')
...
Also to keep asking the user for an integer until they input the correct value I'd use a while loop.
Instead of using two functions for user input you can use single function call it two times. and you also need to add return before function call in user input.
def console_calculator():
def user_input():
x = input('Type your number: ')
if x.isnumeric():
return x
else:
print('Please type in a number')
return user_input()
def operation_input():
operat = input('Type one of the following, "+ - * /": ')
return operat
answer = calc(user_input(), operation_input(), user_input())
print(answer)
You actually hid the answer in your own question:
how can I properly return the number
You forgot to return in your else branch:
# Calculates basic operations
def calc(x, op, y):
for i in op:
if i == str(op):
return eval(str(x) + op + str(y))
# Main function that controls the text-based calculator
def console_calculator():
def first_input():
x = input('Type your first number: ')
if x.isnumeric():
return x
else:
print('Please type in a number')
return first_input() # missing return
def operation_input():
operat = input('Type one of the following, "+ - * /": ')
return operat
def next_input():
y = input('Type your next number: ')
return y
answer = calc(first_input(), operation_input(), next_input())
print(answer)
console_calculator()
But you also have a compilation error because you refer to oper but the parameter is called op.
This merely answers your question, but doesn't address the architecture (which others will, as they cover better implementations).
I'm facing a conditional logic problem here.
I want a value from user, but it should only be confined to either
'ABC','DEF' or'XYZ'
If not provided with one of the above, program should give the user another chance to enter until it gets the input only from it's expected values
My snippet is as follows:-
def foo():
inp_val=raw_input("Enter value\n>> ")
if inp_val.upper() not in {'ABC','DEF','XYZ'}:
print("Invalid Input")
foo()
return inp_val
inp = foo()
Output
Enter value
>> 42342d*#r2
Invalid Input
Enter value
>> abc
Checking inp in python console:-
>> inp
ABC #(Expected)
42342d*#r2 #(Actual)
Why is this happening?
I tried the reverse logic too:-
def bar():
inp_val=raw_input("Enter value\n>> ")
if inp_val.upper() in {'ABC','DEF','XYZ'}:
return inp_val
else:
print("invalid input")
bar()
inp = bar()
Output:
Enter value
>> 42342d*#r2
Invalid Input
Enter value
>> abc
In console:
>> inp
ABC #Expected
#(Actual)
How do I get the actual value?
You forgot to return foo() when recursively calling your function.
#!/usr/bin/python
def foo():
inp_val=raw_input("Enter value\n>> ")
if inp_val.upper() not in {'ABC','DEF','XYZ'}:
print("Invalid Input")
return foo()
return inp_val
inp = foo()
print(inp)
Effect:
~/sandbox » python a.py tracma01#londev1tracma01
Enter value
>> f
Invalid Input
Enter value
>> ABC
ABC
Try this.
def foo():
inp_val=input("Enter value\n>> ")
if inp_val.upper() not in {'ABC','DEF','XYZ'}:
print("Invalid Input")
return foo()
else:
return inp_val
inp = foo()
My own take on this:-
def bar():
temp = True
while temp:
inp_val = raw_input("Enter value\n>> ")
if inp_val.upper() in {'ABC','DEF','XYZ'}:
temp = False
return inp_val
else:
print("invalid input")
Sure it takes loops and not recursion, and is less efficient. But if want to save memory by not backtracking, try this.
In my python program, I have multiple functions defined, then a main function that also holds the menu. The menu is the first thing that should be displayed, but the program is attempting to run the defined functions that are before the main function, first. This is resulting in many problems. Any suggestions.
#!usr/bin/env python
import operator
saved_string = ''
def remove_letter():
return
def num_compare():
return
def print_string():
print saved_string
return
def calculator():
sign_dict = {"+": operator.add(), "-": operator.sub(), "*": operator.mul(), "&": operator.div()}
num1 = int(raw_input("First number: "))
sign = str(raw_input("Action: "))
num2 = int(raw_input("Second number: "))
print sign_dict[sign] (num1, num2)
return
def accept_store():
global saved_string
saved_string = str(raw_input("Enter string: "))
return
def main():
opt_list = [accept_store(),
calculator(),
print_string(),
num_compare(),
remove_letter()]
while(True):
print "SELLECT OPTIONS:"
print "1\tAccept and Store"
print "2\tCalculator"
print "3\tPrint String"
print "4\tNumber Compare"
print "5\tRemove Letter"
opt_choice = int(raw_input("SELLECTION: "))
opt_choice -= 1
opt_list[opt_choice]()
return
main()
() is a function call notation. So in opt_list, you're listing all the function calls, not the function names. You'd have to change it to:
opt_list = [fn1, fn2, ...]
Then call each function like:
for f in opt_list:
f()
I have spent the last few hours reading around on the net and looking at the Python online manual (currently using Python v2.7) but I'm still struggling to understand how I pass a variable from one function to another.
At the moment I am just starting out with something simple, to get my head around passing variables. I have 3 functions (one which will display a hello message), another that will ask for user input and the third that will take the user input and perform the calculation).
For the life of me I cant figure how to get the user input values into the calculation function. I thought that once I entered the values in the user input, I could send them to the calc function. But I cant.......I keep getting an error message:
calc = calculation(num1, num2)
NameError: global name 'num1' is not defined
Can someone point out where I am going wrong ? This is driving me nuts !
def main():
message()
input = user()
calc = cal(num1, num2)
def message():
print "Welcome message"
def user():
side_a = int(raw_input("Enter a: "))
side_b = int(raw_input("Enter b: "))
return side_a, side_b
def cal(num1, num2):
side_c = side_a + side_b
return side_c
So think of it like this:
You have a function (def user() ) which will return two values. You have to receive those two values and store them somewhere. In your main() you use variable "input" which is now have to hold two values as written. If you were to do:
print input
You'd get (value of side A, value of side B) passed back to you. If you instead wrote
print input[0]
It would print just side A. More easy (in my mind) would be having two variables standing by to receive the returned values:
input1, input2 = user()
Now in your def cal(num1,num2) it is expecting to receive two arguments and return one value. So your main should look like this:
def main()
message()
input = user()
calc = cal(input[0], input[1])
When you define your function, the variables you use (num1, num2) is how you are going to represent the inputs in that function. If you just pass the arguments num1, num2 they have no value as they were not declared in main. The names do not have to match, you just have to pass the right number(and type) of arguments.
So for example:
def sample(int1, int2, string):
number3 = number1 + number2
print(string1 + str(number3))
You could pass this raw data, or pass it variables. In this sample main, the printed output would be the same:
def main():
number1 = 2
number2 = 2
string1 = "two plus two equals: "
sample(2,2,"two plus two equals: ")
sample(number1,number2,string1)
Change what you have to
def main():
message()
num1, num2 = user() # grab the numbers from user fn and store them in num1, num2
calc = cal(num1, num2)
def message():
print "Welcome message"
def user():
side_a = int(raw_input("Enter a: "))
side_b = int(raw_input("Enter b: "))
return side_a, side_b
def cal(side_a, side_b):
side_c = side_a + side_b
return side_c
I have the following code:
#AON = Amount of Numbers to average
def general():
print "Enter how many numbers you will enter."
print "Maximum amount is 10: "
aon = raw_input()
try:
aon = int(aon)
if aon >= 10:
print "I cannot average more than 10 numbers."
general()
else:
start_average()
except ValueError:
print "You entered an invalid input, try again."
general()
def start_average():
if aon == 1:
print "You cannot average one number."
general()
elif aon == 2:
def first_number():
print "First number: "
first_ni = raw_input()
second_number()
first_number()
def second_number():
print "Second number: "
second_ni = raw_input()
ans_two = first_ni / second_ni
second_number()
final_two()
elif aon == 3:
def third_number():
first_number()
second_number()
print "Third number: "
third_ni = raw_input()
ans_three = ans_two / third_ni
third_number()
final_three()
elif aon == 4:
def fourth_number():
first_number()
second_number()
third_number()
print "Fourth number: "
fourth_ni = raw_input()
ans_four = ans_three / fourth_ni
fourth_number()
final_four()
elif aon == 5:
def fifth_number():
first_number()
second_number()
third_number()
fourth_number()
print "Fifth number: "
fifth_ni = raw_input()
ans_five = ans_four / fifth_ni
fifth_number()
final_five
def final_two():
final_input = ans_two
final_answer()
def final_three():
final_input = ans_three
final_answer()
def final_four():
final_input = ans_four
final_answer
def final_five():
final_input = ans_five
final_answer()
def final_six():
final_input = ans_six
final_answer()
def final_seven():
final_input = ans_seven
final_answer()
def final_eight():
final_input = ans_eight
final_answer()
def final_nine():
final_input = ans_nine
final_answer()
def final_answer():
listofnumbers = [first_ni, second_ni, third_ni, fourth_ni, fifth_ni, sixth_ni, seventh_ni, eight_ni, ninth_ni]
print "The average of your numbers:"
print listofnumbers
print "Is = %d." % final_input
general()
It's purpose is to find the average of a number, but when I run it through PowerShell, I get the following error:
Traceback (most recent call last):
File "average.py", line 97, in <module>
general()
File "average.py", line 10, in general
general()
File "average.py", line 10, in general
general()
File "average.py", line 12, in general
start_average()
UnboundLocalError: local variable 'start_average' referenced before assignment
I've probably done this more throughout my code, and I just made this, but I just don't know how to fix it or what is the error showing! I don't understand.
It's hard to tell from what you've pasted, because you've clearly broken the indentation.
But it looks like this code:
print "Enter how many numbers you will enter."
print "Maximum amount is 10: "
… is meant to be inside general, while this code:
aon = raw_input()
try:
aon = int(aon)
if aon >= 10:
print "I cannot average more than 10 numbers."
general()
else:
start_average()
except ValueError:
print "You entered an invalid input, try again."
general()
… is meant to be at module level.
Code is executed in the order it appears. Function definitions are just code, like anything else. So, you can't call a function before you define it, because the function doesn't exist yet.
You're probably about to object, with an example like this:
def foo():
bar()
def bar():
print('Hi!')
foo()
It looks like we're calling bar before it exists, and yet it works. How?
Well, the definition of foo is being executed before bar exists, but that's fine. That just defines a function that will, when run, call whatever bar means. As long as we've defined bar before we call it—and we have—everything is fine.
However, you have a number of similar problems in your code. For example, let's look at this part:
elif aon == 2:
def first_number():
print "First number: "
first_ni = raw_input()
second_number()
first_number()
def second_number():
print "Second number: "
second_ni = raw_input()
ans_two = first_ni / second_ni
second_number()
final_two()
That first_ni is a local variable within the first_number function. Every time you call first_number, a new first_ni gets defined, but only visible within that function. You can't use it in second_number, because second_number can only see its own local variables, and global variables, and first_ni is neither.
The concept you need to understand is called scope. Python has some nice tools to help you understand scope. You can print out locals() and globals() and dir() at any part of your program to see what's in scope there. But you'll need to read the tutorial first.
Indentation and a few other things are questionable. I'm not sure why you're defining all of these functions inside of other functions... I think this will do what you want. You're going to need a lot more error checking though (making sure the inputs are integers, divide by 0, etc.)
>>> def getMean(maxNumsToDivide):
... listNums = []
... for i in range(maxNumsToDivide):
... num = raw_input("Please enter a number: ")
... if not num:
... break
... listNums.append(int(num))
... return float(sum(listNums))/len(listNums)
...
>>> getMean(100)
Please enter a number: 2
Please enter a number: 3
Please enter a number: 4
Please enter a number: 5
Please enter a number: 3
Please enter a number:
3.4