r/learnpython • u/Bipin_Gaire69 • 29d 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
5
u/InfamousClyde 29d ago
Is there something you find particularly confusing in the CS50 courseware about the topic of "functions"?
4
u/Rudeus_Kino 29d ago
Erm. "def" declaring a function in python
3
u/Classic-Pomelo-5573 29d ago
Think of
defas writing a saved recipe, while a normal variable is just an item in your fridge.When you write a normal variable:
name = "Alice"You are just putting one piece of data into a box.When you use
def, you are naming a set of actions so you do not have to type them over and over:That code does not do anything immediately when Python reads it. It just saves the recipe in memory.
It only executes when you call its name with parentheses:
message = make_greeting("Alice")The word in parentheses (
name) is the ingredient you hand it, andreturnis the finished result it hands back to you.2
u/Lewistrick 29d 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.
0
u/[deleted] 29d ago
[deleted] — view deleted comment