0% found this document useful (0 votes)
11 views20 pages

MODULE 3 Python

Uploaded by

wtcricci
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
11 views20 pages

MODULE 3 Python

Uploaded by

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

PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

1. Python Functions
 What is a Function?
A function is a block of reusable code designed to perform a specific task. It helps in writing
efficient programs by reducing repetition and improving organization.

 Purpose of Functions
Functions help break down complex problems into smaller steps. This improves readability,
code reusability, and makes debugging easier.

Types of Functions in Python

2. A) Built-in Functions
Python provides many built-in functions that can be used without needing to write them from
scratch. These functions perform common tasks like calculations, data conversions, and
input/output handling.

 abs(): Returns the absolute value of a number.


Example: abs(-5) returns 5.

 all(): Returns True if all elements in an iterable are true.


Example: all([True, True, False]) returns False.

 any(): Returns True if any element in an iterable is true.


Example: any([False, True, False]) returns True.

 ascii(): Returns a string with any non-ASCII characters escaped.


Example: ascii('é') returns '\\xe9'.

 bin(): Converts an integer to its binary equivalent.


Example: bin(10) returns '0b1010'.

 bool(): Converts a value to Boolean (True or False).


Example: bool(0) returns False.

 chr(): Converts an integer to its character representation.


Example: chr(65) returns 'A'.

 complex(): Returns a complex number from real and imaginary parts.


Example: complex(2, 3) returns (2+3j).

 dict(): Creates a dictionary object.


Example: dict(a=1, b=2) returns {'a': 1, 'b': 2}.

 divmod(): Returns quotient and remainder of a division.


Example: divmod(10, 3) returns (3, 1).

 eval(): Evaluates and executes an expression passed as a string.


Example: eval('2 + 3') returns 5.

1
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

 float(): Converts a value to a floating-point number.


Example: float('3.14') returns 3.14.

 format(): Formats a value based on a specified format.


Example: format(3.14159, '.2f') returns '3.14'.

 help(): Displays the documentation for a given object.


Example: help(print) shows how to use the print() function.

 hex(): Converts an integer to a hexadecimal string.


Example: hex(255) returns '0xff'.

 input(): Takes input from the user.


Example: input('Enter your name: ').

 int(): Converts a value to an integer.


Example: int('10') returns 10.

 iter(): Returns an iterator object.


Example: iter([1, 2, 3]).

 len(): Returns the length of an object.


Example: len('hello') returns 5.

 list(): Creates a list from an iterable.


Example: list('abc') returns ['a', 'b', 'c'].

 max(): Returns the largest item in an iterable.


Example: max([1, 2, 3]) returns 3.

 min(): Returns the smallest item in an iterable.


Example: min([1, 2, 3]) returns 1.

 next(): Returns the next item from an iterator.


Example: next(iter([1, 2, 3])) returns 1.

 oct(): Converts an integer to an octal string.


Example: oct(8) returns '0o10'.

 ord(): Converts a character to its Unicode code point.


Example: ord('A') returns 65.

 pow(): Returns the power of a number.


Example: pow(2, 3) returns 8.

 print(): Outputs a message to the console.


Example: print('Hello').

 range(): Returns a sequence of numbers.


Example: range(1, 5) gives 1, 2, 3, 4.

 reversed(): Returns the reversed iterator of a sequence.


Example: reversed([1, 2, 3]).

 round(): Rounds a number to a specified number of digits.


Example: round(3.14159, 2) returns 3.14.

2
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

 set(): Creates a set object.


Example: set([1, 2, 2, 3]) returns {1, 2, 3}.

 sorted(): Returns a sorted list from an iterable.


Example: sorted([3, 1, 2]) returns [1, 2, 3].

 str(): Converts a value to a string.


Example: str(10) returns '10'.

 sum(): Returns the sum of all items in an iterable.


Example: sum([1, 2, 3]) returns 6.

 tuple(): Creates a tuple from an iterable.


Example: tuple('abc') returns ('a', 'b', 'c').

 type(): Returns the type of an object.


Example: type(5) returns <class 'int'>.

 zip(): Combines elements from multiple iterables into tuples.


Example: zip([1, 2], ['a', 'b']) returns [(1, 'a'), (2, 'b')].

b) User-Defined Functions
These are functions created by the user to perform specific tasks. You define them using the def
keyword.

3
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

Explanation:

 Function Name: is_even


 Parameter: number (the number to check)
 Code Block:
o The function checks if number is divisible by 2.
o If it is, it returns True (meaning the number is even).
o Otherwise, it returns False (meaning the number is odd).

3. Mathematical Functions in Python

Mathematical functions in Python are used to perform mathematical operations on numeric


data types. Python provides a built-in module called math, which includes a variety of
functions that help with numerical computations.

Importing Functions from the math Module

Python provides three ways to import functions from the math module:

You can use functions by prefixing them with math., e.g., math.ceil(5.4).

You can use the functions directly without the module prefix, e.g., ceil(5.4).

This imports all functions, allowing you to use them without the module prefix. However, it's
generally not recommended due to potential naming conflicts.

4
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

3.1. Numeric Representation Functions:

The math module provides various functions that perform mathematical operations. Below
are some commonly used functions:

1. math.ceil(x): (Ceiling)
o Returns the smallest integer greater than or equal to x.
o Example: math.ceil(5.4) → 6
2. math.comb(n, k): (Combination)
o Returns the number of ways to choose k items from n items without repetition and
without order (combinations).
o Example: math.comb(5, 2) → 10
3. math.fabs(x): (Floating Absolute Value)
o Returns the absolute value of x as a float.
o Example: math.fabs(-3) → 3.0
4. math.factorial(x): (Factorial)
o Returns the factorial of a non-negative integer x.
o Example: math.factorial(5) → 120
5. math.floor(x): (Floor)
o Returns the largest integer less than or equal to x.
o Example: math.floor(5.9) → 5
6. math.fsum(iterable): (Floating-point Sum)
o Returns an accurate floating-point sum of a given iterable (e.g., list or tuple).
o Example: math.fsum([1, 2, 3]) → 6.0
7. math.gcd(a, b): (Greatest Common Divisor)
o Returns the greatest common divisor of a and b.
o Example: math.gcd(8, 12) → 4
8. math.isqrt(n): (Integer Square Root)
o Returns the integer square root of n.
o Example: math.isqrt(16) → 4
9. math.modf(x): (Modf)
o Returns the fractional and integer parts of x as a tuple.
o Example: math.modf(5.75) → (0.75, 5.0)
10. math.perm(n, k): (Permutation)
o Returns the number of ways to choose k items from n items with order
(permutations).
o Example: math.perm(5, 2) → 20
11. math.prod(iterable, *, start=1): (Product).
o Returns the product of all the elements in an iterable. It can also take an optional
start value.(1)
o Example: math.prod([2, 3, 4]) → 24

5
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

12. math.remainder(x, y): (Remainder)


o Returns the difference between x and the closest multiple of another number y.
o Example: math.remainder(5, 2) → 1.0
o Closest multiple of 2 to 5 is 4.(multiple of 2= 0,2,4,6,8,…)nearest is 4 and 6,4 is
lesser so we will consider that one.
o Calculation: 5−4=1
o Output: 1.0
13. math.trunc(x): (Truncate)
o Returns the integer part of x by truncating the decimal part.
o Example: math.trunc(5.9) → 5

Conclusion

Mathematical functions in Python provide powerful tools for performing a wide range of
numerical operations. The math module includes many useful functions that can simplify
complex calculations, making it easier for programmers to work with numbers in Python.

3.2. Power and Logarithmic Functions:


Python’s math module provides several functions to work with powers and logarithms, making it
easier to perform complex mathematical calculations. Here’s a simplified explanation of these
functions.

6
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

Conclusion

These functions allow you to handle power and logarithmic operations easily in Python,
helping with a variety of mathematical calculations.

3.3. Trigonometric Functions:

Python provides several built-in trigonometric functions in the math module, which are used
to calculate angles and distances. Here's a simple explanation of each function:

7
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

Conclusion

These trigonometric functions are useful for working with angles and distances, especially in
fields like geometry, physics, and engineering. They provide quick solutions for common
trigonometric problems

3.4. Angular Conversion Functions


Python's math module provides functions to convert angles between degrees and radians, which
are widely used in trigonometry and geometry.

8
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

Conclusion

These functions are useful when working with angles in different units, as radians are often
used in mathematical calculations, while degrees are more commonly used in everyday
applications.

3.5. Hyperbolic Functions

Hyperbolic functions are similar to trigonometric functions but are based on hyperbolas
instead of circles.

3.6. Math Constants

Python provides important mathematical constants with high precision:

(It represents the ratio of a circle's circumference to its radius.)

9
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

4. Date and Time Functions

Python provides multiple modules to handle dates and times efficiently, with the most
common ones being datetime and time.

4.1. datetime Module

The datetime module is the main way to work with dates and times in Python. It consists of
several classes:

1. date
o Full Form: Date
o Purpose: Represents a date (year, month, day).
o Usage:
 Creating a date object: date(year, month, day)

2. time

 Full Form: Time


 Purpose: Represents a time (hours, minutes, seconds, microseconds).
 Usage:
o Creating a time object: time(hour, minute, second, microsecond)

3. datetime

 Full Form: DateTime


 Purpose: Combines both date and time into a single object.
 Usage:
o Creating a datetime object: datetime(year, month, day, hour, minute,
second)

10
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

4. timedelta

 Full Form: Time Delta


 Purpose: Represents the difference between two date or time objects.
 Usage:
o Creating a timedelta object: timedelta(days, seconds, microseconds,
milliseconds, hours, weeks)

5. tzinfo

 Full Form: Time Zone Information


 Purpose: A base class for dealing with time zone information.
 Usage: Typically used in conjunction with other classes to manage time zone data.

6. timezone

 Full Form: Time Zone


 Purpose: A subclass of tzinfo that represents a fixed offset from UTC (Coordinated
Universal Time).
 Usage:
o Creating a timezone object: timezone(offset)

Constants in datetime Module:

 datetime.MINYEAR: The minimum year supported, usually 1.


 datetime.MAXYEAR: The maximum year supported, usually 9999.

11
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

4.1.1 Date Objects

 Full Form: Date Objects


 Usage: Represents a date (year, month, day) without any time component.
 Methods:
o today(): Returns the current local date.
o fromtimestamp(timestamp): Creates a date object from a POSIX timestamp.

4.1.2 Time Objects

 Full Form: Time Objects


 Usage: Represents time (hours, minutes, seconds, microseconds) without any date
component.
 Methods:
o isoformat(): Returns a string representing the time in ISO 8601 format.

4.1.3 DateTime Objects

 Full Form: DateTime Objects


 Usage: Combines date and time into one object for convenience.
 Methods:
o now(): Returns the current local date and time.
o strftime(format): Formats the datetime object as a string based on a specified
format.

12
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

4.2 time Module

The time module provides various time-related functions that can be used to measure time
intervals, manage sleep times, and get the current time.

Key Functions:

 time.time()
o Full Form: Current Time
o Purpose: Returns the current time in seconds since the epoch (January 1, 1970).

time.sleep(seconds)

 Full Form: Sleep


 Purpose: Suspends the execution of the calling thread for the given number of
seconds.

13
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

5. Random Numbers with Python

Random Numbers in Python

In Python, random numbers are used in various applications like simulations, games, data
analysis, and cryptography. The random module provides tools to generate random numbers
and perform random operations. It supports generating numbers from different distributions
and allows customization to meet specific needs.

Why Use Random Numbers?

 Simulations: To mimic real-world processes where outcomes are unpredictable.


 Games: To add variability and unpredictability.
 Testing: To generate random test data for software testing.
 Data Sampling: For statistical sampling or shuffling datasets.

14
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

15
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

6. Arguments and Parameters

Parameters:

 These are variables that are defined in a function's declaration. They act as
placeholders for the values (arguments) that will be passed into the function when it is
called.
 Example:

Arguments:

 These are the actual values or data you pass into the function when you call it.
Arguments can be variables, constants, or expressions.
 Example:

1. Required Arguments:

 These are arguments that must be provided to the function. If they are missing, the
program will raise an error.
 Example:

2. Default Arguments:

 These are arguments that have a default value. If the caller does not provide a value,
the function will use the default.
 Syntax: parameter=default_value
 Example:

16
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

3. Keyword Arguments:

 These are arguments passed to a function by explicitly stating the parameter name.
This allows you to pass arguments in any order.
 Example:

4. Arbitrary Arguments:

 These allow a function to accept any number of positional arguments. They are
defined using an asterisk (*) before the parameter name.
 Example:

5. Arbitrary Keyword Arguments:

 These allow you to pass any number of keyword arguments to a function. You don't
know how many arguments you'll pass in advance.

 Use ** before the parameter name to accept these arguments.

17
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

Example:

Explanation:

 first and last are regular arguments.


 **extra_info can take any number of keyword arguments (like age and location in
this case).

Output:

7. Return Values:
When a function completes its task, it can send a result back using the return statement. To get the
output from a function and use it later in your code.

8. Local and Global Variables:

 Local Variables:

 Variables created inside a function.


 They can only be used inside that function and disappear once the function ends.

18
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

 Global Variables:

 Variables created outside any function.


 Can be accessed inside any function as well as throughout the program.

 Example:

9. Recursion:

Recursion is when a function calls itself to solve a smaller part of a problem.

A function keeps calling itself until it reaches a stopping condition (called the base case).

19
PYTHON NOTES AL JAMIA ARTS AND SCIENCE COLLEGE

 Explanation:

 The function factorial(5) calls itself with smaller numbers (4, 3, 2, 1) until it
reaches 1.
 When it reaches 1, it stops calling itself and calculates the final result.

 Key Point:

 Recursion must always have a base case to stop the function from calling itself
forever

10.Anonymous (Lambda) Functions:

A lambda function is a small, one-line function without a name.

 It's used when you need a function quickly, for small tasks.
 You use the keyword lambda to create it.

 It can take arguments and returns a result, just like a regular function, but it doesn’t
need a name.
 Syntax:

Example:

20

You might also like