+ 1
Doubt in functions lesson in python
In this slide they are saying that we have to assign a variable before using them ,but in the previous slide they didn't assign the variable before itself but we got the output how?? Little bit confused 😕 kindly any one clear me .it would be great and helpful for me if any one clears me please
9 ответов
+ 3
S. V. Shivaani You can declare a variable inside the function.
def display():
x = "Text"
return x
print(display())
>> Text
# Although here, the value of x will be always "Text" or constant so it depends on your program.
- - - - - - - - - - - - -
# If you want the text to be dependent on the input.Then this:
inpt = input()
def display(text):
print(text)
display(inpt)
# So here, the input was taken from the user and then passed it to the function "display" then prints it inside the function. Note that we passed the value of "inpt" to the variable/parameter "text" inside function then prints it. Try it in code playground and experiment.
Hope this helps.☺
+ 4
def add(x, y):
print(x + y)
add(2, 3)
>> 5
- - - - - - - - - - - -
def add():
print(20 + 10)
>> 30
- - - - - - - - - - - -
Parameters are optional, you can create functions without variables (parameters).
In the First code at the top, the x and y are the PARAMETERS and the 2 and 3 are the ARGUMENT.
ARGUMENT are the values that are passed into functions as PARAMETER. When you call the function with argument, the value of the paramater x and y will now be 2 and 3 respectively.
While on the Second code, we just called the function and print the sum of two numbers 10 and 20
+ 2
My doubt is. Is it compulsory to define a variable before using it in function?
+ 2
Anyways thanks a lotttt 《 Nicko12 》 thank you
+ 2
Understood 《 Nicko12 》 🙏
+ 1
If you're not specific you should mess around with code and clear the doubt yourself.
variable1 = "Hello"
print(variable1)
print(variable2)
# output
Hello
ERROR variable2 was never assigned a value
+ 1
Oh I always forgot to mention the language
+ 1
《 Nicko12 》 in python functions lesson
+ 1
《 Nicko12 》 in functions and modules topic, functions second slide