Python: 'other_activity' is not defined - python

I want to print the other_activity if its not empty after taking input from user but this error, I know its pretty basic but not able to find the solution
print("What kind of activity is this?")
print '\n'.join(acti)
userInput = raw_input("\n""Client->")
r = re.compile(userInput)
if not filter(r.match, acti):
print("not valid activity")
else:
if (userInput == "Other"):
event_activity = raw_input("-> Please specify your activity\n""Client->")
other_activity = ("Other:" + event_activity)
else:
event_activity = userInput
if not other_activity:
print("Activity type: ", other_activity)
else:
print("Activity type: ", event_activity)

Define other_activity = None at the top of your code (There are cases in your code when other_activity is never assigned, and thus, never created. By adding this default assignment, you are making sure the variable will exist when checking its value)
At the end, you can use a ternary condition to print one variable or the other:
print('Activity type:', other_activity if other_activity else event_activity)

Related

User input for gender not functioning

I am attempting to make a game that I made via Rpg Maker MV in python but I've hit a road block in the if statement or rather the gender input. The code is meant to have the user input either "Boy" or "Girl" and depending on that the variable "gender" will be set for pronouns. How ever the console is saying This
This is the code
import time
print ("Elvoria")
print ("Start")
input = input()
if input == ("Start"):
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if input == ("Boy"):
gender = 1
elif input == ("Girl"):
gender = 2
else:
print ("Error")
You need to check the input using the variable name genderin that you defined, instead of input == ("Boy").
EDIT: Also, you are mirroring the built-in method input() with the variable name input and you should not do that. Rename your variable to e.g. start_input.
import time
print ("Elvoria")
print ("Start")
start_input = input()
if start_input == "Start":
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if genderin == "Boy":
gender = 1
elif genderin == "Girl":
gender = 2
else:
print ("Error")
You're defining the variable "input" on line 4 to be a string, given from the "input" function. This overrides the keyword. Then, on line 9, you're calling "input" again. Since you've replaced the built-in function with a string, an error is thrown (the error "not callable" means that you're trying to treat a non-function like a function).
Here's your code sample, without overriding built-in methods:
import time
print ("Elvoria")
print ("Start")
user_input = input()
if user_input == ("Start"):
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if genderin == ("Boy"):
gender = 1
elif genderin == ("Girl"):
gender = 2
else:
print ("Error")
You should avoid using input as a varible name, since a built-in function with that name already exists, input(). So just change it's name to something else. Secondly, you're storing the gender input (boy/girl) in genderin, but then checking input, when you should be checking genderin. So the code after fixing these would look something like this:
import time
print ("Elvoria")
print ("Start")
choice = input()
if choice == "Start":
print("Always Great To See New People")
time.sleep(1)
print("Now Are You A Boy Or Girl?")
genderin = input()
if genderin == "Boy":
gender = 1
elif genderin == "Girl":
gender = 2
else:
print("Error")
I have used choice for demonstration purposes, you can use a different name if you want, just remember to make sure that a python built-in with that name doesn't exist. Also, no need to put ("Start") in the if statement, use "Start" instead (same goes for other if/elif statements)
You have also used print ("example") (space between print and brackets), i've rarely ever seen someone using this, most people use print("example") instead.
Finally a tip -> You can make the string lowercase, genderin = genderin.lower() to manage case sensitivity, i.e, both boy and Boy will be valid inputs, etc.

How can I call a function using an if statement and then print the value returned inside the if statement?

This part of my if statement calls the find_feed function and it it returns None, the if statement completes, however if it returns anything else, the else statement re-calls the function: news_feed = feedparser.parse(find_feed(user_input))
Instead of calling the function twice (because it takes a bit to complete), I'd like to call it once and if it doesn't return None, use the returned value in the else statement instead of calling the function again. Can I do that, and if so, how?
elif find_feed(user_input) is None:
print("No location found.")
else:
print("Pulling weather data from Environment Canada.")
news_feed = feedparser.parse(find_feed(user_input))
brief_current()
more_question = input("\n" + "Would you like more details? (y or n) ")
if more_question == "y":
detailed_current()
Since PEP 572 in Python 3.8 you can also combine if statement with assignment so you don't have to create the variable in advance:
elif (unparsed_news_feed := find_feed(user_input)) is None:
print("No location found.")
else:
print("Pulling weather data from Environment Canada.")
news_feed = feedparser.parse(unparsed_news_feed)
brief_current()
more_question = input("\n" + "Would you like more details? (y or n) ")
if more_question == "y":
detailed_current()
Although here I'd suggest swapping two branches and inverting is None to is not None so unparsed_news_feed is only used in its corresponding branch.
Store the return value in a variable, so you can reference it later. See here:
xy = find_feed(x)
# Assumes a pre existing if statement
elif xy is None:
print('no location')
else:
print("Pulling weather data from Environment Canada.")
news_feed = feedparser.parse(xy)
brief_current()
more_question = input("\n" + "Would you like more details? (y or n) ")
if more_question == "y":
detailed_current()
You need to save the result of the call to find_feed before you test its value:
else: # instead of the original elif find_feed(user_input) is None:
result = find_feed(user_input)
if result is None:
print("No location found.")
else:
print("Pulling weather data from Environment Canada.")
news_feed = feedparser.parse(result)
brief_current()
more_question = input("\n" + "Would you like more details? (y or n) ")
if more_question == "y":
detailed_current()

How to fix 'TypeError' that comes up for some inputs

I'm currently in year 10 and I'm creating a program which tells the user if their ransom note can be created from an article they have inputted. Some of the inputs I've been typing in come up with the error: TypeError: Can't convert 'NoneType' object to str implicitly
It seems to work at first but then I typed in "hello" as my ransom note and "hell" as my article and it came up with the error above. I thought it might've been because the article is shorter than the note but I tried it with other inputs and that doesn't seem to be the problem. I've included the function in case that might have something to do with it. Sorry if my code is a bit messy or inefficient.
elif choice == "2" :
user_note = input("\nPlease enter your ransom note: ")
user_article = input("Please enter your article: ")
print("\n" + can_I_ransom(user_article, user_note))
can_I_ransom function:
def can_I_ransom(newspaper_text, ransom_text):
article_list = list(newspaper_text)
article_copy = list(newspaper_text)
for i in range(len(ransom_text)):
for j in range(len(article_list)):
if ransom_text[i] == article_list[j]:
del article_list[j]
if len(article_copy)-len(ransom_text) == len(article_list):
return "Ransom can be made"
break
else:
if j == len(article_list)-1:
return "Ransom note cannot be made"
I'm expecting the output to be either "Ransom can be made" or "Ransom note cannot be made" and nothing else. Please help if you can :)
The problem is that when the ransom cannot be made, you aren't returning anything, and so it doesn't know what to do with a None which is what comes out when you just break without actually getting a "You can ransom" output. For example, what happens if the first if statement is true but the second isn't? Or if the first if statement is false and the second is false? This is why it only happens for some inputs - it only happens on the ones that slip through the cracks on the if statements. Also, I'm not quite sure your indentation is right for the outer else statement you have. Try running this:
def can_I_ransom(newspaper_text, ransom_text):
article_list = list(newspaper_text)
article_copy = list(newspaper_text)
for i in range(len(ransom_text)):
for j in range(len(article_list)):
if ransom_text[i] == article_list[j]:
del article_list[j]
if len(article_copy)-len(ransom_text) == len(article_list):
return "Ransom can be made"
else:
return "something"
else:
if j == len(article_list)-1:
return "Ransom note cannot be made"
else:
return "something"
choice = "2"
if choice == "2" :
user_note = input("\nPlease enter your ransom note: ")
user_article = input("Please enter your article: ")
print("\n" + can_I_ransom(user_article, user_note))
Just change the "something"s to the appropriate response.

Append Python returns instead of overwriting

I'm teaching myself Python and writing a simple GPA calculator. I have very little programming experience prior other than a college Java course, so bear with my code.
The premise is, the code will ask if you want to add a course to the list. If you do, it runs a function asking you the class name. Every time you add a class it'll ask if you want to add another. If you don't, it'll spit out a list of the classes you've added and then ask you to enter in the grades. I didn't get the grading part done yet. I don't think that will be too hard.
The problem is you can add a bunch of classes and it will only spit out the last one you entered. I'm assuming the issue is in askAgain(): classList = addClasses() because it keeps overwriting, but I'm not sure how to avoid a global variable (since they're bad?) and still keep this from overwriting itself. I seem to draw a blank when trying to figure out how to call something once to intialize it and not run it again. I've also read that conditional variables are bad, so I'm not sure what's best practice here. thanks
def main():
askAgain()
return 0
def askAgain():
while True:
addOrNot = raw_input("Add a class? [y/n]: ")
if addOrNot == "Y" or addOrNot == "y":
classList = addClasses() #This is probably where my issue is.
else:
try:
editClassGradeSelection = mainMenu(classList)
addGrades(editClassGradeSelection, classList)
except:
print("Hey you didn't add any classes yet.")
def addClasses():
try:
if classList in locals():
print("debug msg - classList exists")
except:
classList = []
classList.append(raw_input("Add class to the list: "))
return classList
def mainMenu(classList):
print("Here are the classes you've added: ")
counter = 0
for classes in classList:
print((str(counter+1)) + ". " + (str(classList[counter])) + "\n")
counter = counter + 1
while True:
editGrade = raw_input("Enter the number for the class grade to edit: ")
if int(editGrade) > len(classList) or int(editGrade) < 1:
print("Enter a proper number in the range listed.")
else:
break
return editGrade
def addGrades(editClassGradeSelection, classList):
print("debug stuff for now: ")
print((str(editClassGradeSelection)))
print((str(classList[:])))
if __name__ == '__main__':
main()
Although this snippet makes sure classlist is defined:
try:
if classList in locals():
print("debug msg - classList exists")
except:
classList = []
classlist is a local variable, hence everytime you run that function, classlist will be [], which probably explains why you can't ever display more than one. The classlist you assign it to gets reassigned to the one element of classlist (addClasses scope) every time this line is called:
classList = addClasses() #This is probably where my issue is.

Simple Phonebook

this is some simple code I wrote for a phonebook.
It does not seem to work though, and I do not know why.
I am very new to python, and I am sure there are many errors.
def startup(contactlist = {}):
print "Welcome to Contacts+\n"
print "Please enter your name"
name = raw_input()
print "Hi " + name + " would you like to check your existing contacts or make new ones?"
print "To make new contacts type in 'New'"
print "To check existing contacts type in 'Contacts'"
choose = ""
choose = raw_input()
if choose == "'New'" or choose == "'new'" or choose == "New" or choose == "new":
newcontact()
elif choose == "'Contacts'" or choose == "'contacts'" or choose == "Contacts" or choose == "contacts":
checkcontact()
def newcontact():
startup(contactlist = {})
print "To create a new contact please first input the name"
contactname = raw_input()
print "Next enter the phone number"
contactnumber = raw_input()
print "Contact created!"
contactlist[name] = number
def checkcontact():
startup(contactlist = {})
print contactlist
startup()
Have you tried to run this...?
This if/elif statement shouldn't be indented:
if choose == "'New'" or choose == "'new'" or choose == "New" or choose == "new":
newcontact()
elif choose == "'Contacts'" or choose == "'contacts'" or choose == "Contacts" or choose == "contacts":
checkcontact()
And why do you have:
startup(contactlist = {})
in the beginning of newcontact() and checkcontact() function?
Four things you can do right now to make your code better:
Go read about this gotcha in Python. We tricked you. (We're sorry! We had good reasons.) You can't really do that with lists and dicts, and you have to use a Python idiom involving None to do it right.
Use raw_input's first argument. Instead of print('Hey user!'); raw_input(), just write raw_input('Hey user!').
Learn the in keyword. Whenever you find yourself saying if x == 'x' or x == 'y' or x == 'z', it's probably easier to write if x in 'xyz' (strings are iterable, remember?). You can also get rid of two of those cases by stripping off quotes the user might enter if you don't want them -- choose.strip("'").
Fix your function calls. Functions in Python can be called in two ways, using positional arguments f(a, b, c) or keyword arguments f(a, b=0, c=2). Calls like startup(contactlist={}) are just explicitly setting that argument to the empty dict, its default value, so this is always equivalent to startup() the way you have it defined.

Categories

Resources