0% found this document useful (0 votes)
16 views42 pages

Python Module 1 23MBA

Uploaded by

adithyahegdee2
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
16 views42 pages

Python Module 1 23MBA

Uploaded by

adithyahegdee2
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 42

Introduction to Python

- History, Characteristics, Advantages, Applications


- Python Installation (3.11)/Anaconda installation
- Python Interpretor, compilor, IDE
(IDLE/Jupyter/Spyder/Pycharm, etc.), online python
- Modules/Packages/Libraries
- Working with Python – simple commands.
- Data types, Variables, operators and Functions

MODULE 1
Python - History
 1980s: Guido van Rossum, a Dutch programmer, starts working on Python as a hobby project
during Christmas.
 1991: Python's first version, Python 0.9.0, is released, featuring exception handling, functions,
and modules.
 1994: Python 1.0 is released, with features like lambda, map, filter, and reduce.
 2000: Python 2.0 is released, introducing list comprehensions and garbage collection.
 2008: Python 3.0 (also known as "Python 3000" and "Py3k") is released, with significant changes
to the language to improve its consistency and eliminate redundancy.
 2010: The release of Python 2.7, which would be the last major version in the Python 2.x series,
marking the start of the transition to Python 3.
 2018: Python 3.7 is released, featuring various improvements and optimizations.
 2020: Python 2 reaches its end-of-life, and all development efforts focus on Python 3.
 2021: Python 3.9 is released, introducing features like the walrus operator (:=) and performance
enhancements.
 2022: Python 3.10 is released, bringing features like pattern matching and improved error
messages.
 2023: Python 3.11 released
 2024: Python 3.12 released
 Python continues to evolve with regular updates and releases, maintaining its status as one of the
most popular programming languages worldwide.
Python - Characteristics
 Readability: Python emphasizes code readability and simplicity, making it easier to write and
understand code, even for beginners.
 Versatility: Python is a versatile language, suitable for various domains such as web
development, data science, machine learning, artificial intelligence, automation, and more.
 Interpreted: Python is an interpreted language, meaning that code is executed line by line,
allowing for quick prototyping and development.
 Dynamic typing: Python uses dynamic typing, where variable types are determined at runtime,
providing flexibility but requiring careful attention to type compatibility.
 Large standard library: Python comes with a comprehensive standard library, providing
modules and packages for tasks ranging from file I/O to networking to web development, reducing
the need for external dependencies.
 High-level language: Python abstracts away low-level details, allowing developers to focus on
problem-solving rather than system-specific details.
 Community support: Python has a large and active community of developers, contributing to a
wealth of resources, libraries, frameworks, and online forums for support and collaboration.
 Object-oriented: Python supports object-oriented programming paradigms, allowing for the
creation and manipulation of objects with attributes and methods, facilitating code organization
and reuse.
 Cross-platform: Python is available on various operating systems, including Windows, macOS,
and Linux, making it highly portable and accessible across different environments.
 Integration: Python can easily integrate with other languages like C/C++, allowing for
performance-critical tasks to be optimized while still leveraging Python's high-level features.
 These characteristics contribute to Python's popularity and widespread adoption across different
industries and applications.
Python – Applications
 Web Development: Python is widely used for web development, with
frameworks like Django and Flask facilitating the creation of dynamic and
scalable web applications.
 Data Science and Machine Learning: Python is a popular choice for
data analysis, machine learning, and artificial intelligence tasks. Libraries
like NumPy, Pandas, scikit-learn, TensorFlow, and PyTorch provide
powerful tools for data manipulation, analysis, and building machine
learning models.
 Scientific Computing: Python is extensively used in scientific
computing and computational science for tasks such as simulations,
modeling, and visualization. Libraries like SciPy and Matplotlib are
commonly employed for these purposes.
 Automation and Scripting: Python's simplicity and versatility make it
well-suited for automation tasks, scripting, and process automation. It's
commonly used for tasks like file manipulation, data processing, and
system administration.
 Desktop GUI Applications: Python can be used to develop desktop GUI
applications using frameworks like Tkinter, PyQt, and PyGTK, allowing
developers to create cross-platform desktop applications with graphical
 Game Development: Python is used in game development, both for creating
games from scratch and for scripting within existing game engines like Unity and
Blender. Libraries like Pygame provide tools for game development in Python.
 Web Scraping: Python's ease of use and rich ecosystem of libraries make it a
popular choice for web scraping and data extraction tasks. Libraries like
BeautifulSoup and Scrapy are commonly used for extracting data from websites.
 Networking: Python is used for networking tasks, such as building network
servers, clients, and network automation scripts. Libraries like Twisted and
asyncio provide tools for asynchronous networking programming.
 Education: Python's readability and simplicity make it an excellent choice for
teaching programming concepts to beginners. Many educational institutions use
Python as an introductory programming language.
 Financial and Quantitative Analysis: Python is widely used in the finance
industry for tasks such as financial modeling, algorithmic trading, and
quantitative analysis. Libraries like pandas and NumPy are commonly used for
analyzing financial data.
 These are just a few examples of the diverse range of applications for Python. Its
versatility, ease of use, and large ecosystem of libraries and frameworks make it
a popular choice for a wide variety of projects and industries.
Python installation
Here are the general steps to install Python on a Windows system:

 Download Python Installer:

 Go to the official Python website at https://www.python.org/.

 Navigate to the "Downloads" section.

 Choose the latest version of Python for Windows, typically displayed prominently on the page.

 Click on the download link for the Windows installer (usually labeled as "Download Python X.X.X").

 Run Python Installer:

 Once the installer is downloaded, locate the downloaded file (typically in your Downloads folder).

 Double-click on the installer file to run it. The file name usually starts with "python-" followed by the version number.

 Configure Python Installation:

 In the Python installer, make sure to check the box that says "Add Python X.X to PATH". This option ensures that Python is added to the system
PATH, allowing you to run Python from the command line easily.

 You can also customize the installation by choosing optional features or changing the installation directory if needed. For most users, the default
settings are sufficient.

 Install Python:

 Click on the "Install Now" button to start the installation process.

 The installer will copy Python files to your system and set up the environment. This process may take a few minutes.

 Verify Installation:

 Once the installation is complete, you can verify that Python is installed correctly by opening a command prompt (search for "cmd" in the Start
menu).

 In the command prompt, type python --version and press Enter. This command should display the installed Python version. Alternatively, you can
type python and press Enter to start the Python interpreter, where you can execute Python code directly.

 That's it! Python should now be successfully installed on your Windows system. You can start writing and running Python code right away.
Anaconda
 Anaconda is an open-source distribution of Python and other programming languages commonly used for
data science and machine learning tasks. It includes a wide range of pre-installed libraries and tools that
are essential for data analysis, scientific computing, and machine learning tasks. Anaconda simplifies the
process of setting up and managing environments for data science projects by providing a convenient
package management system called Conda.
 Here's how Anaconda is related to Python:
 Python Distribution: Anaconda includes Python as its primary programming language. It comes bundled
with the Python interpreter, standard library, and commonly used third-party packages.
 Pre-installed Libraries: Anaconda comes with a curated selection of data science libraries pre-installed,
including NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, and many others. These libraries are
commonly used for tasks such as data manipulation, visualization, statistical analysis, and machine
learning.
 Conda Package Manager: Anaconda includes Conda, a powerful package and environment management
system. Conda allows users to easily install, update, and manage packages and dependencies for their
Python projects. It also enables the creation and management of isolated environments, which can have
their own set of packages and Python versions, making it easy to manage dependencies and avoid
conflicts between projects.
 Cross-platform: Anaconda is available for Windows, macOS, and Linux, making it a versatile choice for
data science and machine learning tasks across different operating systems.
 Integrated Development Environment (IDE): Anaconda includes an integrated development
environment called Anaconda Navigator, which provides a graphical interface for managing environments,
installing packages, and launching applications such as Jupyter Notebook, JupyterLab, and Spyder.
 Overall, Anaconda provides a convenient and comprehensive platform for data scientists, researchers, and
developers to work with Python and other programming languages for data-intensive tasks. It simplifies
the setup and management of environments and comes with a rich ecosystem of libraries and tools
tailored for data science and machine learning workflows.
Anaconda installation
Here are the steps to install Anaconda on a Windows system:
 Download Anaconda Installer:
 Go to the Anaconda website at https://www.anaconda.com/products/distribution
 Navigate to the download section and choose the appropriate version of Anaconda for your operating system
(Windows).
 Select the Python version (Python 3.x is recommended) and download the installer corresponding to your system
architecture (32-bit or 64-bit).
 Run Anaconda Installer:
 Once the installer is downloaded, locate the downloaded file (typically in your Downloads folder).
 Double-click on the installer file to run it. The file name usually starts with "Anaconda3-" followed by the version
number.
 Follow Installation Wizard:
 The Anaconda installer will launch and display the installation wizard.
 Click "Next" to proceed with the installation.
 Read and Accept License Agreement:
 Read the Anaconda Individual Edition License Agreement.
 If you agree to the terms, select "I Agree" and click "Next" to continue.
 Choose Installation Type:
 Select the installation type. The default option, "Just Me (recommended)", installs Anaconda for your user
account only. You can choose "All Users" if you want to install Anaconda system-wide for all users on the
computer.
 Click "Next" to proceed.
 Choose Installation Location:
 Choose the installation location where Anaconda will be installed. The default location is usually
in your user directory (e.g., C:\Users\YourUsername\Anaconda3).
 You can change the installation location if needed.
 Click "Next" to continue.
 Select Start Menu Folder:
 Choose the Start Menu folder where shortcuts for Anaconda will be created.
 Click "Install" to begin the installation process.
 Wait for Installation to Complete:
 The installer will copy files and install Anaconda on your system. This process may take a few
minutes.
 Completing the Installation:
 Once the installation is complete, click "Next" and then "Finish" to exit the installer.
 Verify Installation:
 After installation, you can verify that Anaconda is installed correctly by searching for "Anaconda
Navigator" in the Start menu.
 Launch Anaconda Navigator, and you should see the graphical interface where you can manage
environments, install packages, and launch applications like Jupyter Notebook and Spyder.
 That's it! Anaconda should now be successfully installed on your Windows system, and
you can start using it for data science, machine learning, and other tasks.
Translators: (Interpreters and compilers)
Python is a high-level language intended to be relatively
straightforward for humans to read and write and for computers
to read and process like, Java, C++, PHP, Ruby, Basic, Perl,
JavaScript, and many more.
However, The actual hardware inside the Central Processing Unit
(CPU) does not understand any of these high-level languages.
The CPU understands a language we call machine language.
Machine language is very simple and frankly very tiresome to
write because it is represented all in zeros and ones:
001010001110100100101010000001111
11100110000011101010010101101101
However it is quite tricky and complex to program.
So programmers build translators to convert highend languages
to machine language and vice versa.
2 types of translators
 These programming language translators fall into two general
categories: (1) interpreters and (2) compilers.
1. Intepreters:
An interpreter reads the source code of the program as written by the
programmer, parses the source code, and interprets the instructions.
Python is an interpreter and when we are running Python interactively,
we can type a line of Python (a sentence) and Python processes it
immediately and is ready for us to type another line of Python.
>>> x = 6
>>> print(x)
6
>>> y = x * 7
>>> print(y)
42
>>>
2. Compiler:
A compiler needs to be handed the entire program in a file, and then it runs a
process to translate the high-level source code into machine language and then the
compiler puts the resulting machine language into a file for later execution.
If you have a Windows system, often these executable machine language programs
have a suffix of “.exe” or “.dll” which stand for “executable” and “dynamic link
library” respectively. In Linux and Macintosh, there is no suffix that uniquely
marks a file as executable.
If you were to open an executable file in a text editor, it would look completely
crazy and be unreadable:

^?ELF^A^A^A^@^@^@^@^@^@^@^@^@^B^@^C^@^A^@^@^@\xa0\x82
^D^H4^@^@^@\x90^]^@^@^@^@^@^@4^@ ^@^G^@(^@$^@!^@^F^@
^@^@4^@^@^@4\x80^D^H4\x80^D^H\xe0^@^@^@\xe0^@^@^@^E
^@^@^@^D^@^@^@^C^@^@^@^T^A^@^@^T\x81^D^H^T\x81^D^H^S
^@^@^@^S^@^@^@^D^@^@^@^A^@^@^@^A\^D^HQVhT\x83^D^H\xe8
Modules, packages and Libraries
 In Python, both module packages and libraries serve
as means to organize and distribute code, but they
differ in their scope and usage.
 Module: A module in Python is a single file containing
Python code that defines functions, classes, and
variables. It allows you to organize your code logically
and reuse it across different Python scripts. Modules
are typically used for a specific purpose or
functionality.
 Example: Suppose you have a file named
math_operations.py containing functions for
mathematical operations such as addition,
subtraction, multiplication, and division. This file can
be considered a module.
 In the context of Python, the terms "package" and "library" are often used interchangeably
but they have slightly different meanings:
 Library:
 A library in Python refers to a collection of modules that contain reusable code and functions for
specific tasks or domains.
 Libraries typically consist of multiple modules that are related to each other and serve a common
purpose.
 Examples of Python libraries include NumPy, Pandas, Matplotlib, Requests, and BeautifulSoup.
 Package:
 A package in Python is a directory that contains one or more modules and an optional __init__.py
file.
 Packages allow you to organize related modules into a hierarchical directory structure.
 The __init__.py file can be empty or contain initialization code that is executed when the package is
imported.
 Packages provide a way to structure and namespace your code, making it easier to manage and
import.
 Examples of Python packages include NumPy, Pandas, Matplotlib, Django, Flask, and TensorFlow.
 In summary, a library is a collection of modules, while a package is a directory containing
modules and potentially other sub-packages.
 However, in everyday usage, the terms "library" and "package" are often used
interchangeably to refer to collections of reusable code in Python.
Part 2

Python -
Values & data types, Variables,
Expressions, statements &
scripts,
Operators,
Functions
Values and value types (data types)
 A value is one of the basic unit a program works with,
like a letter or a number. Eg: 1, 2, “Hello, World!”, etc
 Values types/data types: There are several types of
values like Integer, float, and string.
 strings belong to the type str and integers
belong to the type int. Numbers with a
decimal point belong to a type called float,
because these numbers are represented in a
format called floating point. [We will learn later
that there are types like bool, list, tuple,
dictionary, no type etc]
 2 is an integer, 2.00 is a float and “Hello, World!” is a
string, so called because it contains a “string” of
 To check the type of a value, type, type; the interpreter will tell
you.
>>> type('Hello, World!')
<class 'str'>
 >>> type(17)
 <class 'int'>
>>> type(3.2)
<class 'float'>
 What about values like “17” and “3.2”? They look like numbers, but they
are in quotation marks like strings.
>>> type('17')
<class 'str'>
>>> type('3.2')
<class 'str'>
 They’re strings.
Variables
 A variable is a name that refers to a value.
 An assignment statement creates new variables and gives them values:
>>> message = ‘There is no class tomorrow'
>>> n = 17
>>> pi = 3.1415926535897931
 This example makes three assignments. The first assigns a string to a new variable named message; the second
assigns the integer 17 to n; the third assigns the (approximate) value of π to pi.
 To display the value of a variable, you can use a print statement:
>>> print(n)
17
>>> print(pi)
3.141592653589793
 The type of a variable is the type of the value it refers to (and not of the variable itself)
>>> type(message)
<class 'str'>
>>> type(n)
<class 'int'>
>>> type(pi)
<class 'float'>
Variable names
 Programmers generally choose names for their variables that are
- Meaningful and represent what the variable is used for.
- Variable names can be arbitrarily long.
- They can contain both letters and numbers,
- But they cannot start with a number
- They cannot have space in between and
- They are case sensitive
- Cannot use key words
- It is legal to use uppercase letters, but it is a good idea to begin variable
names with a lowercase letter (you’ll see why later).
- The underscore character ( _ ) can appear in a name. It is often used in
names with multiple words, - such as my_name or mary_had_a_little_lamb
- Variable names can start with an underscore character, but we generally
avoid doing this unless we are writing library code for others to us
Illegal names
 If you give a variable an illegal name, you get a syntax error:
examples,
>>> 76trombones = 'big parade' SyntaxError: invalid
syntax
>>> more@ = 1000000 SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy' SyntaxError:
invalid syntax
 76trombones is illegal because it begins with a number.
more@ is illegal because it contains an illegal character @,
and class is a key word in python
 Case sensitivity –they are case sensitive
 Space – space matters
It turns out that class is one of Python’s keywords. The interpreter
uses keywords to recognize the structure of the program, and they
cannot be used as variable names.
Python reserves 35 keywords:

and continue finally is raise


as def for lambda return
assert del from None True
async elif global nonlocal try

await else if not while


break except import or with
class False in pass yield
Expressions, statements and scripts
 Expression is a combination of values, variables, and
operators. A value all by itself is considered an expression,
and so is a variable, so the following are all legal
expressions (assuming that the variable x has been
assigned a value):
17
x
x + 17
 If you type an expression in interactive mode, the
interpreter evaluates it and displays the result:
>>> 1 + 1
2
 But in a script, an expression all by itself doesn’t do
anything! Until the entire script is executed.
 statement is a unit of code that the Python interpreter can execute.
 We have seen two kinds of statements:
 print being an expression statement and the assignment statement.
 An assignment statement assigns a value to a variable, while an expression
statement generates a result and provides an putput
 When you type a statement in interactive mode, the interpreter executes it
and displays the result, if there is one.
 script usually contains a sequence of statements. If there is more than one
statement, the results appear one at a time as the statements execute.
 For example, the script
print (1) # expression statement gives output
x=2 # assignment statement gives no output
print (x) # expression statement gives output
produces the output
1
2
Operators
(mathematical,
comparison and logical)
Mathematical operators and operands
 Mathematical Operators are special symbols that represent computations like
addition, subtraction, multiplication, division (including floored division, modulus) and
exponents.
 The values the operator is applied to are called operands.
 Examples: The operators +, -, *, /, and ** perform addition, subtraction,
multiplication, division, and exponentiation, as in the following examples:
20+32 hour-1 hour*60+minute minute/60 5**2
(5+9)*(5-7)
 In Python 3.x result of division is a floating point
>>> minute = 59
>>> minute/60
0.9833333333333333
 Floored division/Integer division for quotient:
 To obtain quotient/integer or the truncation result in Python 3.0 use floored ( //
integer) division
>>> minute = 59
>>> minute//60
 Modulus operator
 The modulus operator works on integers and yields the
remainder when the first operand is divided by the second. In
Python, the modulus operator is a percent sign (%). The syntax
is the same as for other operators:
>>> remainder = 7 % 3
>>> print(remainder)
1
 Application of mod operator:
 The modulus operator turns out to be surprisingly useful. For
example, you can check whether one number is divisible by
another: if x % y is zero, then x is divisible by y.
 You can also extract the right-most digit or digits from a
number. For example, x % 10 yields the right-most digit of x (in
base 10). Similarly, x % 100 yields the last two digits.
Precedence of operators/Order of operations
 When more than one operator appears in an expression, the order of evaluation
depends on the rules of precedence. For mathematical operators, Python follows
mathematical convention. The acronym PEMDAS is a useful way to remember the
rules:
 Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first,
2 * (3-1) is 4, and (1+1)**(5-2) is 8.
 Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is
3, not 27.
 Multiplication and Division have the same precedence, which is higher than Addition
and Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and
6+4/2 is 8, not 5.
 Operators with the same precedence are evaluated from left to right. So the
expression 5-3-1 is 1, not 3, because the 5-3 happens first and then 1 is subtracted
from 2.
 When in doubt, always put parentheses in your expressions to make sure the
computations are performed in the order you intend.
Boolean expressions and operators
 A boolean expression is an expression that is either true or false.
 The following examples use the operator ==, which compares two operands and
produces True if they are equal and False otherwise:
>>> 5 == 5
True
>>> 5 == 6
False
 True and False are special values that belong to the class bool; they are
not strings:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
Comparison operators
 x==y # x s equal to y
 x != y # x is not equal to y
 x>y # x is greater than y
 x < y # x is less than y
 x >= y # x is greater than or equal to y
 x <= y # x is less than or equal to y
 x is y # x is the same as y
 x is not y # x is not the same as y
 A common error is to use a single equal sign (=) instead of a
double equal sign (==). Remember that = is an assignment
operator and == is a comparison operator.
 There is no such thing as =< or =>
Logical operators
 There are three logical operators: and, or, not.
The semantics (meaning) of these operators is
similar to their meaning in English. For example,
 x > 0 and x < 10 is true only if x is greater
than 0 and less than 10.
 n%2 == 0 or n%3 == 0 is true if either of the
conditions is true, that is, if the number is divisible
by 2 or 3.
 Finally, the not operator negates a boolean
expression, so not (x > y) is true if
x > y is false; that is, if x is less than or equal to
In operation
Functions
Functions
 In the context of programming, a function is a named
sequence of statements that performs a computation.
 When you define a function, you specify the name and the
sequence of statements. Later, you can “call” the
function by name. We have already seen one example of a
function call:
>>> type(32)
<class 'int'>
 The name of the function is type. The expression in
parentheses is called the argument of the function. The
argument is a value or variable that we are passing
into the function as input to the function. The result, for
the type function, is the type of the argument.
 It is common to say that a function “takes” an argument and
“returns” a result and result is called the return value.
Types of functions

 Built-in functions and


 User defined functions
Built-in functions
 Python provides a number of important built-in functions that we can use
without needing to provide the function definition.
 The max and min functions give us the largest and smallest values in a list,
respectively:
>>> max('Hello world')
’w’
>>> min('Hello world')
’’
 The max function tells us the “largest character” in the string (which turns out
to be the letter “w”) and the min function shows us the smallest
character (which turns out to be a space).
 len function tells us how many items are in its argument. If the argument to
len is a string, it returns the number of characters in the string.
>>> len('Hello world')
11
 These functions are not limited to looking at strings. They can operate on any
set of values.
Type conversion functions
 Python also provides built-in functions that convert values from one type to another. The int function
takes any value and converts it to an integer, if it can, or complains otherwise:
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'
 int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
 float converts integers and strings to floating-point numbers:
>>> float(32)
32.0
>>> float('3.14159')
3.14159
 Finally, str converts its argument to a string:
>>> str(32)
’32’
>>> str(3.14159)
’3.14159’
math functions
 Python has a built-in math module that provides most of the familiar mathematical
functions. To use the module, we have to import it:
>>> import math
 To access one of the functions, you have to specify the name of the module and the name of
the function, separated by a dot (also known as a period). This format is called dot notation.
 Example: computes decibels by the logarithm base 10 of the signal-to-noise ratio. (The math
module also provides a function called log that computes logarithms base e)
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
 Example: Find the square root of a given number
>>> math.sqrt(16)
4
 Third example below calculates height from degrees after converting degrees to radians
convert from degrees to radians (divide by 360 and multiply by 2π)
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> Height = math.sin(radians)
0.7071067811865476
function random returns a random float between 0.0 and 1.0
(including 0.0 but not 1.0). Each time you call random, you get the
next number in a long series. To see a sample, run this loop:
import random
for i in range(10):
x = random.random()
print(x)

 This program produces the following list of 10 random numbers between 0.0 and up to but not including 1.0.
0.11132867921152356
0.5950949227890241
0.04820265884996877
0.841003109276478
0.997914947094958
0.04842330803368111
0.7416295948208405
0.510535245390327
0.27447040171978143
0.028511805472785867
Composition of function/composite function
 Composite function is where any kind of expression
(including arithmetic operators) or another function is used
as an argument to a function. Example:
 X=math.sin(angle+math.pi/4)
 Here we have used an expression (angle+math.pi)/4 as an
argument to the function math.sin.
 First the inner expression is calculated and the resultant
value is used as an argument for the function math.sin
 Similarly we can take a function as an argument for
another function Example:
 X=math.exp(math.log(10.0))
 Here the value of function math.log(10.0) is calculated first
and used as an argument for the function math.exp
Creating new functions - user defined functions

 A function definition specifies the name of a new function and the sequence of
statements that execute when the function is called. Example:
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
 def is a keyword that indicates that this is a function definition. The name of the
function is print lyrics.
 [The rules for function names are the same as for variable names: letters,
numbers and some punctuation marks are legal, but the first character can’t be a
number. You can’t use a keyword as the name of a function, and you should avoid
having a variable and a function with the same name]
 The empty parentheses after the name indicate that this function
doesn’t take any arguments. Later we will build functions that take
arguments as their inputs.
 The first line of the function definition is called the header; the rest
is called the body. The header has to end with a colon and the body has
to be indented. By convention, the indentation is always four spaces.
The body can contain any number of statements.
 If you type a function definition in interactive mode, the interpreter prints
ellipses (. . . ) to let you know that the definition isn’t complete:
>>> def print_lyrics():
... print("I'm a lumberjack, and I'm okay.")
... print('I sleep all night and I work all day.')

 To end the function, you have to enter an empty line (this is not necessary in
a script). Defining a function creates a variable with the same name
 The value of the variable print_lyrics is called a ‘function object’ , which is of
type “function”.
 The syntax for calling the new function is the same as for built-in functions:
print(type(print_lyrics))
<class 'function'>
 Calling the function:
>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
Recursion or recursive function
 If a function calls itself it is called recursion or recursive
function. Usually a function calls another function but in this
case it calls itself.
 Example:
Def countdown(n):
if n <= 0:
print(Blast off!)
else:
print(n)
countdown(n-1)
 Please note that this is very similar to iteration which uses while
statement and updating variables. This one uses If, else
statement and repeats a function itself

You might also like