Python-3.4.3/C4/Getting-Started-with-Functions/English
|
|
Show Slide title | Welcome to the spoken tutorial on Getting started with functions. |
Show Slide
Objectives
|
In this tutorial, we will learn to,
|
Show Slide
System Specifications |
To record this tutorial, I am using
|
Show Slide
Pre-requisite |
To practise this tutorial, you should know how to use tuples.
|
Show Slide
|
First we will learn about functions.
|
Slide:
Syntax of functions:
return [expression]
|
Here is the syntax for defining the functions.
It is an optional, but recommended.
|
Show Slide:
Example: Function
return x*x
|
Now we will understand the functions with an example.
|
Open terminal | Let us start ipython.
|
Type, ipython3
then press Enter |
Type ipython3 and press Enter.
|
Type,
def f(x): return x*x |
Type,
def f inside brackets x colon return x asterisk x
|
Type,
f(2)
|
Let us call the f of x with different arguments.
f inside brackets 2
|
Type,
def greet(): print ("No function arguments")
|
Now let us see how to write functions without arguments.
|
Type,
greet() |
Now we will call the function as,greet open and close parentheses |
Note that it is not mandatory for a function to return values.
| |
Show Slide
docstrings
|
Next we will learn how to comment in a code.
|
Type, (type manually)def avg(a, b):
""" avg takes two numbers as input a & b. Returns the average of a and b""" return (a + b) / 2.0 |
Let us write a function which returns average of two numbers.
Type the code as shown.
|
Type,
avg?
|
Type,
avg question mark
|
Type,
avg(3, 5) |
Now let us pass 3 and 5 as values to the arguments a and b to the function avg.
|
Pause the video.
| |
Show Slide
Assignment 1 |
Write a function circle which returns the area and perimeter of a circle with given radius r. |
Switch terminal | Switch back to the terminal for the solution. |
Type,
def circle(r): """returns area and perimeter of a circle given radius r""" pi = 3.14 area = pi * r * r perimeter = 2 * pi * r return area, perimeter |
Type the code as shown.
|
Type,
a, p = circle(6) |
Let us call the function circle as,
a comma p is equal to circle inside brackets 6 |
Type,
print (a, p) |
Type,
print inside brackets a comma p
|
Show Slide
Summary
|
This brings us to the end of this tutorial. Let us summarize.
|
Show Slide
|
Here are some self assessment questions for you to solve
|
Show Slide
Solution of self assessment questions
|
And the answers,
def rectangle underscore area inside brackets l comma b colon return l asterisk b |
Show Slide Forum | Please post your timed queries in this forum. |
Show Slide Fossee Forum | Please post your general queries on Python in this forum. |
Slide Textbook Companion | FOSSEE team coordinates the TBC project. |
Show Slide
Acknowledgment |
Spoken Tutorial Project is funded by NMEICT, MHRD, Govt. of India.
For more details, visit this website. |
Previous slide | This is Priya from IIT Bombay signing off.
Thanks for watching. |