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]()
Related
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.
Apologies for this newbie question. I'm not sure if I even phrased it correctly.
I have a class inside a function that lists a bunch of variables, and I want to be able to choose which variables are printed and returned at the final function call. However, I clearly don't understand enough about objects to accomplish this, because it raises errors when I try to attempt something.
def gpscall(call):
#Write GPSinput
out = ''
ser.write(com.GPSstatus.encode())
time.sleep(1)
#Read output
while ser.inWaiting() > 0:
decoded = (ser.read(1).decode)
out += decoded()
strlen = len(str(out))
substr = out[0:strlen-9]
#GPS? information list
variables = substr.splitlines()
#Storing each output in a variable
class GPS:
PULSE_SAWTOOTH = [int(s) for s in variables[1] if s.isdigit()]
TRACKED_SATELLITES = [int(s) for s in variables[2] if s.isdigit()]
VISIBLE_SATELLITES = [int(s) for s in variables[3] if s.isdigit()]
LONGITUDE = variables[5]
longlen = len(LONGITUDE)
LONGDEG = LONGITUDE[0:longlen-7]
LONGMIN = LONGITUDE[longlen-7:]
LATITUDE = variables[6]
latlen = len(LATITUDE)
LATDEG = LATITUDE[0:latlen-7]
LATMIN = LATITUDE[latlen-7:]
HEIGHT = variables[7]
KNOTS = variables[8]
DEGREES = [9]
GPS_STATUS = variables[10]
TIMING_MODE = variables[17]
FIRMWARE_VERSION = variables[20]
print (call)
return (call)
if __name__ == "__main__":
#Call the functions
gpscall(gpscall.GPS.LATITUDE)
This raises the error,
Function 'gpscall' has no 'GPS' member.
I don't understand why it cannot see the class, I think I'm using the function parameters incorrectly.
Any help with my poorly written code would be greatly appreciated.
Perhaps something like so is your intention? __init__ will initialize the object, and the self. will "save variables to the object."
class GPS:
def __init__(self):
#Write GPSinput
ser.write(com.GPSstatus.encode())
#Read output
out = ''
while ser.inWaiting() > 0:
decoded = (ser.read(1).decode)
out += decoded()
#GPS information list
substr = out[0:len(str(out))-9]
variables = substr.splitlines()
self.PULSE_SAWTOOTH = [int(s) for s in variables[1] if s.isdigit()]
self.TRACKED_SATELLITES = [int(s) for s in variables[2] if s.isdigit()]
self.VISIBLE_SATELLITES = [int(s) for s in variables[3] if s.isdigit()]
self.LONGITUDE = variables[5]
self.LONGDEG = LONGITUDE[0:len(LONGITUDE)-7]
self.LONGMIN = LONGITUDE[len(LONGITUDE)-7:]
self.LATITUDE = variables[6]
self.LATDEG = LATITUDE[0:len(LATITUDE)-7]
self.LATMIN = LATITUDE[len(LATITUDE)-7:]
self.HEIGHT = variables[7]
self.KNOTS = variables[8]
self.DEGREES = variables[9]
self.GPS_STATUS = variables[10]
self.TIMING_MODE = variables[17]
self.FIRMWARE_VERSION = variables[20]
gps = GPS()
print(gps.GPS_STATUS)
Yor cls inside the function is perfect and there is nothing wrong there. You are just trying to call the function and the cls objects in a wrong way.
if __name__ == "__main__":
#Call the functions
gpscall(gpscall.GPS.LATITUDE) <---- ERROR HERE
gpscall is a function, so when you are trying to access GPS.LATITUDE, it won't find any objects. You would have to do either this
gpscall(gpscall("").GPS.LATITUDE)
But I think the best way to do this is to write the func inside the cls. You will still be able to access all the variables of the cls, and it won't create much hassle.
PS: That's a good question, not a noob one. Good luck (y)
I'm trying to get the last few lines of the following code to have when one of the original 6 buttons is pressed to call the appropriate function to rename the buttons. I've tried changing the command line to buttons[0].command = Pistols(). I've also tried using a if loop with a variable such as x == 1 to determine that if the button is pressed x with then be 1 and the for loop will call the function Pistols, but with no success. However the button automatically calls the function and renames the first button to ".44 Pistol" rather than what it should be "Pistols". I wan't the command to only be executed and call the function when pressed. I know that tkinter will automatically look to the function being called and run it's code. How can I either delay this or go about this in another way to have the functions code only execute when pressed. Thanks in advance!
from tkinter import *
buttons = []
clm = [1,2,1,2,1,2]
rw = [1,1,2,2,3,3]
btnmain_list = ['Pistol','Rifle','Assult Rifle','Submachine Gun','Heavy Weapon','Plasma Weapons']
btnpistol_list = ['.44 Pistol', '10mm Pistol', 'Pipe Bolt-Action Pistol','Flare Gun', 'Pipe Pistol', 'Pipe Revolver']
btnrifle_list = []
btnasrifle_list = []
btnsubgun_list = []
btnheavy_list = []
btnplasma_list = []
ms = Tk()
ms.title('Fallout 4 weapon mods and needed materials')
ms.geometry('450x400')
placement = Frame(ms)
placement.grid()
class Guns:
def Pistols ():
buttons[0] = Button(placement,height = '5',width = '20', text = btnpistol_list[0])
buttons[0].grid(column = clm[0], row = rw[0])
def Rifles ():
x = 0
def AssultRifles ():
x = 0
def SubmachineGuns ():
x = 0
def HeavyWeapons ():
x = 0
def PlasmaWeapons ():
x = 0
for i in range (6):
b = Button(placement,height = '5',width = '20', text = btnmain_list[i])
b.grid(column = clm[i], row = rw[i])
buttons.append(b)
buttons[0].command = Pistols()
I've found a solution by changing the class to this:
class Guns:
global counter
counter = 0
def pistolCycle():
global counter
buttons[0].config(text=btnpistol_list[counter])
if counter == len(btnpistol_list)-1:
counter=0
counter = counter+1
def Pistols ():
buttons[0] = Button(placement, height = '5',width = '20', text="Pistols", command = lambda: Guns.pistolCycle() )
buttons[0].grid(column = clm[0], row = rw[0])
def Rifles ():
x = 0
def AssultRifles ():
x = 0
def SubmachineGuns ():
x = 0
def HeavyWeapons ():
x = 0
def PlasmaWeapons ():
x = 0
for i in range (6):
b = Button(placement,height = '5',width = '20', text = btnmain_list[i])
b.grid(column = clm[i], row = rw[i])
buttons.append(b)
Pistols()
So, here's a breakdown of what happens:
Once your buttons are defined, the Pistol function is called, which adds all the features to your Pistol button, including changing the text, and adding the function it will call when pressed.
When the button is pressed, it calls to pistolCycle. What pistol cycle does, is takes the "counter" value, and changes the text of the button to the item in the list which is associated to it. EG, when the counter is 0, .44 Pistol is displayed.
The counter increases by one, each time pistolCycle is called, meaning the next time it's called, it will display the next item in the list.
Now, using global variables can get messy. I've given you the basic framework, so you may be able to use your own logic to get the variable "counter" to pass into pistolCycle each time (EG, pistolCycle(counter))
You will need to make a separate counter and cycle function in order for all the buttons to work.
I hope this helped!!
PS: The if statement in the pistolCycle function means that it wont try and get an item when it doesn't exist in the list.
I am new to Python and creating a program within Maya, that creates a solar system. This is part of my code that is causing the problems (hopefully enough to understand). The first function defines the radius of the planet, and then creates a sphere accordingly. The second function needs to use the variable planetRadiusStr to determine the radius of the Torus(ring). However, planetRadiusStr is only defined in the first function, so I know I need to somehow pass the variable between functions. However, I cannot seem to get this to work. Can anyone help?
def planetRadius():
planetRadiusStr = raw_input("Please enter the radius of the planet:")
if float(planetRadiusStr)<float(sunRadiusStr):
cmds.polySphere(radius=float(planetRadiusStr), n='planet1')
else:
print "Planet Radius must be less than Sun Radius"
planetRadius()
def planetRings():
ringsStr = raw_input("Would you like this planet to have a ring?").lower()
if str(ringsStr) == "yes":
cmds.polyTorus(r=float(planetRadiusStr)*2, sr=0.5, n='ring1')
cmds.scale(1,0.2,1)
elif str(ringsStr) == "no":
pass
else:
print "Please enter 'yes' or 'no'."
planetRings()
(I can upload a photo of my code if that will be easier to read.)
Thanks!
A couple of things to consider here.
First, I'd get this working using only standard functions and not using raw_input(). Until you have other users you can just type the values you want into the listener; when you do have users you can create a proper GUI that just passes arguments into the functions.
So, I'd suggest you try it by just making functions that take the info you need:
def create_planet(name, radius):
planet, shape = cmds.polySphere(n = name, r = radius)
return planet
def create_sun (radius):
cmds.polySphere(name = "sun", r = radius)
In this case, you don't need to track the planet radius: you can derive it from the history of the planet itself if you know which planet to look at
def create_ring (planet):
planet_history = cmds.listHistory(planet) or []
pSphere = cmds.ls(*planet_history , type = 'polySphere')[0]
planet_radius = cmds.getAttr(pSphere + ".radius")
ring, ring_shape = cmds.polyTorus(r = planet_radius * 2, sr = .5, n = planet + "_ring")
cmds.scale(1,0.2,1)
cmds.parent(ring, planet, r=True)
With all that in place, you can manage the passing of arguments from one function to another manually in the listener:
p = create_planet("saturn", 1)
create_ring(p)
or, you can create another function that does multiple passes:
def add_planet (sun, planet, distance):
cmds.parent(planet, sun, r=True)
cmds.xform(planet, t= (distance, 0 ,0), r=True)
def solar_system ():
sun = create_sun (10)
mercury = create_planet( 'mercury', .5)
add_planet(sun, mercury, 20)
venus = create_planet( 'venus', .7)
add_planet(sun, venus, 40)
earth = create_planet( 'earth', .8)
add_planet(sun, earth, 50)
mars = create_planet( 'mars', .75)
add_planet(sun, mars, 60)
jupiter = create_planet( 'jupiter', 2)
add_planet(sun, jupiter, 70)
saturn = create_planet( 'satun', 1.2)
add_planet(sun, saturn, 80)
create_ring(saturn)
As you can see, as long as you're inside the function solar_system you can keep variables alive and pass them around -- you'll also notice that create_planet() returns the name of the planet created (maya may rename it behind you back, so it's a good idea to check this way) so you can pass that name along to other functions like 'create_ring' or 'add_planet' which need to know about other objrects.
def planetRadius():
planetRadiusStr = 42
#blas
planetRings(planetRadiusStr)
def planetRings(planetRadiusStr):
#blas
def planetRadius():
size = 4
return size
def planetRings(inputSize):
"function placed here"
print('my planet size was ' + str(inputSize))
var01 = planetRadius()
planetRings(var01)
#result : 'my planet size was 4'
If you are planning to create a UI, keep in mind that you should set your def as this :
def planetRadius(*args):
Indeed, maya UI output a default boolean variable and will create an error if you don't put *args.
Furthermore, if you try to pass a variable through a UI as yours:
def planetRings(inputSize, *args):
"function placed here"
print('my planet size was ' + str(inputSize))
You will have to look for the module functools.partial to specify the input size :
from functools import partial
import maya.cmds as cmds
cmds.button(l='exec', c=partial(planetRings, inputSize))
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'])