0
Using Def
Can anyone tell me how to use def function in Python??
4 ответов
+ 3
Saksham Guragain ,
> functions in python and their use are described in the last module (`functions`) of the course `introduction to python`.
> since you allready have started learning from this tutorial, just continue until you have finished it.
+ 2
Hi! Once you've written a solution (as in the example of calculating the body mass index) and wrapped the calculation code in a function, you can call that function with a single line, simply passing in new values.
Code written as a function is convenient to use in a large program in different parts of it, which simplifies the program itself and reduces the number of lines of code. For example, think about the console output function /print()/. You don't need to write it every time in your program to output something to the console. You simply call this function by its name, and everything else happens "under the hood." This code functionality was once written by a programmer and saved as a function, and it is also integrated into the Python programming environment.
Please, check out my example:
https://sololearn.com/compiler-playground/cm8ZPU450nAE/?ref=app
https://sololearn.com/compiler-playground/cPP9jwAvj7Mr/?ref=app
0
[Part 1]
I think this is a tough question to answer in a Q&A section. And in my opinion, if you're a beginner, you should have some basic Python knowledge before you dive into the topic of functions.
What a function does really depends on what you want it to do. The basic syntax for a function in Python is:
code
Python
download
content_copy
expand_less
def function_name(parameters):
# code to be executed
return value # (optional)
Here’s an example of a small and simple function:
code
Python
download
content_copy
expand_less
def greet(name):
return f"Hello, {name}!"
print(greet("Ferdous")) # Output: Hello, Ferdous!
Here, the value of the parameter isn't fixed. I can use whatever value I want. For example:
code
Python
download
content_copy
expand_less
print(greet("Alice")) # Output: Hello, Alice!
print(greet("Bob")) # Output: Hello, Bob!
0
[Part 2]
Now, you might be thinking, "Why go through all this trouble?" We could just do it this way:
code
Python
download
content_copy
expand_less
name = input()
print("Hello, " + name + "!")
When I was first learning Python functions, I had the same question in my mind. But as I learned more about functions and saw bigger codebases, I started to understand their importance.
I'd say that instead of learning from us in a Q&A box, you should check out the Functional Programming section here:
https://www.sololearn.com/learn/courses/python-intermediate