Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Unit 4 Python

This document lists and describes 10 common built-in functions in Python including functions for type conversion, math operations, and more. The functions covered are int(), float(), ord(), hex(), oct(), tuple(), set(), list(), dict(), and str() with examples of using each function.

Uploaded by

TAIBA SHAIKH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Unit 4 Python

This document lists and describes 10 common built-in functions in Python including functions for type conversion, math operations, and more. The functions covered are int(), float(), ord(), hex(), oct(), tuple(), set(), list(), dict(), and str() with examples of using each function.

Uploaded by

TAIBA SHAIKH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Q. List and Use of Python built-in functions(e.g.

type/data conversion functions, math functions ,


etc )
Built in Functions in Python
Sr. Function Purpose Example
No
1. In Python, the int() # Converting a string to an integer
1 int(a,base)
function is used to convert a print(int("123")) # Output: 123
given value into an integer.
It can handle different types
# Converting a float to an integer
of input and convert them
print(int(3.14)) # Output: 3
into integers if possible

# Converting a binary string to an integer


(base 2)
print(int("1010", 2)) # Output: 10

# Converting a hexadecimal string to an


integer (base 16)
print(int("A5", 16)) # Output: 165
the float() function is used to # Converting a string to a float
2 float()
convert a given value into a print(float("3.14"))
floating-point number (i.e., a # Output: 3.14
decimal number).
Syntax:
# Converting an integer to a float
float(x)
print(float(42))
x: The value to be converted
# Output: 42.0
to a floating-point number.
This can be a string, integer,
or any object that can be # Converting a string in scientific notation to a float
converted to a float. print(float("6.022e23"))
# Output: 6.022e+23
The ord() function in Python print(ord('A')) # Output: 65
3 ord()
returns an integer representing print(ord('a')) # Output: 97
the Unicode code point of the print(ord('€')) # Output: 8364
given Unicode character.
Syntax
ord(‘character’)
This function is to convert print(hex(255)) # Output: '0xff'
4 hex()
integer to hexadecimal print(hex(100)) # Output: '0x64'
string. print(hex(16)) # Output: '0x10'
Syntax:
hex(x)
x is an integer to be converted
to a hexadecimal string.
print(oct(255)) # Output: '0o377'
5 oct()
: This function is to convert print(oct(100)) # Output: '0o144'
integer to octal string.
print(oct(16)) # Output: '0o20'

Syntax:
oct(x)

where x is an integer to be
converted to an octal string.

In Python, the tuple() function # Creating a tuple from a list


6 tuple() is used to create a tuple object.
my_list = [1, 2, 3]
A tuple is an immutable
sequence data type that can my_tuple = tuple(my_list)
contain a collection of print(my_tuple)
elements, which may be of # Output: (1, 2, 3)
different data types. Tuples
are similar to lists, but unlike
lists, tuples cannot be # Creating a tuple from a string
modified after creation. my_string = "hello"
Syntax: my_tuple = tuple(my_string)
tuple(iterable) print(my_tuple)
Where iterable is an iterable # Output: ('h', 'e', 'l', 'l', 'o')
object (such as a list, string, or
another tuple) whose
elements will be used to # Creating a tuple directly
create the tuple. my_tuple = tuple([4, 5, 6])
print(my_tuple)
# Output: (4, 5, 6)
In Python, the set() function is # Creating a set from a list
7 set() used to create a set object. A
my_list = [1, 2, 3, 2, 3, 4]
set is an unordered collection
of unique elements. Sets are my_set = set(my_list)
mutable, meaning you can print(my_set)
add or remove elements from # Output: {1, 2, 3, 4}
them, but they cannot contain
duplicate elements.
Syntax: # Creating a set from a string
set(iterable) my_string = "hello"
my_set = set(my_string)
Where iterable is an iterable print(my_set)
object (such as a list, tuple,
# Output: {'h', 'e', 'l', 'o'}
string, or another set) whose
elements will be used to
create the set. # Creating a set directly
my_set = set([4, 5, 6, 4, 5])
print(my_set)
# Output: {4, 5, 6}
In Python, the list() function # Creating a list from a tuple
8 list() is used to create a list object.
my_tuple = (1, 2, 3)
Lists are ordered collections
of elements, which can be of my_list = list(my_tuple)
different data types. Lists are print(my_list)
mutable, meaning you can # Output: [1, 2, 3]
modify them by adding,
removing, or modifying
elements after creation. # Creating a list from a string
Syntax: my_string = "hello"
list(iterable)
my_list = list(my_string)
Where iterable is an iterable print(my_list)
object (such as a tuple, string, # Output: ['h', 'e', 'l', 'l', 'o']
or another list) whose
elements will be used to
create the list. # Creating a list directly
my_list = list([4, 5, 6])
print(my_list)
# Output: [4, 5, 6]
In Python, the dict() function 1. Passing keyword arguments:
9 dict() is used to create a new
my_dict = dict(key1=value1, key2=value2 ,
dictionary object.
Dictionaries are unordered key3=value3)
collections of key-value pairs,
where each key is associated 2. Passing an iterable (e.g., a list of tuples):
with a value. Dictionaries are
my_dict = dict([(key1, value1), (key2, value2), (key3,
mutable, meaning you can
modify them by adding, value3)])
removing, or modifying key-
value pairs after creation.
Syntax:

dict(**kwargs) Code:
# kwargs stands for keyword # Using keyword arguments
arguments
my_dict = dict(name='John', age=30, city='New
dict(iterable) York')
# iterable can be another print(my_dict)
dictionary, or an iterable of # Output: {'name': 'John', 'age': 30, 'city': 'New
key-value pairs (e.g., a list of York'}
tuples)
# Using an iterable of key-value pairs
my_list = [('name', 'John'), ('age', 30), ('city', 'New
York')]
my_dict = dict(my_list)
print(my_dict)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}
In Python, the str() function is # Converting an integer to a string
10 str() used to convert a given value
print(str(123)) # Output: '123'
into a string

Syntax: # Converting a float to a string


str(object) print(str(3.14)) # Output: '3.14'

# Converting a boolean to a string


print(str(True)) # Output: 'True'

# Converting a list to a string


print(str([1, 2, 3])) # Output: '[1, 2, 3]'
In Python, the complex() # Creating a complex number from real and
11 complex() function is used to create a imaginary parts
complex number object.
Complex numbers are z = complex(3, 4)
numbers that have both a real print(z) # Output: (3+4j)
part and an imaginary part.
They are represented as a + bj,
# Creating a complex number from real part
where a is the real part, b is
the imaginary part, and j is the only
imaginary unit, z = complex(5)
print(z) # Output: (5+0j)
Synatx:
complex(real, imag)
# Creating a complex number from
imaginary part only
z = complex(imag=2)
print(z) # Output: 2j

# Creating a complex number from a string


z = complex('6+7j')
print(z) # Output: (6+7j)
Q. Explain how to use user defined function in python with example.
4.2 User defined functions: Function definition, function calling, function arguments and
parameter passing, Return statement, Scope of Variables: Global variable and Local
variable.

the user can create its functions which can be called user-defined functions.

In python, we can use def keyword to define the function. The syntax to define a function in python is
given below.

def my_function():
function code
return
<expression>

Function calling

In python, a function must be defined before the function calling otherwise the python interpreter
gives an error. Once the function is defined, we can call it from another function or the python
prompt. To call the function, use the function name followed by the parentheses.

A simple function that prints the message "Hello Word" is given below.

def hello_world():

print("hello world")

hello_world()

Output:

hello world
Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses.

def hi(name):
print(name)

hi("MMP")
Output:
MMP

def my_function(fname, lname): print(fname + "


" + lname)

my_function("Purva","Paw
ar") Output:
Purva Pawar

Q. Explain Arbitrary Arguments, *args

If you do not know how many arguments that will be passed into your function, add a * before
the parameter name in the function definition.

If the number of arguments is unknown, add a * before the


parameter name: def my_function(*kids):
print("The youngest child is " + kids[1])

my_function("purva","sandesh","jiya
nsh") Output
The youngest child is sandesh

If the number of keyword arguments is unknown, add a double ** before the


parameter name: def my_function(**kid):
print("Her last name is " + kid["lname"]) my_function(fname = "nitu", lname =

"mini")

Output
Her last name is mini
Q. How to set Default Parameter Value

If we call the function without argument, it uses the default value:

def my_function(country = "Norway"):


print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Output
I am from
Sweden I am
from India
I am from
Norway I am
from Brazil

Q. How to pass List as an Argument

def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana",

"cherry"] my_function(fruits)
Outp
ut
apple
bana
na
cherr
y
Q. Explain Return statement
def my_function(x):

return 5 * x

print(my_function(3)) print(my_function(5))

print(my_function(9))

Output

15

25

45

Q. Explain Scope of Variables: Global variable and Local variable.

Local variable

A variable created inside a function belongs to the local scope of that function, and can only
be used inside that function.
A variable created inside a function is available inside that
function:
def myfunc():
x = 300
print(x)

myfunc
()
Output

300

Global variable

Global variables are available from within any scope, global and local.
A variable created outside of a function is global and can be used
by anyone: x = 300

def myfunc():
print(x)

myfunc()
print(x)
Output 300

300

The global keyword makes the

variable global. def myfunc():

global x

x = 300

myfunc()
print(x)

Outpu
t 300
Q. Explain Modules and How to define modle
Shown below is a Python script containing the definition of function.
SayHello()
It is saved as hello.py.
Example: hello.py

def SayHello(name):
print("Hello {}! How are you?".format(name))
return

importing modules
>>> import hello

>>> hello.SayHello("purva")

Output

Hello purva! How are you?

importing objects from modules


To import only parts from a module, by using the from keyword.

The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name":
"John",
"age": 36,
"country": "Norway"
}

Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Output:
36
Explain Python built-in modules(e.g. Numeric and Mathematical module, Functional
programming module)
Python - Math Module

The math module in Python provides various mathematical functions.

1. Constants:
• math.pi: Represents the mathematical constant π (3.14159...).
• math.e: Represents the mathematical constant e (2.71828...).
• math.inf: Represents positive infinity.
• math.nan: Represents a "Not a Number" value.
2. Basic mathematical functions:
• math.sqrt(x): Returns the square root of x.
• math.pow(x, y): Returns x raised to the power of y.
• math.exp(x): Returns the exponential of x (e^x).
• math.log(x[, base]): Returns the natural logarithm of x (to the given base if specified).
• math.log10(x): Returns the base-10 logarithm of x.
• math.ceil(x): Returns the ceiling of x (the smallest integer greater than or equal to x).
• math.floor(x): Returns the floor of x (the largest integer less than or equal to x).
• math.trunc(x): Returns the truncated integer value of x.
• math.degrees(x): Converts angle x from radians to degrees.
• math.radians(x): Converts angle x from degrees to radians.
3. Trigonometric functions:
• math.sin(x), math.cos(x), math.tan(x): Returns the sine, cosine, and tangent of x (in radians).
• math.asin(x), math.acos(x), math.atan(x): Returns the arcsine, arccosine, and arctangent of x
(result in radians).
• math.atan2(y, x): Returns the arc tangent of y/x in radians, taking into account the signs of
both arguments to determine the quadrant of the result.
4. Hyperbolic functions:
• math.sinh(x), math.cosh(x), math.tanh(x): Returns the hyperbolic sine, cosine, and tangent
of x.
5. Miscellaneous functions:
• math.factorial(x): Returns the factorial of x.
• math.gcd(a, b): Returns the greatest common divisor of the integers a and b.
Namespace and Scoping.

• A namespace is a mapping from names to objects.


• Python implements namespaces in the form of dictionaries.
• It maintains a name-to-object mapping where names act as keys and the objects as values.
• Multiple namespaces may have the same name but pointing to a different variable.

• A scope is a textual region of a Python program where a namespace is directly accessible.

➢ Local scope

➢ Non-local scope

➢ Global scope

➢ Built-ins scope
1. The local scope. The local scope is determined by whether you are in a class/function
definition or not. Inside a class/function, the local scope refers to the names defined inside
them. Outside a class/function, the local scope is the same as the global scope.

2. The non-local scope. A non-local scope is midways between the local scope and the
global scope, e.g. the non-local scope of a function defined inside another function is the
enclosing function itself.

3. The global scope. This refers to the scope outside any functions or class definitions. It
also known as the module scope.

4. The built-ins scope. This scope, as the name suggests, is a scope that is built into Python.
While it resides in its own module, any Python program is qualified to call the names
defined here without requiring special access.

# var1 is in the global


namespace var1 = 5
def some_func():

# var2 is in the local


namespace var2 = 6
def some_inner_func():

# var3 is in the nested


local # namespace
var3 = 7
Python Packages : Introduction
Python has packages for directories and modules for files. As a directory can contain sub-
directories and files, a Python package can have sub-packages and modules.

init .py in order for Python to consider it as a package. This file can
A directory must contain a file named
be left empty but we generally place the initialization code for that package in this file.

Steps:
• First create folder game.
• Inside it again create folder sound.
• Inside sound folder create load.py file.
• Inside sound folder create pause.py file.
• Inside sound folder create play.py file.
• Import package game and subpackage sound(files:load,pause,play)
Q. How to import module from a package
import game.sound.load
Now if this module contains a function named
load(), we must use the full name to reference it.
game.sound.load.load()

Q. Explain Math package:


In Python, the math module is not referred to as a "package," but rather as a "module." However, it
serves a similar purpose as a package in that it contains a collection of related functions and constants
for mathematical operations.

The math Module:


Purpose: Provides mathematical functions and constants for various mathematical operations.

Importing: You can import it using the import statement:


>>> import math
>>>math.pi
3.1415926535897
93

Example:

import math

# Calculate the square root of a number


print(math.sqrt(25)) # Output: 5.0

# Calculate the value of e raised to the power of 2


print(math.exp(2)) # Output: 7.38905609893065

# Calculate the factorial of a number


print(math.factorial(5)) # Output: 120

# Convert radians to degrees


print(math.degrees(math.pi/2)) # Output: 90.0

# Calculate the sine of an angle in radians


print(math.sin(math.radians(30))) # Output: 0.49999999999999994 (approximately 0.5)
Q. Explain NumPy in pythin

It is a python library used for working with arrays.


NumPy stands for Numerical Python.

Why Use NumPy ?

In Python we have lists that serve the purpose of arrays, but they are slow to

process. NumPy aims to provide an array object that is up to 50x faster that

traditional Python lists.

• Install it using this command:

C:\Users\Your Name>pip install numpy

Import NumPy

Use a tuple to create a NumPy array:

0-D Arrays

0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.

Create a 0-D array with value 42


1-D Arrays

An array that has 0-D arrays as its elements is called uni-dimensional or

1-D array. These are the most common and basic arrays.

Create a 1-D array containing the values 1,2,3,4,5:

Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:

Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and 4,5,6:
Q.Explain Matplotlib Package in Python
Matplotlib is a powerful plotting library in Python that offers a wide range of capabilities for
creating static, interactive, and animated plots. Its flexibility, ease of use, and extensive
documentation make it a popular choice among data scientists, researchers, engineers, and
students for visualizing data and communicating results effectively.

is a plotting library for the Python programming language and its numerical mathematics
extension NumPy.
It provides an object-oriented API for embedding plots into applications using general-purpose
GUI toolkits like Tkinter, wxPython, Qt, or GTK+SciPy makes use of Matplotlib.

Installation:
You can install Matplotlib using pip:

pip install matplotlib

Example
to create a simple line plot using Matplotlib:

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Create a new figure and axis


fig, ax = plt.subplots()

# Plot the data


ax.plot(x, y, marker='o', linestyle='-')

# Customize the plot


ax.set_title('Line Plot Example')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.grid(True)

# Show the plot


plt.show()

Q.Explain Pandas in Python


It is used for data manipulation, analysis and cleaning. Python pandas is well suited for
different kinds of data, such as:

• Tabular data with heterogeneously-typed columns


• Ordered and unordered time series data
• Arbitrary matrix data with row & column labels
• Any other form of observational or statistical data sets

You might also like