NameError: name 'char' is not defined error - python

I'm trying to make a text game in python and i'm trying to debug the game right now.
I think this code I'm writing is supposed to type out the letters/characters one by one and make a typing effect.
here it is:
def setup_game():
### BACKSTORY TELLING
backstory = "something something boring backstory"
typeout(backstory)
def typeout(x):
time.sleep(0.03)
sys.stdout.write(char)
sys.stdout.flush()
option = input('> ')
if option.lower() == '> ok':
title_screen()
else:
print("please try again\n")
option = input('> ')
#Actual game
def start_game():
print_location()
main_game_loop()
setup_game()
but whatever i do it always gives me an error and i don't know how to fix it.
here it is:
Traceback (most recent call last):
File "textgame.py", line 612, in <module>
setup_game()
File "textgame.py", line 600, in setup_game
typeout(backstory)
File "textgame.py", line 604, in typeout
sys.stdout.write(char)
NameError: name 'char' is not defined
all the lines referenced in the error are in the code from the top.
I did find another post about the:
time.sleep(0.03)
sys.stdout.write(char)
sys.stdout.flush()
part and i tried doing what the answer said but instead it just gave me a different error which is what i have now.
help would be appreciated, thanks

You need to do something like:
sys.stdout.write(x)
Because char is not defined in your code. You're passing x to the function.

Related

Automate The Boring Stuff with Python Ch 4 myPets

I am currently working through Automate the Boring Stuff with Python and was given this example in Chapter 4 (You can read the page here if you're curious). The code was typed from the example given in the book as suggested and is pasted below. In the book, I am told the response I get is supposed to prompt me to enter a pet name, and if it doesn't match what's in the list I should get a response saying that I don't have a pet by that name.
The problem I run into is that the response I ACTUALLY get is :
Enter a pet name:
Gennie
Traceback (most recent call last):
File "/Users/gillian/Documents/Python/AutomateTheBoringStuffwithPython/Ch4Example1.py", line 3, in <module>
name = str(input())
File "<string>", line 1, in <module>
NameError: name 'Gennie' is not defined
I'm not sure why that would be. I don't see anything different about my code from the example, but something about that error seems not right. Can anyone tell me where I've gone off course?
myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name: ')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
Change input() into raw_input() as you seem to be using python 2.x and this code is written in 3.x.
Find out more about differences here.

Why do I keep getting this error when checking a variable within an "if" condition?

When I run this code:
#!/usr/bin/python
from time import strftime
#welcome
state = input("Morning? [y/n] ")
if state == y:
print("Good morning sir! Welcome to our system!")
pass
else:
print("Good afternoon sir! Welcome to our system!")
pass
user = input("What is your name? ")
print("Hello World.")
print("{} is using this computer right now".format(user))
print(strftime("%Y-%m-%d %H:%M:%S"))
I get this error:
Morning? [y/n] y
Traceback (most recent call last):
File "C:/Users/toshiba/py/hello/hello_world.py", line 7, in <module>
if state == y:
NameError: name 'y' is not defined
This code is intended to display a custom print message depending on the input of the user as seen in the first input method. I code in python 3 and I can't figure out the issue.
Your if statement should be:
if state == 'y':
The type of state is a string.
Also, your if statement will currently fail if the user enters Y or yes. It's not excruciatingly important now, but you could always handle that like this:
if state in ('y', 'Y', 'yes'):
It's just something good to know for the future.

Executing a function in Python [duplicate]

This question already has answers here:
"NameError: name '' is not defined" after user input in Python [duplicate]
(3 answers)
Closed 7 years ago.
I am having a spot of bother with the following script, it uses a function within it:
def my_function(arg1, arg2, arg3):
print("I love listening to %s" %(arg1))
print("It is normally played at %d BPM" %(arg2))
print("I also like listening to %s" %(arg3))
print("Dat be da bomb playa!")
print("What music do you like listening to?")
ans1 = input(">>")
print("What speed is that usually played at?")
ans2 = input(">>")
print("whats your second favourite genre of music?")
ans3 = input(">>")
my_function(ans1, ans2, ans3)
I get to the first user input: What music do you like listening to? When I type in 'House' and hit enter, I am expecting the second question to be displayed, but I get the following error message:
Traceback (most recent call last):
File "ex19_MyFunction.py", line 26, in <module> ans1 = input(">>")
File "<string>", line 1, in <module>
NameError: name 'house' is not defined**
Any help would be appreciated!
If you use Python2 then use raw_input() because input() try to parse text as python code and you get error.
Your script would run just fine in Python3, so I am assuming you are using Python2. Change input to raw_input.
In Python2, raw_input will convert the input to a string, while input('foo') is equivalent to eval(raw_input('foo')).

Create Variables and Dictionaries from .txt

I currently have this as my code.
def makeFolder():
if not os.path.exists('Game Saves'): os.makedirs('Game Saves')
def saveAllPlayerInfo(dest,fileName):
f=open(dest+fileName,'w')
f.write("{0}:{1}\n".format('playerName',playerName))
f.write("playerStats={\n")
f.write("\t'{0}':'{1}'\n".format('playerMaxHp',playerStats['playerMaxHp']))
f.write("\t'{0}':'{1}'\n".format('playerCurrentHp',playerStats['playerCurrentHp']))
f.write("\t'{0}':'{1}'\n".format('playerAtk',playerStats['playerAtk']))
f.write("\t'{0}':'{1}'\n".format('playerDef',playerStats['playerDef']))
f.write("\t'{0}':'{1}'\n".format('playerDefending',playerStats['playerDefending']))
f.write("\t'{0}':'{1}'\n".format('playerRunAbility',playerStats['playerRunAbility']))
f.write("\t'{0}':'{1}'\n".format('luck',playerStats['luck']))
f.write("\t'{0}':'{1}'\n".format('playerExperience',playerStats['playerExperience']))
f.write("\t'{0}':'{1}'\n".format('level',playerStats['level']))
f.write("\t}")
f.close()
def saveFile():
makeFolder()
dest=os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+'\\Game Saves\\'
fileName="{0}.txt".format(playerName)
if not (os.path.isfile(dest+fileName)):
print("New File Created")
print("Game Has Been Saved")
saveAllPlayerInfo(dest,fileName)
elif (os.path.isfile(dest+fileName)):
saveAllPlayerInfo(dest,fileName)
print("Game Has Been Saved")
def readFile():
gameFiles=[f for f in os.listdir(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+'\\Game Saves\\') if isfile(join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+'\\Game Saves\\',f))]
dest=os.path.basename(os.path.abspath(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+'\\Game Saves\\'))
print("What would you like to do?")
print("1. Load a Game")
print("2. Start a New Game")
ans=input()
a=0
while a==0:
if ans.lower() in ["1.","1","load a game","load game","load"]:
print("")
print("Select Which Game: ")
filesRead=0
for saves in gameFiles:
gameSave=(open(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+'\\Game Saves\\'+gameFiles[filesRead],'r'))
firstLine=gameSave.readline()
print("{0}. {1}".format(filesRead+1, firstLine[11:]))
filesRead+=1
gameToLoad=input("")
if int(gameToLoad)<=filesRead:
exec(gameSave.read())
a=1
elif ans.lower() in ["2.","2","start a new game","start a game","start game","start"]:
clr()
newGame()
a=1
else:
print("I didn't understand that. Can you say that again?")
And this is the file it is pulling from. It is called 'Alex.txt'
playerName:Alex
playerStats={
'playerMaxHp':'10'
'playerCurrentHp':'10'
'playerAtk':'5'
'playerDef':'5'
'playerDefending':'0'
'playerRunAbility':'10'
'luck':'10'
'playerExperience':'0'
'level':'1'
}
Now, I understand that it currently doesn't have anyway to translate what file you input into the code for what the program should load. But that's not what I'm worrying about.
The problem here is that I want as elegant and simple of a solution as possible to load the file. That's why I saved it in the format I did. That's the exact format it is inside the code itself.
But when I execute it as is, I get
Traceback (most recent call last):
File "E:\Game.py", line 614, in <module>
readFile()
File "E:\Game.py", line 82, in readFile
exec(gameSave.read())
File "<string>", line 3
'playerCurrentHp':'10'
^
SyntaxError: invalid syntax
And when I do an eval() instead, I get.
Traceback (most recent call last):
File "E:\Game.py", line 614, in <module>
readFile()
File "E:\Game.py", line 82, in readFile
eval(gameSave.read())
File "<string>", line 1
playerStats={
^
SyntaxError: invalid syntax
Both have problems. I'd like to just have a few lines of code if possible.
I've also tried having it go line by line, but neither will accept the line that eval is getting stuck on (Unexpected EOF error).
I will not import any third party modules. I am working on many computers, and I do not want to have to install modules on all the computers I'm working on for one project.
Can someone offer an elegant solution to my problem?
(Also, is there a way to simplify my reading function, specifially the dest= part? Seems pretty complex to me. I just searched here, did some testing, threw something together until it worked, and stuck with it. But it feels like it should be able to be far less obtuse.)

Python 3 builtins.NameError: global name --- is not defined -

Need some guidance here please. This is probably a stupid mistake, but I'm getting the "builtins.NameError: global name -- is not defined" error and I'm not seeing why - I'm still learning the language :).
Here is my code:
def option(x):
if x == "E":
enter()
elif x == "V":
view()
else:
exit()
def enter():
msg = input("Enter the message\n")
main()
def view():
##if msg == 0:
#print("no message yet")
#main()
#else:
print("The message is:", msg )
main()
def exit():
print("Goodbye!")
def main():
print("Welcome to BBS")
print("MENU")
print("(E)nter a message")
print("(V)iew message")
print("e(X)it")
print("Enter your selection:")
choice = input()
option(choice)
#msg = 0
main()
My problem is that I'm getting this even though I'm choosing the "E" option first:
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 36, in <module>
File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 33, in main
File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 3, in option
pass
File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 11, in enter
File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 33, in main
File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 5, in option
File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 18, in view
builtins.NameError: global name 'msg' is not defined
Could I please be guided? I've been searching for info and haven't found anything, and my conclusion is that it is probably something really stupid and noobish.
Also, as you guys can see from what I've commented out, I've attempted to restrict "view" from giving an error by checking that msg != 0 -- I made msg = 0 in main() - this obviously doesn't work because after going through enter() it goes back to main() and makes msg == 0 again. Could you guys link me to a page/guide that will help me understand how to solve this? I don't want to be spoon fed that much..
Thanks,
Itachi
The problem here is that msg inside enter() is a local variable: it's created when the enter() function runs, and it ceases to exist when enter() returns. Normally, whenever you set a variable inside a function, you're setting a local variable. If you want to set a global variable, which retains its value even after the function returns, use a global statement:
def enter():
global msg
msg = input("Enter the message\n")
main()
That said, global variables are often not the best way to do things. It may be better to have the enter() function return the message instead of storing it in a variable.
msg is a name that's not scoped to be used anywhere. That's why you get the NameError.
Each one of the functions you've created should stand alone and have straightforward inputs and outputs.
main is your entry point and it should call other functions as appropriate.
Those functions will return to their caller when their execution is complete. They can and in some cases should return some amount of data back to their caller.
For example, here's a subset of your problem showing how main invokes view and then returns:
def view(text):
if not text:
print("no message yet")
else:
print("The message is:", msg )
def main():
print("Welcome to BBS")
print("MENU")
print("(E)nter a message")
print("(V)iew message")
print("e(X)it")
print("Enter your selection:")
while not exiting:
choice = input()
view(choice)
exiting = True # TODO: set this based on the value in choice

Categories

Resources