I have this exercise and the first part of the program was running fine but I must've done something because now when I try to run it will just show None and and nothing seems to be 'wrong'. I don't know enough to even figure out what's wrong.
def main():
"""Gets the job done"""
#this program returns the value according to the colour
def re_start():
#do the work
return read_colour
def read_names():
"""prompt user for their name and returns in a space-separaded line"""
PROMPT_NAMES = input("Enter names: ")
users_names = '{}'.format(PROMPT_NAMES)
print (users_names)
return users_names
def read_colour():
"""prompt user for a colour letter if invalid colour enter retry"""
ALLOWED_COLOURS = ["whero",
"kowhai",
"kikorangi",
"parauri",
"kiwikiwi",
"karaka",
"waiporoporo",
"pango"]
PROMPT_COLOUR = input("Enter letter colour: ").casefold()
if PROMPT_COLOUR in ALLOWED_COLOURS:
return read_names()
else:
print("Invalid colour...")
print(*ALLOWED_COLOURS,sep='\n')
re_start()
main()
The only function you call is main(), but that has no statements in it, so your code will do nothing. To fix this, put some statements in your main() and rerun your code.
Related
No matter how many times I google variations of my question, I cannot seem to find a solution. I am a beginner programmer, trying to build a game that randomly generates events as you progress through the stages. The problem I am running into are return statements, and passing the values between different modules. Each method for each file are inside of classes. They are all static methods, and calling these methods is not my problem. It is transferring the value of the variables. I'm not sure where I am going wrong, whether it is how I am structuring it, or if I just don't understand how these return statements work.
This is the first File I am starting from. Print statements will be filled out after everything functions properly.
def story():
print("---Intro Story Text here--- ... we will need your name, Traveler. What might it be?")
user_prompt = Introduction.PlayerIntroduction
name = user_prompt.player_info(1)
print(f"Welcome {name}!")
print(f"----After name is received, more story... how old might you be, {name}?")
age = user_prompt.player_info(2)
This is the file I am trying to get the values from. File: Introduction, Class: PlayerIntroduction
#staticmethod
def player_info(funct_select):
if funct_select == 1:
name = PlayerIntroduction.get_player_name()
player_name = name
elif funct_select == 2:
age = PlayerIntroduction.get_player_age()
player_age = age
return player_name, player_age
#staticmethod
def get_player_name():
print("\n\n\nWhat is your name?")
players_name = input("Name: ")
while True:
print(f"Your name is {players_name}?")
name_response = input("Yes/No: ")
if name_response == "Yes" or name_response == "yes":
name = "Traveler " + players_name
break
elif name_response == "No" or name_response == "no":
print("Let's fix that.")
PlayerIntroduction.get_player_name()
else:
print("Please respond with 'Yes' or 'No'.")
return name
#staticmethod
def get_player_age():
print("\n\n\nHow old are you?")
age = input("Age: ")
while True:
print(f"Your age is {age}?")
age_response = input("Yes/No: ")
if age_response == "Yes" or age_response == "yes":
break
elif age_response == "No" or age_response == "no":
print("Let's fix that.")
PlayerIntroduction.get_player_age()
else:
print("Please respond with 'Yes' or 'No'.")
return age
I would like to use the values for "name" and "age" throughout multiple modules/multiple methods within my program. But in order to get those values, I need to assign a variable to the function call.. Resulting in prompting the user to re-enter their name/age at later stages in the game. My idea to combat this was in the first method of this module, creating a conditional statement "if 'example' == 1: 'run the name prompt' and elif == 2: run age prompt, thinking the initial run with the arguments defined would run these prompts, store the values into the variables (name, age), and finally pass the values to the new variables that are NOT assigned to the function call (p_name, p_age), avoiding triggering the user prompt over and over. Ultimately, this failed, and as the code sits now I am getting:
UnboundLocalError: local variable 'player_age' referenced before assignment
Why is this? The only instance 'player_age' is called that is reachable at this point is in the return statement, indented in-line with the conditional statement. The code should read (If I understand incorrectly, please explain) from top to bottom, executing in that order. The 'if' condition is met, so it should run that. If I were to define 'player_name' and 'player_age' as null at the top of this method to avoid this error, then every time I would need to reference these values initially entered by the user, they would be re-assigned to 'null', negating everything I am trying to do.
Thank you all for your patience, I tried to explain what I was doing and my thought process the best I could. Any feedback, criticism, and flaws within my code or this post are GREATLY appreciated. Everything helps me become a better programmer!! (:
So I have this while loop which asks user if he/she wants to repeat the program. All works good but I was trying it out and found out that after user repeats the program and when asked second time if he/she wants to repeat, I choose no. But the program still repeats although it prints that program is closing, how can I fix this?
edit: I've fixed it with changing break with return and adding return after main()
def main():
endFlag = False
while endFlag == False:
# your code here
print_intro()
mode, message=get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
while True:
if ui == "Y":
print(" ")
main()
elif ui == 'N':
endFlag = True
print("Program is closing...")
break
else:
print("wrong input, try again")
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
This is because main() function is being called recursively & endFlag is a local variable.
So when you first put 'y' , then another main() is recursively called from the first main() function.
After you put 'n' which ends this second main() and return to the first main which still in a loop with endFlag (local variable) with value as false.
So, need to change,
Either
endFlag variable as global ( i.e. defined outside main function )
Or,
some program exit function in place of break
The thing is that you're doing recursion over here, i.e. you're calling method main() inside main() and trying to break out of it the way you've done is not gonna work (well, you're know it :) )
Second - you don't need a forever loop inside a first loop, you can do it with one simple loop and break.
Here it is:
def print_intro():
intro = "Welcome to Wolmorse\nThis program encodes and decodes Morse code."
print(intro)
def get_input():
return 'bla', 'bla-bla-bla'
def main():
while True:
# your code here
print_intro()
mode, message = get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
if ui == "Y":
print(" ")
elif ui == 'N':
print("Program is closing...")
break
else:
print("wrong input, try again\n")
main()
this is what you should do:
(BTW this is a piece of example code)
while True
name = input('Enter name:')
print ('Hi '+ name)
exit = input('Do you want to exit?(Y/N)')
if exit == 'N' or 'n':
break
(Im not sure if i put the indents correctly )
You can apply this concept into your code.
This question already has answers here:
Using global variables in a function
(25 answers)
Closed 2 years ago.
I am trying make a script that will accept 3 inputs first is username as input second and third are bar codes i need to compare, but after the first input of the user I want it to stop asking me for the user and just save and use it and cant seem to do it. I am assigning the user_global to be None at start so can I use an if to run the get_user function but when the script runs it second loop time it gives None as value to the user again and i cant seem to remember how to remove the user from the loop and save it after the first iteration because i am real dumb, as I stated before. Here is the code:
while True:
def get_user():
user=input("Enter User :")
user_global = user
print(user)
print(user_global)
user_global = None
if user_global == None:
get_user()
a = datetime.datetime.now()
print(a)
def gun_read():
barcode1=input("Please the first barcode the barcode!?")
print(barcode1)
barcode2=input("Plese read the secdon barcode?!")
print(barcode2)
if barcode1 == barcode2:
print("GREEN LIGHT!!")
else:
print("you fcked up broooo!!")
# if os.cwd() ima csv file add to csv else create csv
gun_read()
Help, please ? Also ignore prints and datetime.
By default, Python doesn't allow you to assign global variables. In get_user() what it's doing is making a new variable called global_user. To change this behaviour, have global user_global on a line before you assign the variable.
Unless I'm missing something,
user = None
def get_user():
return input("Enter User :")
def gun_read():
barcode1 = input("Please the first barcode the barcode!?")
print(barcode1)
barcode2 = input("Plese read the secdon barcode?!")
print(barcode2)
if barcode1 == barcode2:
print("GREEN LIGHT!!")
return True
else:
print("you fcked up broooo!!")
return False
def main():
global user # so we can write to the global user variable
user = get_user() # grab the username and write it
while True: # repeat gun reads until the end of time
gun_read()
if __name__ == "__main__":
main()
first of all, keep your def functions always on top for readability, second of all why is the whole thing in while True:? And lastly in get_user() you can call gun_read()
def get_user():
user=input("Enter User :")
user_global = user
print(user)
print(user_global)
gun_read()
def gun_read():
barcode1=input("Please the first barcode the barcode!?")
print(barcode1)
barcode2=input("Plese read the secdon barcode?!")
print(barcode2)
if barcode1 == barcode2:
print("GREEN LIGHT!!")
else:
print("you fcked up broooo!!")
user_global = None
while True:
if user_global == None:
get_user()
else:
gun_read()
I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...
I have been trying to figure this out for way too long! What to do?
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return(submission)
name = input("What is your name?")
(fallBack(name))
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
I keep having the last input just print out nothing...
You need to store the result of fallBack().
Also, change fallBack() to return the original value if it is non-null:
def fallBack(submission):
if not submission:
return "fixed!"
else:
return submission
Then, use it like this:
name = fallBack(input("What is your name?"))
Just remove the brackets around fallBack(name)
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return submission
name = input("What is your name?")
name = fallBack(name)
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
Also remember that if using python 2.7 you should use raw_input instead of input
I'm not sure what you want to do, but I think this would do it:
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return (submission)
name = input("What is your name?")
name = fallBack(name)
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
Your two mistakes were not to return anything in case there is nothing to fix, and not to assin the value returned by the function.
By the way, there is a much more idiomatic way of doing this in Python:
name = input("What is your name?")
name = name or 'fixed!'
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
The second line tests if converting name to a boolean, and, if it returns False (for a string, it is equivalent to testing if it is not empty), replace it with 'fixed!'
The return is not well aligned! You are not returning anything unless submission is empty! :-)
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return(submission)