+ 1
Why not work
7 Réponses
+ 6
RocketLover
That's your code:
def exclamation(word):
ex=word + "!"
exclamation("spam")
print(ex)
With print(ex) you are refering to the local variable ex.
Variables that are declared in a function are local variables that can only be used in the function.
Instead you can use this code:
def exclamation(word):
return word + "!"
ex = exclamation("spam")
print(ex)
or even shorter:
def exclamation(word):
return word + "!"
print(exclamation("spam"))
or you can put the print statement in the function like here:
def exclamation(word):
print(word + "!")
exclamation("spam")
+ 3
Also another solution but I don't recommend it.
You can make a global variable inside a function with the global keyword.
def exclamation(word):
global ex
ex=word + "!"
exclamation("spam")
print(ex)
+ 3
Niels F 🇩🇪 <html challenger>
Why "does not work"? Does it show an error?
I think both cases are the same, anyway you will have a global variable.
"Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)"
https://www.w3schools.com/python/python_variables_global.asp#:~:text=the%20global%20keyword.-,Example,x%20%3D%20%22fantastic%22%0A%0Amyfunc()%0A%0Aprint(%22Python%20is%20%22%20%2B%20x),-Try%20it%20Yourself
+ 1
Okay thank you
0
I’ve put a comment in your code.
0
I dont understand it myself