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.
Related
Let me just start off by saying that I'm very new to programming, I'm pretty sure this is like my fourth time sitting down and learning stuff, so well, I'm not even sure the question sounds right.
So I watch beginner tutorials for Python by CS Dojo on YouTube, I'm on the third video, it's about functions. Watching tutorials I pause the video a lot and try to experiment a little bit to truly understand what I'm working with. So it went all good when I would play around with numbers. Like here:
def function(x):
return x+5
a = function(10)
print(a)
(Not sure if I pasted the code well, sorry)
But then I tried to do something with words to see if it could work:
def function(name):
return ("Hi ")
b = function(Oskar)
print(b)
And it doesn't, I get an error like this:
NameError: name 'Oskar' is not defined
Do these kind of codes only work with numbers? Or did I do something wrong? I wanna understand this so I'd like someone to explain it to me, considering that I'm a beginner and don't understand a lot of the words programmists use here.
Oskar is a variable. 'Oskar' and "Oskar" are strings (note the quotes).
In other words, any of the following will work:
b = function('Oskar')
b = function("Oskar")
my_name = 'Oskar'
b = function(my_name)
my_name = input('What is your name? ')
b = function(my_name)
(Along with an infinite number of other examples, of course.)
name = "oskar"
def function(name):
return ("Hi " + name)
b = function(name)
print(b)
Oskar is not a string, but undefined variable.
Oskar without quote is treated as an identifier not a string. Use "Oskar" or 'Oskar'
String always have to be encapsulated in a double("") or a single('') quote
def function(name):
return ("Hi " + name)
b = function("Oskar")
print(b)
Or use this one, in future it will come in real handy
def function(name):
return (f"Hi {name}")
b = function("Oskar")
print(b)
When you type Osakar python interpreter expects a variable which is not defined in your case.
Please note that Oskar is different from 'Oscar'. The first is a variable (that must be defined first). While the latter is a string.
Even if you use sting 'Oscar' you cannot use it with your function. Because the + does not work between a string and an integer.
I was to print the contents of a variable, despite the fact that the variable exists inside a def. This is what my code looks like:
def count_words():
var_one = "hello world"
print count_words.var_one
The above does not work. I get the following error:
AttributeError: 'function' object has no attribute 'hello'
How do I get around this?
You need to return something:
def count_words():
var_one = "hello world"
return var_one
print(count_words())
Now the print statement is calling a function and printing what value is returned.
If you want to print he contents of a variable, you need to make sure the variable exits and you can access. According to your code piece, you cant do what you want because both of the conditions are not satisfied. The code written in a file and the code after executing aren't the same concepts. The code written in a file is like a cookbook, and when the computer executes the code, it is as the cook is cooking something according to the cookbook. You cant tough the ingredient(print the variable) without the cook is cooking(the variable doesn't exit in the running environment, only exits in the file). And you cant tough the ingredient if the cook doesn't allow you to tough it(you don't have the accessibility to print the variable). A function is like a recipe, it tells you how to do some cooking, but it only remains in the paper(file) until you do the cooking following the recipe. Then you can print the variable according to answer
Nick's answer is probably what you want. As a side note, you might want to use a class and access its attribute as so:
class CountWords():
var_one = "hello world" # this is the attribute
count_words = CountWords() # instantiate the class
print(count_words.var_one) # access the class' attribute
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
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.
I want a function that can return the variable/object name as str like this :
def get_variable_name (input_variable):
## some codes
>>get_variable_name(a)
'a'
>>get_variable_name(mylist)
'mylist'
it looks like silly but i need the function to construct expression regarding to the variable for later on 'exec()'. Can someone help on how to write the 'get_variable_name' ?
I've seen a few variants on this kind of question several times on SO now. The answer is don't. Learn to use a dict anytime you need association between names and objects. You will thank yourself for this later.
In answer to the question "How can my code discover the name of an object?", here's a quote from Fredrik Lundh (on comp.lang.python):
The same way as you get the name of that cat you found on your porch:
the cat (object) itself cannot tell you its name, and it doesn’t
really care — so the only way to find out what it’s called is to ask
all your neighbours (namespaces) if it’s their cat (object)…
….and don’t be surprised if you’ll find that it’s known by many names,
or no name at all!
Note: It is technically possible to get a list of the names which are bound to an object, at least in CPython implementation. If you're interested to see that demonstrated, see the usage of the inspect module shown in my answer here:
Can an object inspect the name of the variable it's been assigned to?
This technique should only be used in some crazy debugging session, don't use anything like this in your design.
In general it is not possible. When you pass something to a function, you are passing the object, not the name. The same object can have many names or no names. What is the function supposed to do if you call get_variable_name(37)? You should think about why you want to do this, and try to find another way to accomplish your real task.
Edit: If you want get_variable_name(37) to return 37, then if you do a=37 and then do get_variable_name(a), that will also return 37. Once inside the function, it has no way of knowing what the object's "name" was outside.
def getvariablename(vara):
for k in globals():
if globals()[k] == vara:
return k
return str(vara)
may work in some instance ...but very subject to breakage... and I would basically never use it in any kind of production code...
basically I cant think of any good reason to do this ... and about a million not to
Here's a good start, depending on the Python version and runtime you might have to tweak a little. Put a break point and spend sometime to understand the structure of inspect.currentframe()
import inspect
def vprint(v):
v_name = inspect.currentframe().f_back.f_code.co_names[3]
print(f"{v_name} ==> {v}")
if __name__ == '__main__':
x = 15
vprint(x)
will produce
x ==> 15
if you just want to return the name of a variable selected based on user input... so they can keep track of their input, add a variable name in the code as they make selections in addition to the values generated from their selections. for example:
temp = raw_input('Do you want a hot drink? Type yes or no. ')
size = raw_input('Do you want a large drink? Type yes or no. ')
if temp and size == 'yes':
drink = HL
name = 'Large cafe au lait'
if temp and size != 'yes':
drink = CS
name = 'Small ice coffee'
print 'You ordered a ', name, '.'
MJ
If your statement to be used in exec() is something like this
a = ["ddd","dfd","444"]
then do something like this
exec('b = a = ["ddd","dfd","444"]')
now you can use 'b' in your code to get a handle on 'a'.
Perhaps you can use traceback.extract_stack() to get the call stack, then extract the variable name(s) from the entry?
def getVarName(a):
stack = extract_stack()
print(stack.pop(-2)[3])
bob = 5
getVarName(bob);
Output:
getVarName(bob)