Python main() not executing properly - python

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()

Related

call a 'def' with an 'input' in Python

I'm working on a project, and I got a bit stuck. I want the user the of the program to be able to call a function. But it must be easy for the user to call it. For example
def definition():
print("This is a function")
command = input("> ")
if command == definition:
definition()
else:
print("")
in this function I want the user not to write the () in the input. But I want the user just to be able to write 'definition' to call the function. Does anyone have any clue how to do this?
You are missing the quotes from around definition, therefore trying to compare an undeclared variable with an inputted string which will always equate to false.
Try:
def definition():
print("This is a function")
command = input("> ")
if command == 'definition':
definition()
else:
print("")
You are mixing up the function name (callable object in you code) and the name from your input.
For your problem I would use a dictionary of function names for the keys and function references for the value
def function1():
print ('calling function1')
def function2():
print ('calling function2')
def function3():
print ('calling function3')
functions = {}
functions['function1'] = function1
functions['function2'] = function2
functions['function3'] = function3
name = input('Enter the function name:\n')
if name in functions:
functions[name]()
else:
print ('Invalid function name. Use one of: ')
for key in functions.keys():
print (' - ' + key)
Just one command "definition"
def definition():
print("This is a function")
command = input("> ")
if command == "definition":
definition()
else:
print("Wrong command !")
More commands and functions
def definition():
print("This is definition function")
def modify():
print("This is modify function")
func = {"definition":definition, "modify":modify}
command = input("> ").strip().lower()
if command in func:
func[command]()
else:
print("Wrong command !")
You will have to implicitly define the conditions with if statement..
For ease of user you can do like this:
def definition():
#your function here
if __name__=='__main__':
print ("Choose your option:\n1. Definition")
choice = int(input("Enter choice: "))
if choice == 1:
definition ()
Try this
whitelist_funcs = ['definition', 'something else']
command = input("> ")
if command in whitelist_funcs:
exec(f"{command}()")
else:
print("")

How to get the main function to call the other program

I have this issue I did where the replace function calls the uppercase function, what I need to do is, I need the main function to call the other functions(SO first the uppercase and then the replace). I also need to change the interactive area. What I mean by this is right now the uppercase function is asking the user for a string, but I need the main function to ask the user for a string and then call the uppercase function and then call replace function.
def uppercase():
cap_letters = input("Please enter your string here: ")
new_uppercase=''
for letters in cap_letters:
if ord(letters) > 96:
new_uppercase += chr(ord(letters)-32)
else:
new_uppercase += letters
print(new_uppercase)
return new_uppercase
def replace():
old,new = [],[]
newString = ""
new_uppercase = uppercase()
string = new_uppercase
char = input("Change: ")
toThis = input("Change " + char + " to this: ")
for x in range(0,len(string)):
old.append(string[x])
for y in range(0,len(old)):
if old[y] != char:
new.append(old[y])
else:
new.append(toThis)
for z in range(0,len(new)):
newString+=new[z]
print(newString)
def main():
print("Hello, And Welcome to this Slang Program")
uppercase()
# write the part of the program that interacts with the user here
replace()
main()
You are trying to pass values between functions. You need to return the values from each function so that the parent function can use them. Passing values around works like this:
def function2(foo):
double_foo = foo * 2 # Do something to create whatever output you need
return double_foo
def function1(bar):
foobar = function2(bar) # Note that the foo and bar variables here are locally scoped
return foobar
def main():
user_input = input("Please enter your string here: ")
output = function1(user_input)
return output
main()
For more on scoping, check out https://matthew-brett.github.io/teaching/global_scope.html

Python and Variable Passing

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

Not sure why I can't indent this code in Python

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

Referenced before assignment Python

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

Categories

Resources