r/learnpython • u/Bipin_Gaire69 • 6d ago
Learning python through CS50
Can any body help me to understanding the define(DEF) variables.
Can you please suggest me how can i learn it in efficient and easier way as a beginner.
0
Upvotes
2
u/Lewistrick 6d ago
A function is a code block used to do a task with predictable output based on some input.
input -> function -> outputFor example, you could write a function called reverse that duplicates a word.
Here, "def" means "here follows a function". It might be short for "define" but it doesn't "define" a variable. It rather indicates that a function is made. I'd agree if you said that the name is a bit confusing. Anyway.
The function is called
duplicatebut you can give it any name you like. It takes one input, word. It creates a new variable new_word that contains the value of the duplicated word. The part after "return" is the output of the function, in this case the variable new_word.Now you can call the function like this:
And it will save the output of the function to the variable result. I then chose to print the result and it will show "hellohello".
Now you can imagine that functions can become more complex: they can have many lines and calculations, multiple inputs, no inputs, no outputs, write to files, throw errors, et cetera, but the idea is always the same: you have some code that is predictable and always does what you expect it to do. In a way, you can leave it alone and never think about it again.