Unit 4 Python
Unit 4 Python
Syntax:
oct(x)
where x is an integer to be
converted to an octal string.
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
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
Arguments are specified after the function name, inside the parentheses.
def hi(name):
print(name)
hi("MMP")
Output:
MMP
my_function("Purva","Paw
ar") Output:
Purva Pawar
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.
my_function("purva","sandesh","jiya
nsh") Output
The youngest child is sandesh
"mini")
Output
Her last name is mini
Q. How to set Default Parameter Value
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
def my_function(food):
for x in food:
print(x)
"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
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
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
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name":
"John",
"age": 36,
"country": "Norway"
}
print (person1["age"])
Output:
36
Explain Python built-in modules(e.g. Numeric and Mathematical module, Functional
programming module)
Python - Math Module
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.
➢ 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.
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()
Example:
import math
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
Import NumPy
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
1-D array. These are the most common and basic arrays.
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:
Example
to create a simple line plot using Matplotlib:
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]