I am new and trying to create a simple "guess the number game":
import random
class Randgame :
def __init__(self):
pass
def restart(self):
response = input("Type Yes To Play Again!").lower()
if response == "yes":
self.play()
else:
print("Thanks for playing!")
pass
def play(self):
guess = int(input("What's your guess?"))
num = random.randint(0, 10)
if guess == num:
print("Correct!")
else:
print("Nope!")
self.restart()
fun = Randgame()
fun.play()
All is well until I get to the restart() method. If I type "yes" into the console I get this response:
NameError: name 'yes' is not defined
I cannot figure this out to save my life and I don't know what to look up. Please help!
In Python 2, getting input as plain text is done via raw_input instead of input. Python 3 changed the name of the function to input. The Python 2 version of input does eval(raw_input(prompt)), so it is trying to actually access a variable called yes, when you just want to get the string "yes".
Python 2 Docs
Related
I created this function and want to call the returned result but, I'm not sure how to get the variable back. If possible I'd also like a different message to pop up if the user types n. Could anyone help?
def give_entertainment():
random_form_of_entertainment = random.choice(form_of_entertainment)
good_user_input = "y"
while good_user_input == "y":
user_input = input(f"We have chosen {random_form_of_entertainment} for your entertainment! Sound good? y/n: ")
if good_user_input != user_input:
random_form_of_entertainment = random.choice(form_of_entertainment)
continue
else:
print("Awesome! Glad we got that figured out. Your trip is all planned! ")
return random_form_of_entertainment
x = give_entertainment()
Should store the return of your function into x.
With:
print(x)
you should see what's stored in your x variable.
Call the method while assigning it to a variable.
some_var = your_method()
Now this some_var variable have the returning value.
I'd personally use a recursive function for this, I made it work with y/n/invalid_input cases. Also with this an invalid input won't update random_form_of_entertainment so the user has to say y or n for it to change. I hope this is what you're looking for!
def give_entertainment():
random_form_of_entertainment = random.choice(forms_of_entertainment)
good_user_input = "y"
bad_user_input = "n"
invalid_input = True
while invalid_input:
user_input = input(f'We have chosen {random_form_of_entertainment} for your entertainment! Sound good? y/n: ')
if user_input == good_user_input:
print("Awesome! Glad we got that figured out. Your trip is all planned for!")
return random_form_of_entertainment
elif user_input == bad_user_input:
print("Sorry to hear that, let me try again...")
return give_entertainment()
else:
print("I don't recognize that input, please try again.")
continue
chosen_result = give_entertainment()
print(f'You chose {chosen_result}!')
I am very new to using classes and creating functions within it. I have been trying to write a bit more elegant code to the point where the only line to be 'executed' is 1 line, 'o.pag' in this case.
However, my pag function is just not working out. To my eyes, though I've made several variations of the same and even tried to turn it into an series of 'if' statements, gets stuck on "Would you like to play again'?.
Here the problematic but:
def pag(self):
o.game()
o.q()
while p_again == 'yes':
o.game()
o.q(). <<<<<<THIS IS WANT WONT EXECUTE AFTER TYPING 'YES'
if p_again != 'yes':
break
Here is the complete code sample. I am wondering if I caused the problem myself by trying to put everything into functions. Any help would be greatly appreciated.
import random
a = random.randint(1, 9)
#a = 4
again = ''
y = 'yes'
n = 'no'
g= 0
p_again = ''
class olv(object):
def glogic(self):
if g > a:
print('You guessed too HIGH.')
elif g < a:
print('You guessed too LOW.')
else:
print(g)
def game(self):
global g
while g != a:
g = int(input('Guess a number between 1 and 9! '))
o.glogic()
if g == a:
print('Wow, you guessed it.')
def q(self):
global p_again
p_again = str(input('Would you like to play again? '))
def pag(self):
o.game()
o.q()
while p_again == 'yes':
o.game()
o.q()
if p_again != 'yes':
break
o = olv()
o.pag()
you need to put in inside function not out side the function.
code should look like this.
def pag(self):
o.game()
o.q()
while p_again == 'yes':
o.game()
o.q(). <<<<<<THIS IS WANT WONT EXECUTE AFTER TYPING 'YES'
if p_again != 'yes':
break
I believed that this guessing game can run without using classes. From your code, it shows that your basics towards classes is not familiar enough.
You can try to make this guessing game without using classes first. Then you can try to implement the game using classes.
Here is an example of using classes for this game:
import random
p_again = ""
class olv:
def __init__(self):
self.answer = random.randint(1, 9)
self.guess = 0
def game(self):
while self.guess != self.answer:
self.guess = int(input('Guess a number between 1 and 9: '))
if self.guess > self.answer:
print('You guessed too HIGH.')
elif self.guess < self.answer:
print('You guessed too LOW.')
elif self.guess == self.answer:
print("Wow, you guessed it")
else:
print("You should guess between 1 and 9")
while True:
o = olv()
o.game()
p_again = str(input('Would you like to play again? ')).lower()
if p_again != "yes":
break
As pointed out in the comments, you have most of the code logic in there; however there is some confusion about OOP. One great thing to learn is to abandon (at least mostly) global variables, and use classes so that they can keep state of things. Another great suggestion I have is to use meaningful names, for variables and methods.
Now, it is a bit difficult to comment on each line of your code, so I took the liberty to rewrite it a bit. Keep in mind, there are dozen ways to do the same thing, so mine is not the best, nor (hopefully) the worse. I'll add comments to the code:
import random
class Game(object):
# First, let's use meaningful names
def __init__(self):
# Being a class, we can have an init method, and we can use it to initialize
# some variables that we will use to maintain "state". This means, we will give
# the class the job to remember what these values are during the course of the
# program, instead of storing them as global variables
#
# These variables are accessible by ALL methods in the class, using `self.`
self.value_to_guess = -1 # Note: we make value_to_guess and user_input different on purpose
self.user_input = 0 # so that play_game can loop without too much extra code
self.continue_play = True
def game_logic(self):
# This method is in charge of the game logic, which is "compare the values and print something"
# In your original code you did it for only two cases (>, <); it would be a good idea to also
# consolidate the case of equality
if self.user_input > self.value_to_guess:
print('You guessed too HIGH.')
elif self.user_input < self.value_to_guess:
print('You guessed too LOW.')
else:
print('Wow, you guessed it.')
def game_play(self):
# This method is in charge of the game play, making sure that a new random value is
# set at the beginning of a cycle, and that the user is asked every time for a value,
# until the user guesses. Every time, `game_logic` is called so that it will print the
# appropriate message on screen
#
self.value_to_guess = random.randint(1, 9)
while self.value_to_guess != self.user_input:
self.user_input = int(input('Guess a number between 1 and 9! '))
self.game_logic()
def question(self):
# This method will ask the user the question, and return the answered string straight out
return str(input('Would you like to play again? '))
def play(self):
# This method in charge of running games+questions, until the user stops answering 'yes'
self.game_play()
while self.question() == 'yes':
self.game_play()
if __name__ == '__main__':
my_game = Game() # Create a new Game object
my_game.play() # Ask the game object `my_game` to start playing
It's a lot of code, but I hope all the comments will help.
Just what you asked for
The problem manifests like this:
You play the game until you guessed the right number. Note that g == a now.
The asks "Do you want to play again?"
game() is called
But since g == a, game() will immediately quit
So, what's the problem? Well, for a new game, a needs to get a new random value.
Other stuff to make you a better programmer
To me it looks like you're typing in a poor text editor. You use short variable names. If you use an IDE which is made for Python, you'll get code completion and you can have better names that actually express what things are. a could be answer, g could be guess etc. Try JetBrains PyCharm. They have a community edition which is already great.
To me, glogic() is incomplete. The "Wow you guessed it" part is in game(). How about
def glogic(self):
if g > a:
print('You guessed too HIGH.')
elif g < a:
print('You guessed too LOW.')
else:
print('Wow, you guessed it.')
The code depends on global variables. Since you already have a class, all the variables could be included there. Please read about def __init__(self) and member variables like self.answer etc.
In q(), you convert the user input into a string. That's unnecessary, because it is already a string.
In pag(), code is duplicate. The logic to execute o.game() and then o.q() is coded twice. If you set p_again = "yes" initially, you can get rid of that duplication.
It seems n, y and again are unused.
To make user input a bit more robust, you could .lower() the input just in case the user enters some captital letters.
Same for numbers: if the user enters a letter, the code will fail with a ValueError. Use try: ... except ValueError: ... to make the game more robust.
I could rewrite the whole code for you, but I think it's worth doing that yourself.
I'm practice classes and inheritance in a program idea that I came up with myself. Basically Im making an arcade game menu simulator that can play two modes, single player and multiplayer. Every time I enter a choice, either 1 or 2, the menu displays a couple times and then it proceeds to accept the input, I only want the menu to be displayed once. Heres my code:
# Suppose you are at an arcade and you and your friend want to play a multiplayer game that requires UI.
# Make the game ask for the users name and age to see if they can play, make the program so that it can add a friend.
# If any of the players are under the age of 18, they are not allowed to play, otherwise proceed.
# **EXTRA CREDIT** --> Add a functionality which adds the players to a list until the list reaches 4 players, then stop adding to the list.
# arcade_game.py
import sys
# give the user a greeting
import self as self
lst = []
class menu:
def __init__(self, ready):
self.ready = ready
#display menu
#classmethod
def display_menu(self):
print("Pick from one of the choices below, type in the corressponding number")
print("1. single player \n"
"2. Multiplayer")
choice = int(input("Enter your choice here: "))
return choice
# ready or not function to see if the user is ready to play
def ready_or_not(self):
# see if user types 1 or 2 with try & except
try:
# ask user if they are ready
self.ready = int(input("Are you ready to play? Type 1 for yes, 2 for no"))
self.display_menu()
except ValueError:
print("You did not type 1 or 2, please try again!")
# add players class
class player(menu):
# add a default player to __init__(), **(since there has to be at least one player)**
def __init__(self, ready, player1):
super().__init__(ready)
self.player1 = player1
# single player method
def set_name(self):
self.player1 = input("Enter your name for single player mode")
print("Lets play! ", self.player1)
# multiplayer method
def set_names(self):
try:
self.player1 = input("Enter your name to begin")
lst.append(self.player1)
# add another player to continue
while len(lst) <= 4:
add = input("Add player here: ")
lst.append(add)
if len(lst) == 4:
print("Player limit reached!")
break;
except ValueError:
print("You didnt enter valid input, please try again")
# get the names of the players only if 1 is picked from display_menu() above, including player1
def check_choice(self):
if self.display_menu() == 1:
self.set_name()
elif self.display_menu() == 2:
self.set_names()
else:
print("Exiting....")
print("Goodbye!")
sys.exit(0)
m = menu("yes")
m.ready_or_not()
p = player("yes", "test")
p.check_choice()
ready_or_not calls self.display_menu():
def ready_or_not(self):
# see if user types 1 or 2 with try & except
try:
# ask user if they are ready
self.ready = int(input("Are you ready to play? Type 1 for yes, 2 for no"))
self.display_menu()
except ValueError:
print("You did not type 1 or 2, please try again!")
check_choice also calls self.display_menu() at least once, and twice if you type anything other than 1 the first time:
def check_choice(self):
if self.display_menu() == 1:
self.set_name()
elif self.display_menu() == 2:
self.set_names()
else:
print("Exiting....")
print("Goodbye!")
sys.exit(0)
Your top-level code calls ready_or_not() on one menu instance:
m = menu("yes")
m.ready_or_not()
… and check_choice() on another:
p = player("yes", "test")
p.check_choice()
So, your program displays the menu twice, and then a third time if you type anything but 1.
If you don't want the menu displayed two or three times, don't call the method two or three times.
If you want to display the menu only once and remember the choice, instead of displaying it two or three times, you need to use that self.ready attribute that you create in ready_or_not, instead of calling the method again.
However, that still isn't going to work as-is, because your class design is weird. You've made two separate instances, m and p, each of which has its own independent attributes. I'm not sure why player inherits from menu in the first place (or why display_menu is a #classmethod, or why it calls its parameter self rather than cls if it is one, and various other things), but, given that a player is a menu in your design, you probably just want a single player instance, like this:
p = player("yes", "test")
p.ready_or_not()
p.check_choice()
And then, you can change check_choice like this:
def check_choice(self):
if self.choice == 1:
self.set_name()
elif self.choice == 2:
self.set_names()
else:
print("Exiting....")
print("Goodbye!")
sys.exit(0)
Took me a while to figure out, but it seems like when you are done with display_menu() your calling ready_or_not() so you need to remove display_menu() from ready or not like this
# ready or not function to see if the user is ready to play
def ready_or_not(self):
# see if user types 1 or 2 with try & except
try:
# ask user if they are ready
self.ready = int(input("Are you ready to play? Type 1 for yes, 2 for no"))
# self.display_menu()
except ValueError:
print("You did not type 1 or 2, please try again!")
EDIT
looks like im late to the party
This question already has answers here:
error in python d not defined. [duplicate]
(3 answers)
Closed 8 years ago.
def money():
cashin = input("Please insert money: £1 Per Play!")
dif = 1 - cashin
if cashin < 1.0:
print ("You have inserted £", cashin, " you must insert another £", math.fabs(dif))
elif cashin > 1.0:
print ("Please take your change: £", math.fabs(dif))
else:
print ("You have inserted £1")
menu()
def menu():
print ("Please choose an ARTIST: <enter character ID>")
print ("<BEA> - The Beatles")
print ("<MIC> - Michael Jackson")
print ("<BOB> - Bob Marley")
cid = input()
if cid.upper == ("BEA"):
correct = input("You have selected the Beatles, is this correct? [Y/N]:")
if correct.upper() == ("Y"):
bea1()
else:
menu()
elif cid.upper() == ("MIC"):
correct = input("You have selected Michael Jackson, is this correct? [Y/N]:")
if correct.upper() == ("Y"):
mic1()
else:
menu()
elif cid.upper() == ("BOB"):
correct = input("You have selected Bob Marley, is this correct? [Y/N]:")
if correct.upper() == ("Y"):
bob1()
else:
menu()
else:
print ("That is an invalid character ID")
menu()
this is part of my code for a jukebox
my code is giving me the error that bea is not defined if I type 'bea' on the 'CHOOSE AN ARTIST' input. but i'm not trying to use it as a function or a variable? I want to use an if statement to decide what to do based on the users input
usually this works for me, I don't know what the problem is. This is only a section of my code, if you need to see more let me know
In Python 2.x, to get a string from a prompt, you use raw_input() instead of input():
cid = raw_input()
The input function in Python 2 is not equivalent to input in Python 3. It does not return a string, but evaluates it. In your case, you type bea and it tries to evalueate bea as an expression. But this name is not defined.
As mentioned in the docs for input:
Equivalent to eval(raw_input(prompt)).
Also, as #frostnational notes in his comment, you forgot to actually call the upper method on the next line, so you are trying to compare the method itself with a string. You want
if cid.upper() == "BEA":
I am trying to create menu where user can choose which part of the program he/she wants to run. When I am importing function computer automatically runs it rather to wait for user input. What shall I do to run function only when called? My code:
import hangman
menu = raw_input("""Welcome to Menu, please choose from the following options:
1. Hangman game
2.
3.
4. Exit
""")
if menu == 1:
hangman()
elif menu == 2:
"Something"
elif menu == 3:
"Something"
elif menu == 4:
print "Goodbye"
else:
print "Sorry, invalid input"
The code for hangman.py looks like that:
import random
words = ["monitor", "mouse", "cpu", "keyboard", "printer",]
attempts = [] # Stores user input
randomWord = random.choice(words) # Computer randomly chooses the word
noChar = len(randomWord) # Reads number of characters in the word
print randomWord , noChar
print "Hello, Welcome to the game of Hangman. You have to guess the given word. The first word has", noChar, " letters."
def game():
guess = raw_input ("Please choose letter")
attempts.append(guess) # Adds user input to the list
print (attempts)
if guess in randomWord:
print "You have guessed the letter"
else:
print "Please try again"
while True:
game()
chance = raw_input ("Have a guess")
if chance == randomWord:
print "Congratulations, you have won!"
break
Without seeing hangman.py, I would assume that it directly contains the code for running the hangman game, not wrapped in a function. If that's the case, you created a module, no function (yet).
Wrap that code in
def run_hangman():
# Your existing code, indented by 4 spaces
# ...
import it like this:
from hangman import run_hangman
and finally call the function like this:
run_hangman()
So here is the start menu:
import hangman
option = raw_input('1) Start Normal\n2) Quick Start\n3) Default') # '\n' is a new line
if option == '1':
hangman.main()
elif option == '2':
hangman.run_hangman('SKIP')
elif option == '3':
handman.run_hangman('Default User')
Inside your hangman code you want to have it modulated. You should have somthing like this:
def main():
stuff = raw_input('Starting new game. Please enter stuff to do things')
run_hangman(stuff)
def run_hangman(options):
if options == 'SKIP':
important_values = 5
vales_set_by_user = 'Player 1'
else:
values_set_by_user = options
rest_of_code()