Placing a Python variable inline - python

Forgive this rather basic Python question, but I literally have very little Python experience. I'm create a basic Python script for use with Kodi:
http://kodi.wiki/view/List_of_built-in_functions
Example code:
import kodi
variable = "The value to use in PlayMedia"
kodi.executebuiltin("PlayMedia(variable)")
kodi.executebuiltin("PlayerControl(RepeatAll)")
Rather than directly providing a string value for the function PlayMedia, I want to pass a variable as the value instead. The idea is another process may modify the variable value with sed so it can't be static.
Really simple, but can someone point me in the right direction?

It's simple case of string formatting.
template = "{}({})"
functionName = "function" # e.g. input from user
arg = "arg" # e.g. input from user
formatted = template.format(functionName, arg)
assert formatted == "function(arg)"
kodi.executebuiltin(formatted)

OK as far as I get your problem you need to define a variable whose value could be changed later, so the first part is easier, defining a variable in python is as simple as new_song = "tiffny_avlord_I_love_u", similarly you can define another string as new_video = "Bohemia_on_my_feet", the thing to keep in mind is that while defining variables as strings, you need to encapsulate all the string inside the double quotes "..." (However, single quotes also work fine)
Now the issue is how to update it's value , the easiest way is to take input from the user itself which can be done using raw_input() as :
new_song = raw_input("Please enter name of a valid song: ")
print "The new song is : "+new_song
Now whatever the user enters on the console would be stored in the variable new_song and you could use this variable and pass it to any function as
some_function(new_song)
Try executing this line and you will understand how it works.

Related

How do I pass an object instead of a string via pythons' input() function?

I am working on a machine learning modelling problem where an object is created to store training and validation data, but the validation set if optional and if not included when creating the object the default value is None.
If we find out later on though the user wants to add a validation pandas dataframe we were hoping to let them supply the name of the dataframe with input(). With a function defined right in the notebook we're running we can then do an eval(<input>) to turn the string into the object we need. If we define the object outside of our notebook though it seems like the scope doesn't include that variable.
I realize this probably isn't the best way to do this, so what is a more pythonic way to let a user supply a dataframe by name after an object as already been instantiated? We can pass the objects fine as arguments to functions. Is there a way to pass an object like that but with input() or some other user-friendly way to prompt the user?
It maybe possible to use locals() or globals() as a dict for grabbing an initialized variable by it's name.
the_variable = {'key_one': 'val_one'}
selected_input = input("Please input a variable name")
selected_var = locals()[selected_input]
print("selected_var continence -> {0}".format(selected_var))
Should output, well assuming the_variable was passed to input()
selected_var continence -> {'key_one': 'val_one'}
This is an adaptation of an answer to Calling a function of a module by using it's name a string, but seems to work in this instance too.
Update
I can't remember where I picked up the following perversion (I did look about though), and I'm not suggesting it's use in production. But...
questionable_response = lambda message: input("{message}: ".format(message = message))
this_response = json.loads(questionable_response("Input some JSON please"))
# <- '{"Bill": {"person": true}, "Ted": {"person": "Who is asking?"}}'
... does allow for object like inputting.
And getting data from an inputted json string could look like...
this_response['Bill']
# -> {u'person': True}
this_response['Ted'].get('person')
# -> u'Who is asking?'
... however, you'll likely see some issues with using above with other scripted components.
For the Unicode conversion there's some pre-posted answers on the subject. And checking help(json.loads) exposes that there's toggles for parse_ing floats, ints, and constants.
Even with that it may not be worth it, because there's still some oddities you'll run into if trying to implement this funkiness.
Just to list a few;
conjunctions are a no go; let's say ya get a clever Clara who inputs something like '{"Clara": {"person": "I'll not be labelled!"}}'. That would cause an error unless ' was escaped, eg. \'
the above is also quote fragile; perhaps someone at the keyboard hasn't had enough to drink and tries "{'Jain': {'person': True}}". That would first barf on quotes, then heave from True not being true
So like I prefaced at the start of this update, I'll not recommend this in production; could waist a lot of time chasing edge-cases. I only share it because maybe you've not found any other option for getting from input to something that can be interrogated like an object.

Python: Using string stored in variable to create attribute to class

I am trying to follow syntax of the pyparticleio.ParticleCloud package. Using the following command, my code works correctly "particle_cloud.boron1.led('on')" (hardcoded values)
I want to pass portions of the command, "boron1" and "on" as variable. I'm trying to figure out how to use those variables to act in the same way as if i'd hardcoded the values.
My python level is very beginner.
command_list['boron1','on']
device = command_list[0]
function_1 = command_list[1]
access_token = "ak3bidl3xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
particle_cloud = ParticleCloud(username_or_access_token=access_token)
#particle_cloud.boron1.led('on') #hardcoded example that works
particle_cloud.device.led(function_1) #what i would like to work
If you set device to the actual object, you can call methods on the object. Example:
device = particle_cloud.boron1 # Or whatever you like
arg = 'on' # Also make this whatever you like
device.led(arg) # Same as: particle_cloud.boron1.led('on')
Python has a built in function called exec
It allows you to take a string, and have Python execute it as code.
A basic example based on the code you provided would look like this:
command_list['boron1','on']
device = command_list[0]
function_1 = command_list[1]
exec('particle_cloud.' + device + '.led("' + function_1 + '")')
This is a bit ugly, but there are different ways to compose strings in Python such as using join or format so depending on your real code you may be able to build something nice.
Just be careful not to pass raw user input to exec!
I can cause all kinds of trouble from errors to security issues.
I believe you could use getattr() (in Python3: https://docs.python.org/3/library/functions.html#getattr ) :
pcdevice = getattr(particle_cloud, device)
pcdevice.led(function_1)
(BTW, I woudln't name the string 'on' with the label 'function_1' as the variable name implies that this option is a function when it is a string. Also, the above may now work depending on the properties of your library object ParticleCloud.)

python: call a function with parameter from input

I have a list of tuples consisting of name, phone number and address, and a function called "all" which just shows a list of all the tuples (like in a phonebook). The function is called via input from a user.
I want another function, called "entry" which shows a specific entry of my list. This function should be called via input as well with the index number of the entry (for example, "entry 12") and show just this entry.
Although I can't figure out how to take the number from the input as a parameter for my function and how to call the function. Does it have to contain a variable in the function name which will later be replaced by the number? How can i do that?
Have you looked into argparse?
import argparse
parser = argparse.ArgumentParser(description='your description')
parser.add_argument('-entry', dest="entry")
args = parser.parse_args()
print (args.entry)
You can then call this with python yourfile.py -entry="this is the entry"
That will allow you to take an input when you run the file.
I'm sorry if misunderstood your question, but it seems like you need function arguments. For example: if your `entry' program just prints out what the user put in, your code would look like this:
def entry(user_input): # the variable in the parentheses is your argument--is a local variable ONLY used in the function
print user_input # prints the variable
# now to call the function--use a variable or input() as the function argument
entry(input("Please input the entry number\n >>> ") # see how the return from the input() function call is used as a variable? this basically uses what the user types in as a function argument.
Try running it, and you'll see how it works.
Best of luck and happy coding!

Understanding python code?

I need some help understanding the start of this code:
def get_int_input(prompt=''):
I know what the int_input does but i need some help understanding the other parts of the line to finish my code.
I am assuming that by "other parts", you mean prompt=''.
prompt is a named parameter. Named parameters are given a default value whenever its function is called without passing a value to that parameter. Otherwise, it will use the value that was passed.
If you do:
>>> get_int_prompt()
Then the value of prompt (inside the function) would be an empty string ('').
However, if you do:
>>> get_int_prompt('What is your age? ')
Then the value of prompt (inside the function) would be 'What is your age? '.
Source: Python Central

How can I make 'uName' display the correct name that the user inputs after clarifying checks?

I am very new to Python, as you can probably tell from the code. To begin, I am trying to have the user input their name and store that in a global variable that I can access all throughout my code...preferably named uName.
What's happening is during the loop cycle, it asks the user 'Is this your name?' after they input the first response. If I hit type anything but 'yes' or 'Yes', it will re-ask them to input the name. BUT, when they finally hit 'Yes', the program prints the very first name they entered.
Also, any tips on code structure or wording is helpful...
game.py
from decisions import *
import decisions
global globalname
globalname = ''
def gameEngine(uName):
looper = 0
while looper == 0:
print ('You said your name is, ') + uName + ('...')
clarifier = raw_input('Is that correct?\n')
if clarifier == 'yes' or clarifier == 'Yes':
namePrinter(answer)
else:
decisions.userDecisions(username)
def namePrinter(uName):
print uName
gameEngine(answer)
decisions.py
username = ''
def userDecisions(inputs):
response = raw_input("Please enter your name...\n>>> ")
return response
answer = userDecisions(username)
The specific issue that you are encountering is that you are first running the contents of decisions.py though the import statement in game.py. Through that, you have set the variable "answer" to be equal to the first name that the user inputs.
Then you are calling the gameEngine function in game.py, supplying the "answer" variable from decisions.py as the argument, which is stored in "uName". Upon the user entering another name the name is not stored anywhere and is thrown out with the following line.
decisions.userDecisions(username)
You can assign the return of that statement to a variable such as "uName", and that will get you closer to what you want to do.
uName = decisions.userDecisions(username)
The next issue is that when you are printing out the name, you are printing out the variable "answer" as opposed to "uName". This is what is mainly causing the issue of the first name always being printed out.
namePrinter(answer)
This could be resolved by passing in the "uName" variable instead.
namePrinter(uName)
Also if you want the final chosen name to be stored in the global variable you can assign the final user chosen name to the gloabl variable after the user confirms that the nameis correct.
globalname = uName
However, you may want to be careful about a few parts of the structure of your code.
First, you may want to try not to use global variables. Instead you should be passing around the name though the functions which use it. If you have other player information that you need to access often, you can create a Player class and object to store that information in a single object which can be passed around into functions as needed.
Second, as the userDecisions function does not use its arguement "inputs", you can remove that arguement, as it isn't used.
Third, you may want to be careful about running code through import statements alone. Generally when you are importing a source file, you should be importing the functions, and not rely upon imports to directly run code. For example you can remove the non-function lines of decisions.py and simply run the following in game.py instead.
gameEngine(decisions.userDecisions())
I reccomend that you look up some resources on functions and passing arguement in Python, as they might be able to explain the underlying concepts a bit better.
You have screwed up with the variables and their scope. Read more about them here.
To give you a perspective regarding the scope of variables concisely, look at this code snippet:
# This is a global variable
a = 0
if a == 0:
# This is still a global variable
b = 1
def my_function(c):
# this is a local variable
d = 3
print(c)
print(d)
# Now we call the function, passing the value 7 as the first and only parameter
my_function(7)
# a and b still exist
print(a)
print(b)
# c and d don't exist anymore -- these statements will give us name errors!
print(c)
print(d)
Regarding your code, you may want to have a look at these issues:
The answer variable is not accessible in the game.py module.
So is the case with username variable in the decisions.userDecisions(username) call.
The decisions.userDecisions(username) call in the gameEngine(uName) method is not storing the response to any variable and hence the response will be lost.
You are declaring global variable globalname but not assigning any value to it (of course other than '').
P.S.: I was tempted to do your homework for you, but then probably this is good enough information for you to learn more. ;)

Categories

Resources