Understanding python code? - python

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

Related

write a function that takes 2 string arguments

I'm a total beginner so please skip this one if you are offended by how simple it is.
I can't figure out how to write a function which takes two arguments (name and course) and prints : Welcome "name" to the "course" bootcamp.
def greeting('name', 'course'):
print (welcome,'name', to, the, 'course')
I want to be able to print Welcome Stacie to the python bootcamp!
Pls try something like below.
def greeting(name, course):
print ('welcome' + name + 'to' + 'the' + course)
greeting('Stacie', 'python')
if you still getting any error pls share screenshot of error.
The function arguments you declare need to be variables, not actual values.
def greeting(name, course):
print ('welcome', name, 'to the', course)
Notice how you had the quoting diametrically wrong. The single quotes go around pieces of human-readable text and the stuff without quotes around it needs to be a valid Python symbol or expression.
If you want to supply a default value, you can do that.
def greeting(name='John', course='Python 101 course'):
print ('welcome', name, 'to the', course)
Calling greeting() will produce
welcome John to the Python 101 course
and of course calling it with arguments like
greeting('Slartibartfast', 'Pan Galactic Gargle Blaster course')
will fill the variables with the values you passed as arguments:
welcome Slartibartfast to the Pan Galactic Gargle Blaster course
def greeting(name, course):
print (f"Welcome {name} to the {course}")
greeting("Jhon", "Python for Beginners")
# > Welcome Jhon to the Python for Beginners
The function takes two variables, the variables are not strings, so they won't have quote marks. In the print statement, f"<text>" is used in this case to print variables in the string with the help of {}. So when you type in the string {name} it will take the name from the variable itself.

Why does a function execute when put inside a variable (and how to stop it)

While writing a program in python i noticed that if one puts a function like print("hello world") inside a variable it will not be stored like expected, instead it will run. Also when i go and call the variable later in the program it will do nothing. can anyone tell me why this is and how to fix it?
If mean something like:
variable = print("hello world")`
then calling the function is the expected result. This syntax means to call the print function and assign the returned value to the variable. It's analogous to:
variable = input("Enter a name")
You're surely not surprised that this calls the input() function and assigns the string that the user entered to the variable.
If you want to store a function, you can use a lambda:
variable = lambda: print("hello world")
Then you can later do:
variable()
and it will print the message

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!

Placing a Python variable inline

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.

Optional argument in python

I have a python program that I am trying to add an optional argument to.
If the user doesn't enter anything then I want that value to default to 20. But, if they do enter a value, I will use their value. I wrote that into the program like so:
optionParse= argparse.ArgumentParser(description='Change Number of Locations')
optionParse.add_argument('-n', dest='userDefSize')
args=optionParse.parse_args()
if args.n:
sizeOfList=args.userDefSize
else:
sizeOfList=20
But for some reason it keeps saying:
AttributeError: 'Namespace' object has no attribute 'n'
What would be the issue here? Is my if statement written incorrectly?
To answer your first question, add_argument takes a parameter 'default' which will do what you want. See the documentation
optionParse.add_argument('-n', dest='userDefSize', default=20)
To answer your second question, the 'dest' parameter redefines where the value passed in is stored in the arg namespace. In this case you told argparse to store the value in args.userDefSize instead of args.n, so args.n doesn't exist.

Categories

Resources