Having trouble in python 3.0 with this code - python

I've been having trouble with this little program, it skips over the if == "otc": part completely, I've tried stuff to fix it but I just can't get it to work.
print("Hello, what is your name?")
name = input()
if name == "OTC":
print("get out otc!")
elif():
print("Hello! " + name

If you want to check if input has otc you can convert it into uppercase and check but if you want case sensitivity don't use upper()
Modification:
name = input("Hello, what is your name?")
if name.upper() == "OTC":
print("get out otc!")
else:
print("Hello! " + name)
output:
Hello, what is your name?"otc"
get out otc!
Hello, what is your name?"barny"
Hello! barny
Changes in your code:
There is no need for print since the same thing can be done using input function
There is no need for elif since there is only one condition check so use else
elif is a statement and not a function so remove the ()

Related

pytest brings up assertion error when using a string in the given function

here is my code (that is relevant to this problem)
# main.py
def main():
fruit = input("What is the name of your fruit?: ")
name = input("What is the persons name?: ")
fruit_and_name(fruit,name)
def fruit_and_name(fruit,name):
"""
A function that takes the name of a fruit and the user
"""
return (f"Your name is {name} and you chose {fruit}.")
# test_main.py
from main import fruit_and_name
def test_fruit_and_name():
assert fruit_and_name(josh, apple) == "Your name is josh and you chose apple."
assert fruit_and_name(asd, asd) == "Your name is asd and you chose asd."
the error given:
____________________________________ test_fruit_and_name ____________________________________
def test_fruit_and_name():
> assert fruit_and_name(josh, apple) == "Your name is josh and you chose apple."
E NameError: name 'josh' is not defined
test_main.py:8: NameError
Not sure what I'm supposed to do about this error because I can't define josh since its going into the function and its not actually a variable its just a string.
Attempted
I've tried using "" around josh
I've also tried importing main to the test file (not sure why I thought it might work)
Anyways I'm quite lost if anyone could help thanks.
Put quotes around the arguments.
def test_fruit_and_name():
assert fruit_and_name("josh", "apple") == "Your name is josh and you chose apple."
assert fruit_and_name("asd", "asd") == "Your name is asd and you chose asd."

Break outside the loop

I am new to Python. I am trying to run the following code. But every time I try to run it, the IDE says that the break is outside the loop
catname = []
print("Enter the name of the cats")
name = input()
if name == '':
break
catname = catname+[name]
print("The cat Names are :")
for catname in name:
print(name)
Can you please help me?
Thanks
You use break when you want to break free from a loop, to exit the loop, to jump to the nearest code after the loop.
Your code doesn't contain a loop, so nothing to break free from, hence the error.
I think you meant exit() instead of break
You use "break" just inside the loop ("for" or "while"), you are trying use brake inside the "if"
How about this:
if name != '':
catname = catname+[name]
print("The cat Names are :")
for catname in name:
print(name)
Your break statement is not in a loop, it's just inside an if statement.
But maybe you want to do something like the following.
If you want to let the user enter an random number of names and print the names out, when the user entered nothing, you can do the following:
# Here we declare the list in which we want to save the names
catnames = []
# start endless loop
while True:
# get the input (choose the line which fits your Python version)
# comment out the other or delete it
name = input("Enter the name of a cat\n") # input is for Python 3
# name = raw_input("Enter the name of a cat\n") # raw_input is for Python 2
# break loop if name is a empty string
if name == '':
break
# append name to the list catnames
catnames.append(name)
print("The cat names are :")
# print the names
for name in catnames:
print(name)
What you are looking for is exit().
However, your code has also other problems, here is a piece of code that does what you probably want (when prompted, enter the names separated by spaces, like: Cat1 Cat2):
name = raw_input("Enter the name of the cats: ")
if len(name) == 0:
exit()
print("\nThe cat Names are:")
for c_name in name.split():
print(c_name)
If this is the entirety of your code, then it's telling you exactly what the problem is:
catname = []
print("Enter the name of the cats")
name = input()
if name == '':
break
You have a break statement in the code that's not contained inside a loop. What do you expect the code above to do?

How to use a function's if statement to use info from another function?

So I'm designing a sign-in AI, and I want it to work so that the admin name is Shawn. Here is my issue:
The program starts with the interface -
def interface():
username = input('Hello traveler, what is your name? ')
lowerUsername = username.lower()
print()
print()
if lowerUsername == 'megan':
print()
print('So you are the one Shawn has told me so much about? You are looking beautiful today my dear ☺️🌷')
elif lowerUsername == 'shawn':
OfficialSignInEdit()
So you can see at the end that if the user inputs that their name is 'shawn' at sign-in, it calls on the OfficialSignInEdit function, which is the admin sign in. It looks like this:
def OfficialSignInEdit():
print()
if PossInputs('perio', 'What street did you grow up on?: ') == correct:
print()
print('Greetings Master Shawn, it is a pleasure to see you again 🙂')
else:
print()
res1 = input('Incorrect password, try again? (Yes/No)')
lowres1 = res1.lower()
if lowres1 == 'yes':
print()
print()
OfficialSignIn()
elif lowres1 == 'no':
print()
print()
interface()
So I have pinpointed the source of my issue to be right here in this particular line:
if PossInputs('perio', 'What street did you grow up on?: ') == correct:
print()
print('Greetings Master Shawn, it is a pleasure to see you again 🙂')
this (just for your reference) is the PossInputs function:
def PossInputs(x, y):
term = x
question = input(y)
lowQuestion = question.lower()
words = lowQuestion.split()
if term in words:
print()
print (correct)
else:
print()
print (incorrect)
So what I want to happen is, when 'shawn' is entered as a name, the program will jump to the OfficialSignInEdit Function, and ask the question 'What street did you grow up on?'. Then IF the user enters the answer 'perio', the program will print 'correct', and then print the message 'Greetings Master Shawn, it is a pleasure to see you again'. I tried to say that IF PossInputs == correct (and I did define correct = 'correct', and incorrect = 'incorrect' outside all functions) then this would happen, but instead it prints 'correct', and then 'Incorrect password, try again? (Yes/No)', so how can I make a conditional statement that says that if the user answers 'perio', then it will print the welcome message?
Just for thoroughness sake, I also tried
if PossInputs('perio', 'What street did you grow up on?: ') == True
also without success...
anyways anything you can give me is extremely appreciated, if you have any questions or you would like to to clarify something about the written code, I would be more than happy to get back with you as soon as I can.
Thanks!

Using Python Class to make game- how to update self init?

I am making a text-based game on python using the class system to keep track of main character changes (like its name). I am writing the main code for the game outside of the Main Character Class- inside of the main function.
I am struggling because I need to update self.character_name inside the Main Character class to an input from the user inside the main function. I am unsure how to do this, I have the code written below- however it is not updating the name inside Main Character class. How can I rewrite this?
I'm also worried that I will have this problem when trying to update pets, characters_known. However, I do not seem to have this problem with updating Health or XP....
class Main_Character():
def __init__(self):
self.health=100
self.exp=0
self.level=0
self.character_name=""
self.characters_known={None}
self.pets={None}
self.progression_tracker=0
def __str__(self):
return "Name: "+ str(self.character_name)+" | "+ "Health:"+ str(self.health) + " | " +"XP:"+ str(self.exp) + " | "+ "Level:"+ str(self.level)+" | "+"Pets:"+str(self.pets)
def Char_Name(self,name):
if name.isalpha()==False:
print("You entered a name containing non-alphabetic characters, pease reenter a new name:")
main()
elif len(name)>=10:
print("You entered a name containing 10 or more characters, pease reenter a new name:")
main()
else:
self.character_name=name
def Char_Level_Experience(self,exp,b):
self.exp+=exp
b=2
if exp<=0:
exp=1
ans = 1
level=0
while ans<exp:
ans *= b
level += 1
if ans == exp:
self.level=level
print("You have reached level", self.level)
else:
level = int(log(exp, 2))
level = min(level, exp)
if level>=0:
self.level=level
else:
level=0
def healing(self,heal):
if self.health+heal>=100:
self.health=100
else:
self.health+=heal
def other_answers(answer):
if answer=='quit':
raise SystemExit
if answer=='pets':
print("Pets owned:", Main_Character().pets)
user_decision=input("Would you like to continue where you left off? Type 'yes' to continue, or 'no' to go back to main menu")
if user_decision=='yes':
if Main_Character().progression_tracker==0:
main()
elif Main_Character().progression_tracker==1:
choice1()
if user_decision=='no':
main()
else:
other_answers(user_decision)
if answer=='characters':
print("Characters met:", Main_Character().characters_known)
user_decision=input("Would you like to continue where you left off? Type 'yes' to continue, or 'no' to go back to main menu:")
if user_decision=='yes':
if Main_Character().progression_tracker==0:
main()
if Main_Character().progression_tracker==1:
choice1()
if user_decision=='no':
main()
else:
other_answers(user_decision)
def start_check():
print("If you understand the game, type 'go' to continue- if not, type 'more information' to receive more information about how to play the game")
begin_game=input("")
if begin_game=="go":
choice1()
if begin_game=='more information':
print("\n","The object of the game is to gain XP [experience points] without dying")
start_check()
else:
other_answers(begin_game)
def choice1():
Main_Character().progression_tracker=1
print("You are a knight in the Kings Guard- the King has asked to meet with you about a very special mission")
print("What would you like to do?")
print(" 1.Go Directly to King","\n", "2. Finish your dinner")
choice=input("1 or 2?")
if choice=="1":
Main_Character().Char_Level_Experience(1,2)
elif choice=="2":
Main_Character().Char_Level_Experience(.5,2)
else:
other_answers(choice)
print(Main_Character())
def main():
print("Welcome!")
unfiltered_name=input("Please enter the name of your character:")
Main_Character().Char_Name(unfiltered_name)
print("Welcome,", Main_Character().character_name,"!", "Here are your current stats!")
print(Main_Character())
start_check()
You haven't quite understood how classes and instances work.
Calling the class is what you do when you need a new character. Every time you call Main_Character(), you get a whole new instance - with the default values as set in __init__. If you had characters for each of your friends, you would call it one time for each one. You then would need to keep each of those instances in a variable, so you can reference them again each time.
So, for instance:
my_character = Main_Character()
unfiltered_name=input("Please enter the name of your character:")
my_character.Char_Name(unfiltered_name)
print("Welcome,", my_character.character_name,"!", "Here are your current stats!")
print(my_character)
You create a new character each time you call Main_Character. Instead, you should call it once:
the_character = Main_Character()
...
the_character.name = "..."

Python Amateur - 'Greeting program' - 'Referenced before assignment error'

Like I said in my previous question, I'm a python amateur. I've made a couple silly mistakes. I'm attempting to make a highly simple greeting program using Python 3.4 however I have encountered an error. The error I have is:
UnboundLocalError: local variable 'lastNameFunction' referenced before assignment
Here's my code (I know I probably don't need to post it all, but there isn't much of it):
def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?"%firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
if __name__ == '__main__':
main()
I'd appreciate any help and advice! Please take into consideration I am really new to this stuff. I'm also not quite sure on having a function inside of a function, but I thought it would be a fix so that the 'firstName' was available when entering the 'lastName'.
Thanks in advance! :)
You need to move the lastNameFunction declaration somewhere before you call it using lastNameFunction(), e.g.:
def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?" % firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()
if __name__ == '__main__':
main()
You can also move it outside the main function, but you will then need to pass the firstName in using the function arguments:
def lastNameFunction(firstName):
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()
def main():
...
lastNameFunction(firstName)
...
Move your lastNameFunction to somewhere before the call. Ideally, you would place this above the main function.
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
def main():
...
The problem is you called lastNameFunction() before you defined it in the while loop. Try defining the function outside the while loop.
The organisation of the whole program seems a little bit off.
Imports usually go at the top of the module.
Functions defined in functions are usually just for closures, which you a) don't need here and b) might be a bit advanced for your current experience level.
Recursive calls like your calling main() from within main() are wrong. When you adopt that style of control flow instead of a loop, you will eventually run into limitations of recursive calls (→ RuntimeError). You already have the necessary loop, so simply leaving out the elif branch already asks the user again for the first name.
running isn't used anywhere, so you can remove it and just use while True:.
I would move asking the user for ”anything” + the question if the input was correct into its own function:
def ask_string(prompt):
while True:
result = input(prompt).title()
print("You have entered '{0}'. Is this correct?".format(result))
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if choice.upper() == 'Y':
return result
def main():
first_name = ask_string('What is your first name?\n')
last_name = ask_string(
'Hi {0}. Please enter your last name.\n'.format(first_name)
)
print(first_name, last_name)
if __name__ == '__main__':
main()

Categories