Python Function, Names, Variables, Code

Big title, right? I am about to introduce you to the python function! Every programmer will go on and on about functions and all the different ideas about how they work and what they do, but I will give you the simplest explanation you can use right now.

Functions do three things:

  1. They name pieces of code the way variables name strings and numbers.
  2. They take arguments the way your scripts take argv.
  3. Using 1 and 2 they let you make your own “mini-scripts” or “tiny commands.”
  4. Most important is we can use same function many time.

You can create a function by using the word def in Python. I’m going to have you make four different functions that work like your scripts, and I’ll then show you how each one is related.

Lets see a code

 

Python function - pythoninhindi.shiksha

Code Explanation

  • First line is comment.. So nothing to explain
  • In 2nd line we have defined a function called print_none. After defining function name we give “:” which means now we will be writing code in segment of this function. When you hit enter after “:” your curser in next line will have 4 space.
  • This line have code for your function, it start with 4 space, which are important. According to python if you have provided 4 space that means this code is in segment of line above it.
  • You can have as many line of function as you like.
  • To define new function you have to move your cursor to starting point of line or delete 4 space of that line. e.g in line 6.
  • In Line 6 we have define another function call print_one, which have 1 argument which we will pass to it while using this function. Its same as passing arguments to a script.
  • I believe you will be able to understand this code till line 18
  • Line 19 we have called function print_two and passed 2 arguments.
  • You can call any function in any sequence. In case you have to use a function inside another function then you have to define it first.

Try this code yourself and you will understand.

Python Functions

Exercise of the day

  • In first code call functions in different order and see the output.
  • Try calling function in a function.
  • Instead of string pass variables in function.
  • Try to use 3 space instead of 4 space and check this error. Its important, While coding in python you will get this error a lot of time, so its better to understand it right now.

 

comment (1)

Leave me comment