Picking random variable in list - python

I am trying to pick a random dictionary variable from a list. I start out by choosing a random variable from the list emotelist.
import random
emotelist = [bored]
emotechosen = random.choice(emotelist)
emotename = emotechosen['emote']
emoteframe = emotechosen['frame']
bored = {'emote':'bored', 'frame':135}
print emotename
print emoteframe
But I recieve an error of
NameError: name 'bored' is not defined
Thank you for the help. I should have defined my variables in the list before creating the list of variables.

You have to define bored before creating a list that holds it:
import random
# move bored definition here:
bored = {'emote':'bored', 'frame':135}
# now use it in a list construction
emotelist = [bored]
emotechosen = random.choice(emotelist)
emotename = emotechosen['emote']
emoteframe = emotechosen['frame']
print emotename
print emoteframe

You need to define bored before using it:
import random
bored = {'emote':'bored', 'frame':135}
emotelist = [bored]
emotechosen = random.choice(emotelist)
emotename = emotechosen['emote']
emoteframe = emotechosen['frame']

It looks like you are trying to print a random dictionary value:
from random import choice
bored = {'emote':'bored', 'frame':135}
print bored[choice(bored.keys())]

Related

How to append elements from input to empty list in python

I want to make a program where an empty list is populated by an input from the user. How do I do that?
My python code:
def passanger_list(passangerInput, pp):
pp = ["passangers:"]
passangerInput = input("what is your passanger name?")
if passangerInput:
pp.append()
print(passanger_list)
Do it this way
''' You dont need to send pp and passengerInput as parameters for this function because, they're values are being initialized only when the passenger_list() is called. '''
def passenger_list():
''' It would be better for you to avoid having the passengers text inside. If you really want the values as passenger: "name of passenger", you can use a dictionary. I will add code for that as well.'''
pp = []
passengerInput = input("what is your passanger name?")
if passengerInput:
pp.append(passengerInput)
print(pp)
# This statement is crucial so that the value is passed back to the code that is calling it.
return pp
In this case, after calling passenger_list(), your output will look like ["Ram", "Shyam", "Sita"].
For output of the form - {"Passengers":["Ram","Shyam","Sita]}, please refer the code below.
def passenger_list():
pp = {"Passengers":[]}
passengerInput = input("what is your passanger name?")
if passengerInput:
pp["Passengers"].append(passengerInput)
print(pp)
# You can access the list using pp["Passenggers"]
print(pp["Passengers"]) # Output is ["Ram", "Shyam", "Sita"]
return pp
Read more about Python dictionaries here.
Maybe this will help you:
def passanger_list(passangerInput, pp):
if passangerInput:
pp.append(passangerInput)
return pp
pp = []
pp = passanger_list(
input("what is your passanger name?"),
pp
)
print("passangers:", pp)
Also, you might want to spell it "passengers" instead of "passangers".
def passanger_list():
pp = ["passangers:"]
passangerInput = input("what is your passanger name?")
if passangerInput:
pp.append(passangerInput)
return pp
print(passanger_list())
If you define pp = ["passangers:"] why do you want to get input for your function?
global pp
pp= {"passengers":[]}
def passanger_list():
passangerInput = input("what is your passanger name?")
pp["passengers"].append(passangerInput)
return pp
>>> passanger_list()
I think it is better to use a list of dictionaries instead of a list.
Instead of this:
pp = ["passangers:"]
passangerInput = input("what is your passanger name?")
if passangerInput:
pp.append()
print(passanger_list)
I would do:
passenger_list = []
def add_passenger(passenger_name):
if passanger_name:
passenger_list.append({"name":passenger_name})
add_passenger("bob")
print(passanger_list)
This way you can store multiple passengers and can even add other key-value pairs like seat number or class etc.
The way you are doing it will make it harder to retrieve information.

Getting input from input function, and running a function using that letter

I know this is possible with the eval() function, but, it does NOT work in my program. I have no clue why. So, is there another way? Here is some code: I am looking for a simple way, as I am new to python programming. Really new... I have tried eval() but it just returns an error. I have been at this for hours now, and haven't found an answer online. If this is relevant, I use repl.it turtle.
import turtle
from time import sleep
ninja = turtle.Turtle()
ninja.hideturtle()
coordinate1 = ninja.xcor()
coordinate2 = ninja.ycor()
new1=''
new2=''
ninja.speed(10)
def h():
ninja.left(90)
ninja.forward(50)
ninja.back(100)
ninja.forward(50)
ninja.right(90)
ninja.forward(35)
ninja.left(90)
ninja.forward(-50)
ninja.forward(100)
coordinate1 = ninja.xcor()
coordinate2 = ninja.ycor()
new1 = coordinate1+50
ninja.penup()
ninja.goto(new1,0)
def i():
ninja.forward(20)
ninja.pendown()
ninja.left(90)
ninja.st()
ninja.right(90)
ninja.stamp()
ninja.ht()
ninja.penup()
ninja.back(20)
ninja.pendown()
ninja.back(50)
coordinate1 = ninja.xcor()
new1 = coordinate1+50
ninja.penup()
ninja.goto(new1,0)
h()
i()
name = input('What is your name. It will be drawn in the tab to the left lowercase only please.')
print('The name will begin to draw in the tab to the left')
sleep(3)
ninja.clear()
ninja.goto(0,0)
name = list(name)
print(name)
length = len(name)
x=0
while (x < length-1):
print(name[x])
x = x + 1
new2=name[x]+'()'
eval(new2)
print(new2)
You could use a dictionary:
letter_movements = {'h': h, 'i': i}
Then, when you want to run the function (where you have eval) simply pick from the dictionary:
letter_movements[new2]()

Functions NameError

I have been messing around with some code, trying to create a function for work planning. However I am stuck and wondered if someone could help? Thanks
class Work_plan(object):
def __init__(self,hours_work,work_len, work_des):
self.hours_work = hours_work
self.work_len = work_len
self.work_des = work_des
work_load = []
hours_worked = []
if hours_worked > hours_work:
print "Too much work!"
else:
work_load.append(work_des)
hours_worked.append(work_len)
print "The work has been added to your work planning!"
work_request = Work_plan(8, 2, "task1")
Work_plan
print work_load
it comes up with the error:
NameError: name 'work_load' is not defined
You defined the variable work_load inside the __init__ of the class, so you can't access it outside this scope.
If you want to have access to work_load, make it an attribute for objects of Work_plan class, and the access it by doing object.work_plan
For example:
class Work_plan(object):
def __init__(self,hours_work,work_len, work_des):
self.hours_work = hours_work
self.work_len = work_len
self.work_des = work_des
self.work_load = []
self.hours_worked = []
if hours_worked > hours_work:
print "Too much work!"
else:
self.work_load.append(work_des)
self.hours_worked.append(work_len)
print "The work has been added to your work planning!"
work_request = Work_plan(8, 2, "task1")
Work_plan
print work_request.work_load

NameError after importing a file

I have two files. One called "variables.py" with this function in:
def get_players():
'''
(NoneType) -> Dictionary
Asks for player names
'''
loop = True
players = {}
while loop == True:
player = input("Enter player names: ")
player = player.strip()
if player in players or player == "":
print("Choose a different name!")
elif "player1" in players:
players["player2"] = [player, 0]
elif player not in players:
players["player1"] = [player, 0]
if len(players) >= 2:
loop = False
return players
And another file in the same directory called "game.py" with this inside:
import variables
players = get_players()
When i try to run "game.py" i get this errorNameError: name 'get_players' is not defined
why?! I have tried everything!
It should be
players = variables.get_players()
Since you have imported only the module variables, and not the method get_players.
Or you could also do:
from variables import get_players
players = get_players()
Read more on importing modules here
You have imported variables, not get_players. You can either keep the import as it is and call variables.get_players(), or do from variables import get_players and then call get_players().
This is a fairly fundamental thing in Python: looks like you could benefit from a basic tutorial.
With Python, when you import a module, a module variable is created of that name which is where all the imported module's variables live:
import variables
players = variables.get_players()
You can also import from a module which will just introduce that name by itself:
from variables import get_players
players = get_players()
You can also do the following to import all names from a module, but it is discouraged because it leads to hard-to-read code:
from variables import *
players = get_players()

How to save a function with python (3.2)

Just started learning python (3.2) and have a question. I have created a some code that creates some stats (as in health, magic etc etc) and the numbers are randomly generated. Here is the code...
def stats ():
print ()
print ('Some text.')
done = False
while not done :
charname = input(str('What is the name of the character? '))
hp = random.randint(5,20)
mp = random.randint(4,20)
stre = random.randint(3,20)
agi = random.randint(3,20)
spd = random.randint(3,20)
wis = random.randint(3,20)
intel = random.randint(3,20)
cha = random.randint(3,20)
print (charname)
print ('HP:',hp)
print ('Mana:',mp)
print ('Strength:',stre)
print ('Agility:',agi)
print ('Speed:',spd)
print ('Wisdom:',wis)
print ('Intelligence:',intel)
print ('Charisma:',cha)
print ()
done = input('All done? yes/no ')
if( done == 'yes' ):
done = True
elif(done == 'no'):
done = False
while done :
print ()
print ('Now that your stats are done, you can go on your adventure!')
done = False
Now this works fine, but how could I call on this function again in case I wanted to view the stats again with it keeping the same stats it randomly generated before?
Sorry if the question is bit off. Still all new to programming.
Thank you.
Since you're new to programming, here's some advice on a different way to store your data (without actually coding it for you).
First, define a Character class, with attributes for HP, mana, etc. I don't know if you know about classes yet, but here's an intro. There are various tricks you can do to get around having to explicitly write in the names for HP, mana, etc, but for learning's sake, it's probably better to do them all manually for now.
Then def a random_character() function that creates a Character object with random attributes, defined like how you're doing now, but instead of saving them in different variables that Python doesn't know have anything to do with one another, puts them in a single Character.
Add a __str__ method to the Character class, so that if char is a Character, print(char) prints out the attributes.
If you want to be able to keep track of characters, use pickle to store it in files.
If you have questions about any part of this, just ask. :)
Your function now uses local variables to record the stats you've generated. You'll need to bundle them together into either a dictionary or an object so that you can pass them around as a value.
For example:
def get_stats():
stats = {}
stats['charname'] = input(str('What is the name of the character? '))
stats['hp'] = random.randint(5,20)
stats['mp'] = random.randint(4,20)
stats['stre'] = random.randint(3,20)
stats['agi'] = random.randint(3,20)
stats['spd'] = random.randint(3,20)
stats['wis'] = random.randint(3,20)
stats['intel'] = random.randint(3,20)
stats['cha'] = random.randint(3,20)
return stats
def print_stats(stats):
print (stats['charname'])
print ('HP:',stats['hp'])
print ('Mana:',stats['mp'])
print ('Strength:',stats['stre'])
print ('Agility:',stats['agi'])
print ('Speed:',stats['spd'])
print ('Wisdom:',stats['wis'])
print ('Intelligence:',stats['intel'])
print ('Charisma:',stats['cha'])
print ()
you can use def keyword to declare functions . Def
def stat():
you can call the function like this in your desired location. stat()
If you want easy storage in an external file, you can use the pickle module, and a dictionary of the values you wish to store.
for example:
import pickle
stats={}
stats['hp'] = random.randint(5,20)
stats['mp'] = random.randint(4,20)
stats['stre'] = random.randint(3,20)
stats['agi'] = random.randint(3,20)
stats['spd'] = random.randint(3,20)
stats['wis'] = random.randint(3,20)
stats['intel'] = random.randint(3,20)
stats['cha'] = random.randint(3,20)
#save the stats into the file by using:
pickle.dump(stats,yourstatfile.pkl)
#then to load it again from any program just use:
stats=pickle.load(yourstatfile.pkl) #you assign it to a variable, so if i used the variable 'lol' i would use it as lol['hp'] not stats['hp'] like it was originally used when saving.
#then you can use it just like any other dictionary:
print "your hp: "+str(stats['hp'])

Categories