29th Oct 2023, 10:16 PM
RocketLover
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")
29th Oct 2023, 10:40 PM
Niels F 🇩🇪 <html challenger>
Niels F 🇩🇪 <html challenger> - avatar
+ 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)
29th Oct 2023, 11:43 PM
Mafdi
Mafdi - avatar
+ 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
30th Oct 2023, 4:41 AM
Mafdi
Mafdi - avatar
+ 1
Okay thank you
31st Oct 2023, 11:14 PM
RocketLover
0
I’ve put a comment in your code.
30th Oct 2023, 1:38 AM
Annihilate
Annihilate - avatar
0
I dont understand it myself
31st Oct 2023, 10:47 AM
Samuel Bulus
Samuel Bulus - avatar