I am currently writing a game of Blackjack using python 2.7. as part of the app's gameflow I have defined a new function called player_turn(), in which I required a user input that would result in different scenarios depending on the input ("hit" would give the player another card, and "hold" would end the player's turn and pass it on to the dealer. otherwise would result in a customized error)
def player_turn():
if sum(player_card_numbers) < 21:
user_decision = input('would you like to hit or hold?')
if user_decision == 'hit':
player_cards.append(deck.draw())
print player_cards, dealer_cards
player_turn()
elif user_decision == 'hold':
print "Dealer's turn!"
dealer_turn()
else:
print "player must choose 'hit' or 'hold'"
player_turn()
elif sum(player_card_numbers) == 21:
print "Blackjack!"
dealer_turn()
else:
print "Player Burnt! \nDealer's turn!"
dealer_turn()
It is worth mentioning that the code was originally written in python 3.7, and was changed later on. the code worked perfectly with 3.7.
Now I get this error:
NameError: name 'hit' is not defined
I would love some advice on how to solve this issue, as well as an explanation on why this would happen. :)
The problem is this line:
user_decision = input('would you like to hit or hold?')
In Python2, input() has an eval() nature to it, so it's evaling your answer: hit
>>> user_decision = input('would you like to hit or hold?')
would you like to hit or hold?hit
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'hit' is not defined
>>>
The coding standard for Python 2 is to not use input() but rather use raw_input() instead:
>>> user_decision = raw_input('would you like to hit or hold?')
would you like to hit or hold?hit
>>> user_decision
'hit'
>>>
In Python 3, the input() function is equivalent to raw_input() in Python 2.
Related
I am writing Oregon trail game and this is the code I have that is causing issues, I don't know why it is having issues. What I want to do is if they enter a name that contains a word that is in a list it will set the variable easter_mode to 1 if they don't then it will set easter_mode to 0. The words that need to be in the list are: (Sturtz, sturtz, Nate, nate)
Thank you
#asking name
player_name = input('What is your name:')
while len(player_name) >= 0:
if len(player_name) > 1:
print("Weclome" + str(player_name))
print('Which mode do you want to play?')
mode_choice = input('(easy) More modes comming soon:')
break
if len(player_name) == 1:
player_name_choice = input(str(player_name)+"? Are you kidding me? Only one letter? You might regreat it (Y/N):")
if player_name_choice == "y" or player_name_choice == "Y":
print("Ok Your Choice!!...")
mode_choice = 'easter'
break
if player_name_choice == "n" or player_name_choice == "N":
player_name = input('What is your name:')
else:
print("You do not type anything, try again")
player_name = input('What is your name:')
#Check Easter Egg Names
easter_names = ["nate sturtz", "Nate Sturtz", "Nate", "nate", "Sturtz", "sturtz"]
if player_name in easter_names:
easter_mode = 1
else:
easter_mode = 0
#easter eggs for name
if easter_mode == 1:
year_set = 2005
mode_choice = 'easter'
else:
year_set = input('Enter a year whatever you like:')
if year_set.isdigit():
return_num = 0
else:
return_num = 1
while return_num == 1:
print('Error,please try again!')
year_set = input('Enter a year whatever you like:')
if year_set.isdigit():
return_num = 0
else:
return_num = 1
year_set = int(year_set)
When I run the full file I get
Traceback (most recent call last):
File "Oregon.py", line 64, in <module>
player_name = input('What is your name:')
File "<string>", line 1, in <module>
NameError: name 'nate' is not defined
You can view the full code on Github
https://raw.githubusercontent.com/nsturtz/Oregon-Trail/master/Oregon.py
You'll get this error in Python 2. In Python 2, input() uses the exact value as your enter it.
In your example, you're typing nate and not 'nate'. The former value is a variable name (which is undefined in your code, hence the NameError), whereas the latter is a string.
In Python 3, input() behaves as you assume, and passes a string to your code.
If you are sure that you want to use Python 2, you can replace input() with raw_input() and it will interpret your input as a string rather than a variable name.
Under Python 2, you can use raw_input instead of input to prevent Python from interpreting the user input as Python code.
However, since Python 2 is deprecated, I strongly recommend against using it1. Use Python 3 instead, where input works as expected.
1 Except of course to maintain legacy products. But that doesn’t seem relevant here.
>>> Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Maximillian\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Python-koding\steinsakspapir.py", line 64, in scissors
botwin += 1
UnboundLocalError: local variable 'botwin' referenced before assignment
-Tried to remove botwin and youwin from rest of the code
-Tried to use youwin = youwin + 1
def scissors():
bot = random.randint(1,3)
user = 3
if user == bot:
printfuver = ("Stalemate, booth players choose scissors")
printfu = Label(lowerframe, text=printfuver, fg="blue")
printfu.pack()
if user == 3 and bot == 1:
printfuver = ("Rock crushes scissors, bot win! ")
printfu = Label(lowerframe, text=printfuver, fg="red")
printfu.pack()
botwin += 1
if user == 3 and bot == 2:
printfuver = ("Scissors cut paper, you win! ")
printfu = Label(lowerframe, text=printfuver, fg="green")
printfu.pack()
youwin += 1
Simply want botwin to increase with a value of 1 after each time the fuction is ran.
thanks in advance
Aside from the indentation error in your code, this is probably a scope issue. Check to make sure you have botwin = 0 or something like it somewhere in your code. If that code is in a function or otherwise out of global scope, put it at the top of your code. Then, in all functions that reference it, put global botwin at the beginning of your function as explained here.
I hope this helps you.
To sum it up, I have little understanding in what I am doing so I will write a portion of the code so maybe anyone can see what's going on.
import sys
start = input("Continue? y/n ")
if start == "y":
startp()
elif start == "n":
print("Party pooper")
def startp():
text = 'text\n'
text2 = 'text2'
for char in text:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.1)
for char in text2:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.1)
startp()
If this is run, you can enter a letter/word, but the out come is
Traceback (most recent call last):
File "C:/Users/-/Desktop/--.py", line 4, in <module>
startp()
NameError: name 'startp' is not defined
I think what I need to do is call the function after the user has typed y or n - but I have no idea how to, any help would be greatly appreciated.
As python create the functions in run time you can not call it before define the function.
if start == "y":
startp()
^
The error is produced here:
if start == "y":
startp()
because startp is defined below those lines of code.
You should always define the functions first (unless you have a reason to not do so). Also, text and text2 aren't returned by the function, maybe you wanted to include the loops inside it?
import sys
def startp():
text = 'text\n'
text2 = 'text2'
for char in text:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.1)
for char in text2:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.1)
start = input("Continue? y/n ")
if start == "y":
startp()
elif start == "n":
print("Party pooper")
When you're reading a book, should you start with they lived happily ever after or once upon a time? Just as you would read a book, the compiler reads starting at the beginning and thus your function should be declared before it is used.
You should define your function before calling it.
As the output says,startp() is not defined in the line 4 when you're trying to call it. Define your function before calling it and your code will be cleaner and probably will work better ;)
I am trying to make a program that can add/delete/show students in a class, and the 5 classes are 5 lists in a list.
Help is greatly appreciated.
When I run this code:
global classes
def intro():
print("Welcome to Powerschool v2.0!")
print("Actions:")
print("1. Add Student")
print("2. Delete Student")
print("3. Show Students in a Class")
print("4. Show All Students")
x = int(input())
while x<1 or x>4:
print ("Please choose an action, 1-4.")
x = int(input())
if x == 1:
action1()
elif x == 2:
action2()
elif x == 3:
action3()
elif x == 4:
action4()
classes = [[],[],[],[],[]]
return classes
def action1():
print("Which Class? 1-5")
a = int(input())
print("Please enter the student's name.")
z = input()
classes[a-1].append(z)
again()
def action2():
print ("Which Class? 1-5")
print ("Which student?")
again()
def action3():
print ("Which Class? 1-5")
y = int(input())
if y == 1:
print (classes[0])
elif y == 2:
print (classes[1])
elif y == 3:
print (classes[2])
elif y == 4:
print (classes[3])
elif y == 5:
print (classes[4])
again()
def action4():
print (classes)
again()
def again():
print("Would you like to do something else? y/n")
h = input()
if h == "y":
intro()
else:
quit
def main():
intro()
main()
My error is:
Traceback (most recent call last):
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 67, in <module>
main()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 65, in main
intro()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 19, in intro
action1()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 33, in action1
classes[a-1].append(z)
NameError: name 'classes' is not defined
I did return classes at the end of intro() but I see that doesn't work.
I followed some suggestions, and nothing really happened :/
You're defining classes in your intro method, and, even though it's returning it, your action1 method doesn't see any variable named classes anywhere.
Relevant answer on Python scope and relevant documentation.
return doesn't do what you think it does. return statements are a way of passing execution control back up a context (For example, from intro() to main()), with the ability to send back some information for the higher context to use. Although you're passing classes back to main(), you never do anything with it at that context so it goes away.
One way to solve the problem would be to declare classes as a global variable. This is the easiest thing to do, but isn't generally good design. You could do this either by using the global keyword before declaring the local variable classes in intro() (See this question for guidance on global), or by declaring classes outside any of your functions.
Another solution would be to pass classes as a parameter to your action functions.
In either case, you would need to declare classes before any calls to your action functions.
This is because classes is out of scope for the second two methods. Therefore, you have two options:
Option 1
Pass classes to the methods action1(), action2(), etc like so:
def action1(classes)
...and the when you call it:
action1(classes) //with the classes var you just made
Option 2 (recommended)
Simply put the classes var outside your methods or declare it global like so:
global classes = [[],[],[],[],[]]
...right before:
def intro()
In general, you should read up on how return works; it is not necessary in the code you wrote
classes only exists in intro():, you would have to declare it as a global variable to access it in other functions or declare it outside the function.
classes = [[],[],[],[],[]] # can be accessed by action3() ,action4()
def intro():
i'm not sure how to go about this...
I want to use import to go to another script (Once it's called, the original script has finished) but I need the second script to print a variable from the original.
So, I can import the second script and use the prints fine, however if I try and import the original script so I can access the variable..
But if I do that, it just gives me an error:
Traceback (most recent call last):
File "C:\Users\luke\Desktop\k\startGame.py", line 2, in <module>
import Storyline
File "C:\Users\luke\Desktop\k\Storyline.py", line 1, in <module>
import startGame
File "C:\Users\luke\Desktop\k\startGame.py", line 56, in <module>
Storyline.startGame1()
AttributeError: 'module' object has no attribute 'startGame1'
I am trying to print this:
print ("I see you have picked " + startGame.currentPokemon)
and I am calling it like this:
Storyline.startGame1()
and the currentPokemon is
currentPokemon = inputKK
(InputKK is an input of the starter pokemon)
Is there any way to do this? And yes, i'm making a pokemon game in Python, but it's a version that isn't using real pokemon names..
Storyline script:
import startGame
def startGame1():
print ("Welcome to the H.Q of I.O.D")
print ("I am Professor Steel.")
print ("I see you have picked " + startGame.currentPokemon)
startGame script:
import Storyline
inputKK = input("Choose from, 'Craigby', 'Robinby' or 'KKby' ")
if(inputKK == "Craigby"):
print("Craigby is a electric type.")
print("Craigby: Attack = 7, Defence = 3, Health = 6, Speed = 12")
if(inputKK == "Robinby"):
print("Robinby is a fire type.")
print("Robinby: Attack = 6, Defence = 5, Health = 7, Speed = 7")
if(inputKK == "KKby"):
print("KKby is a water type.")
print("KKby: Attack = 5, Defence = 8, Health = 11, Speed = 5")
print("")
os.system('cls')
currentPokemon = inputKK
counter = 0;
while(counter < 1):
print("Welcome to pokeby.")
print("Type S for [STORYLINE]")
print("Type R for pokemon in the field [CURRENT IS GRASS] ")
print("Type Q for [QUIT]")
inputMainMenu = input("S/R/Q ...")
if(inputMainMenu == "S"):
os.system('cls')
counter = counter + 2
Storyline.startGame1()
if(inputMainMenu == "R"):
os.system('cls')
counter = counter + 2
if(inputMainMenu == "Q"):
os.system('cls')
inputExit = input("Are you sure you want to quit? Y/N ")
if(inputExit == "Y" or inputExit == "y"):
print("K")
else:
counter = counter + 1
Don't import StartGame in your Storyline script. Instead, just pass the desired value to your StartGame1 function.
# Storyline.py
def startGame1(currentPokemon):
print ("Welcome to the H.Q of I.O.D")
print ("I am Professor Steel.")
print ("I see you have picked ", currentPokemon)
Then in startGame you call Storyline.startGame1(inputKK) passing the name of the Pokemon.
BTW, it's a little confusing that your startGame1 function isn't in the module startGame...
You are trying to import Storyline into startGame, and also trying to import startGame into Storyline. You just can't do this kind of recursive import. While importing startGame, Storyline is coming across your Storyline.startGame1() call before startGame1() has been defined, so you get the no attribute error.
You should restructure your files so that this becomes unnecessary.
[edit: don't listen to me; it was late and I didn't think hard enough about what I was saying.]
You can't reference attributes or methods in a module like that. What you need is to put your methods in a class. Alternatively, I think you could do from Storyline import startGame1(). But really, use classes [if you want to]; [i think] they are good. Python docs on classes here.