Python Functions || Python Tutorial || Learn Python Programming

Python Functions  ||  Python Tutorial  ||  Learn Python Programming

When programming, you will often encounter
calculations and logical operations you need to perform repeatedly. One way to handle this
is to write the same code over, and over, and over, and over, and — … — over…
A better solution is to write a function. Functions enable you to reuse logic an infinite
number of times without repeating yourself. This is especially helpful to avoid moments
of deja vu. A better solution is to write a function. Functions enable you to reuse
logic an infinite number of times without repeating yourself. This is especially helpful
to avoid moments of deja vu… Time to begin… Before we write a function
of our own, call the directory function to see what objects are available to us… When you first start the Python interpreter,
you will see a list of 4 standard attributes. Once you define a function, it will appear
in the directory. To define a function, you write “d-e-f”
followed by the name of the function. We will call this function F. Next, you write parentheses.
Inside the parentheses you list the inputs to the function. Another name for “inputs”
is “arguments”. This function has zero arguments. Next, type a “colon” and press
return. The colon is how you start a new code block in Python. For our first function we will keep things
simple. We will pass. The word “pass” is how you tell Python to skip this line and
do nothing. Notice that we indented the code inside the function. In Python, you group
code by indentation. There. We have created our first function.
It is short. It is simple. But does it work? To call the function, type the name and parentheses…
The function F did nothing, just like we told it to. By the way, look what happens if you forget
to type parentheses. Without parentheses, Python displays that
F is a function, and gives the memory address. Interesting, but not very helpful. You need
to include parentheses to actually call the function. If you call the directory function again,
you will see that F is now listed. Now we will write a function that actually
does something. We start with d-e-f. We will name this function
ping. Next, list the arguments inside parentheses. This function will have zero arguments. Finally,
type colon and press enter. Functions in Python can return values. To
return a value, type the word “return” and then the object. This function will return
the string “Ping”. To show our enthusiasm, we will type an exclamation point. Return
values are optional; you are under no obligation to return something. Now call the function. This function returns the string ‘Ping’.
Since we did not assign this to a variable, Python printed it to the terminal. But we
can also store the return value to a variable. To see that this worked, print the value X. Call the directory function again and you
will see the function Ping, and the variable X listed.
For our next example, recall the the volume of a sphere is:
V=4/3 π r3, where R is the radius of the sphere. We will write a function which will return
the volume of a sphere when given the radius. To do this, we will need to use the number
Pi. This is available in Python, but first you must import the math module. If you display
the directory of the math module, you will see Pi listed. You can now access the number pi. We are ready to define the volume function.
Type ‘def’ then the name of the function. We will call this function ‘volume’. This
function will have a single argument: the radius R… Next, we will write a brief comment
describing this function. This is called a “docstring” and provides documentation
on what the function does and how to use it. Next, we compute the volume.
Notice that we used decimals for the fraction 4/3. This is because in Python 2, if you divide
one integer by another, it returns the quotient, not the exact value. Also, notice that you
use a double asterisk for exponents. Finally, return the volume. Let’s test this function. Compute the volume
of a sphere with radius 2. It works… Because we used an argument when defining
the function, you must provide an input when calling it — R is a required argument. Look
what happens if you call ‘volume’ without an argument — you get an error and a reminder
to use an argument. We can use the help function to see how to
use the volume function… Very helpful… We have created functions with no arguments
and with one argument. We will now throw caution into the vacuum of space and write a function
with two arguments. Our function will compute the area of a triangle. Recall that the area
of a triangle is ½ base x height. Our previous function was named “volume”,
which was somewhat vague. The name does not tell you what shape is being considered. This
time, we will be more explicit and name the function “triangle area”. To compute the
area, we need two arguments: the base B and the height H. Write a docstring giving a brief
description of this function… And finally, return the area of the triangle. We are ready to test the function. The area
of a triangle with base 3 and height 6 is … 9. This is correct. There is no limit to how many arguments you
can use in your function, but if the number of inputs is too large, you will alienate
others and receive accusing glares… Functions in Python can accept another kind
of argument called “keyword arguments”. To show how to use these kinds of arguments,
we will write a function which converts a person’s height from American Units (feet and inches) to centimeters. Recall that 1 inch equals 2.54 cm, and 1 foot
equals 12 inches. Call this function cm, for centimeter.
This function will accept two arguments: feet and inches.
Notice that these arguments have equal signs after them.
It looks as if we are assigning values to these arguments.
In fact, we are. We are assigning a default value of 0 to each argument. For this reason,
Python also calls keyword arguments “default arguments”… Next, write a docstring describing
the function. Notice that it is customary to use triple-quotes for a docstring.
Now for the actual code. We first convert inches to centimeters… Then we convert feet to centimeters… And we return the combined value. We could have combined these all on one line,
but it is better to write clean code which is easy to read, as opposed to compact code
which impresses no one. Here is how you call a function with keyword
arguments. First we convert 5 feet to centimeters… Next we convert 70 inches to centimeters… And lastly, convert 5 feet 8 inches to centimeters… We can also perform this last calculation
by specifying inches first… Keyword arguments help you to write flexible
functions and clean code. There are 2 kinds of arguments you can use
when writing a function. A keyword argument, which has an equal sign, and a required argument
which does not have an equal sign. When writing a function, you can use both kinds of arguments.
But if you do this, the keyword arguments must come last. For example, if you define a function G with
a keyword argument first, you get a Syntax Error. Notice that Python calls these “default
arguments”. This is another name for a keyword argument. To fix this, you have to list the non-default
arguments first. These are also called required arguments since they are required. To call this function, you must pass in a
value for the required argument Y. The keyword argument X is optional. If you do not provide
a value for X, the default value is used. If you want to pass in a value for the keyword
argument, then you must specify it by its name. Required arguments are not given a name.
They are determined by their position. Functions in Python are flexible contraptions.
Required arguments, keyword arguments, docstrings, return values — together they empower you
to write some amazing, reusable code. And if your function does not require an input,
you will not get an argument from me…

100 thoughts on “Python Functions || Python Tutorial || Learn Python Programming”

  1. Great video, but the variables that you use when declaring a function are called parameters. Arguments are the values you put in a function when you're actually calling it

  2. when I run this it does nothing, WTF am i missing
    import math
    def volume(r):
    v = (4.0/3.0)*math.pi*r**3
    return v

  3. Define function make_doctor() that takes a parameter name
    get user input for variable full_name
    call the function using full_name as argument
    print the return value
    can you .plzz give me the solution for this….either in the comments or to my email [email protected]

  4. I am using Windows10 and I have write some codes to scrape information from a website but I can't copy anything from my command prompt or anaconda prompt. I figure it out that my mouse dosen't working on both command prompt. Can anybody help me?

  5. Keyword arguments are not necessarily default arguments in python 3.
    Consider this function signature:
    def cm(*, feet, inches):
    # Body.

  6. I wish I discovered these videos when I started my PhD! Luckily they're well-done enough I might watch them to understand Python better generally and to not forget what I've learnt.

  7. Sheikh Muazzin Azeem

    initially i thought this would be corny and weird but i hate to admit that it actually grew on me. still quite weird though.

  8. i'm getting "IndentetionError: Expected and indented block".
    I'm using Pyhon 3.6 (32 bit).
    Could the version be the problem?

  9. I use Vim text editor and tried to make a (I guess program, I'm new to this) which would tell you how much of each digit it has. I basicly built it on rounding down, but I can't use floor or ceil function. Where's the problem?

  10. For those that get errors make sure when after you typed pass, you press enter twice. So you have:
    def f():
    … pass

    >>> f()
    don't call your function after the … under pass. Press enter again to make sure you have >>>
    It might seem obvious but its easy to overlook.

  11. "it is better to right clean code than compact code, which impresses NO ONE" couldn't agree more! It really sucks how some coding tutorial forum users show really compact codes to beginners like they're suppose to understand that crap.

  12. Hey I know it's been quite a while since this video was posted, but I have a question. With the volume function, if I use 4/3 instead of 4.0/3.0 I get a different volume. Can anybody explain why this happens?

  13. You don't explicitly have to specify a keyword argument by it's name, if you position the arguments in order:
    def g(x, y = 0, z = 1):
    print(y + x + z)
    g(1) # will print 2
    g(3, 5) # will print 9
    g(2, 2, 2) # will print 6

  14. import math #Why do we need this?

    def get_values_return_ave(all_values):

    print("Type in values one-by-one, press enter to finish.")


    val=input("Enter value #"+str(i)+': ')

    while val!='': #this is a sentinal loop to get the values





    val=input("Enter value #"+str(i)+': ')

    if i>0: return theSum/i

    return None

    def std_deviation(values,ave):

    """Function returns the standard deviation of a list of numbers"""



    for val in values:


    n=len(values) #number of items in values list


    return std_dev #this function does nothing useful, yet.

    def median(values):

    """Function returns the median of a list of numbers"""




    if n%2==1:

    return values[middle]


    return (values[middle-1] + values[middle])/2

    if __name__=="__main__": #conditional execution


    ave=get_values_return_ave(the_values) #FIRST: find errors in average

    if ave!=None:

    s=std_deviation(the_values,ave) #SECOND: get Standard Deviation to work

    med=median(the_values) #THIRD: get median to work.

    outputStr="{0:<10s}= {1:<3.2f}"#format string, 's'-string,'f'-floating point




    print(outputStr.format("tStd. Dev.",s))



    is there any way of this code simple and shot than this? because this one is just too much for me

  15. "We will now throw caution into the vacuum of space, and write a function with TWO arguments." Awesome.

  16. As shown by Socratica, all learning will be presented in this very form on the human species' achievement of Level 1 on the Kardishev scale. However, … It is clear that Socratica's careful, concise lectures come from an even further future we all must strive for: through diligence in our training, precise naming conventions, and doc strings enveloped with triple quotes for every function.

  17. San Diego Uber Driver

    Honestly. This is my favorite way to learn python. I can't tell if the commentator is a real woman or an AI version of a real woman. Great job!
    <function f at 0x0000019B36B6C1E0> LOL

  18. in def volume(r): isn't "r" a "parameter" and when you call the function volume(2) , then 2 is an argument?

  19. The function F does nothing! This is hellaciously funny. Where have I been those years before finding this completely mind blowing way of teaching. Thank you and story writer for making this happen. Love you

  20. Demetrius Harris

    when your brain mobility evovles from "The Flintstones" foot mobile, to a fully powered "The Jeffersons" spacecraft.

  21. Oh hey – I just noticed the last digit of Pi there is 3 and not 1. Also thanks to your Pi memorization video! (Though now I have a crisis – maybe I'm wrong…)

  22. adarshreddy mandapati

    I have seen many videos .but your are video very nice ,simple and super.the way you teach is pretty impressive.weel done.keep going

  23. over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over

    UsE a FuNcTiOn

  24. Mannnn!!! I wish I found this channel earlier. No Udemy, no bundles to be required for purchasing early, all seem to be free! Awesome!

  25. 'We will now throw caution into the vacuum of space'. (5:11) Love it!
    Cyber-Ulka is great, but definitely a delusional space nerd! For space doesn't exist. It's nothing but the simulated product of complex software code running in vast computer systems.

  26. This video is so close to perfect that i only listened like podcast and understand every words.

    Something i think we have alien among us

Leave a Reply

Your email address will not be published. Required fields are marked *