0% found this document useful (0 votes)
6 views

python 3

The document provides an overview of defining and calling functions in Python, including function parameters, return values, and variable scopes (local, global, nonlocal). It also covers error handling, debugging techniques, and introduces Python's lambda functions and modules for code organization. Additionally, it discusses exception handling and the differences between errors and exceptions, along with examples to illustrate these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

python 3

The document provides an overview of defining and calling functions in Python, including function parameters, return values, and variable scopes (local, global, nonlocal). It also covers error handling, debugging techniques, and introduces Python's lambda functions and modules for code organization. Additionally, it discusses exception handling and the differences between errors and exceptions, along with examples to illustrate these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Defining and Calling Function in Python Programming

In Python, a function is a block of organized, reusable code that performs a


specific task. Defining a function involves specifying its name, parameters
(inputs), and the code it executes. Calling a function means executing that
code.
Defining a Function
A function is defined using the def keyword, followed by the function name,
parentheses (), and a colon :. The code block within the function is
indented.
Example
def greet(name):
"""This function greets the person passed in as a parameter."""
print(f"Hello, {name}!")

Calling a Function
To call a function, use its name followed by parentheses (). If the function
expects arguments, they are passed within the parentheses.
Example
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!

Function with Return Value


Functions can return values using the return statement.
Example
def add(x, y):
"""This function returns the sum of x and y."""
return x + y

result = add(5, 3)
print(result) # Output: 8

Function without Return Value


If a function doesn't have a return statement, it implicitly returns None.
Example
def say_hello():
print("Hello!")
result = say_hello() # Output: Hello!
print(result) # Output: None

Function Arguments
Functions can accept arguments, which are values passed to the function
when it is called. Arguments can be positional or keyword-based.
Example
def describe_person(name, age, city="Unknown"):
"""This function describes a person."""
print(f"Name: {name}, Age: {age}, City: {city}")

describe_person("Charlie", 30) # Output: Name: Charlie, Age: 30,


City: Unknown
describe_person("Diana", 25, city="New York") # Output: Name: Diana,
Age: 25, City: New York
describe_person(age=28, name="Eve") # Output: Name: Eve, Age: 28,
City: Unknown

Python Variable Scope


In Python, we can declare variables in three different scopes: local scope,
global, and nonlocal scope.
A variable scope specifies the region where we can access a variable. For
example,
def add_numbers():
sum = 5 + 4

Here, the sum variable is created inside the function, so it can only be
accessed within it (local scope). This type of variable is called a local
variable.
Based on the scope, we can classify Python variables into three types:
1. Local Variables
2. Global Variables
3. Nonlocal Variables

Python Local Variables


When we declare variables inside a function, these variables will have a
local scope (within the function). We cannot access them outside the
function.
These types of variables are called local variables. For example,
def greet():

# local variable
message = 'Hello'

print('Local', message)

greet()

# try to access message variable


# outside greet() function
print(message)
Run Code
Output
Local Hello
NameError: name 'message' is not defined

Here, the message variable is local to the greet() function, so it can only
be accessed within the function.
That's why we get an error when we try to access it outside
the greet() function.
To fix this issue, we can make the variable named message global.

Python Global Variables


In Python, a variable declared outside of the function or in global scope is
known as a global variable. This means that a global variable can be
accessed inside or outside of the function.
Let's see an example of how a global variable is created in Python.
# declare global variable
message = 'Hello'

def greet():
# declare local variable
print('Local', message)

greet()
print('Global', message)
Run Code
Output
Local Hello
Global Hello

This time we can access the message variable from outside of


the greet() function. This is because we have created
the message variable as the global variable.

# declare global variable


message = 'Hello'

Now, message will be accessible from any scope (region) of the program.

Python Nonlocal Variables


In Python, the nonlocal keyword is used within nested functions to
indicate that a variable is not local to the inner function, but rather belongs
to an enclosing function’s scope.
This allows you to modify a variable from the outer function within the
nested function, while still keeping it distinct from global variables.
# outside function
def outer():
message = 'local'

# nested function
def inner():

# declare nonlocal variable


nonlocal message

message = 'nonlocal'
print("inner:", message)

inner()
print("outer:", message)

outer()
Run Code
Output
inner: nonlocal
outer: nonlocal

In the above example, there is a nested inner() function.


The inner() function is defined in the scope of another function outer().
We have used the nonlocal keyword to modify the message variable from
the outer function within the nested function.

Python Lambda/Anonymous Function


In Python, a lambda function is a special type of function without the
function name. For example,
lambda : print('Hello World')

Here, we have created a lambda function that prints 'Hello World'.


Before you learn about lambdas, make sure to know about Python
Functions.
Python Lambda Function Declaration
We use the lambda keyword instead of def to create a lambda function.
Here's the syntax to declare the lambda function:
lambda argument(s) : expression

Here,
 argument(s) - any value passed to the lambda function
 expression - expression is executed and returned
Let's see an example,
greet = lambda : print('Hello World')

Here, we have defined a lambda function and assigned it to


the variable named greet.
To execute this lambda function, we need to call it. Here's how we can call
the lambda function
# call the lambda
greet()

The lambda function above simply prints the text 'Hello World'.

Note: This lambda function doesn't have any argument.

Example: Python Lambda Function


# declare a lambda function
greet = lambda : print('Hello World')

# call lambda function


greet()

# Output: Hello World


Run Code
In the above example, we have defined a lambda function and assigned it
to the greet variable.
When we call the lambda function, the print() statement inside the lambda
function is executed.
Python Modules
As our program grows bigger, it may contain many lines of code. Instead of
putting everything in a single file, we can use modules to separate codes in
separate files as per their functionality. This makes our code organized and
easier to maintain.
Module is a file that contains code to perform a specific task. A module may
contain variables, functions, classes etc. Let's see an example,
Let us create a module. Type the following and save it as example.py.

# Python Module addition

def add(a, b):

result = a + b
return result

Here, we have defined a function add() inside a module named example.


The function takes in two numbers and returns their sum.

Import modules in Python


We can import the definitions inside a module to another module or the
interactive interpreter in Python.
We use the import keyword to do this. To import our previously defined
module example, we type the following in the Python prompt.

import example

This does not import the names of the functions defined in example directly
in the current symbol table. It only imports the module
name example there.
Using the module name we can access the function using the
dot . operator. For example:

example.add(4,5) # returns 9

Import Python Standard Library Modules


The Python standard library contains well over 200 modules. We can
import a module according to our needs.
Suppose we want to get the value of pi, first we import the math module
and use math.pi. For example,
# import standard math module
import math

# use math.pi to get value of pi


print("The value of pi is", math.pi)
Run Code
Output
The value of pi is 3.141592653589793

Importing Built-in Modules


Python provides many built-in modules that can be imported directly
without installation. These modules offer ready-to-use functions for
various tasks, such as random number generation, math operations and
file handling.
import random

# Generate a random number between 1 and 10


res = random.randint(1, 10)
print("Random Number:", res)

Output
Random Number: 9
Explanation:
 import random brings in Python’s built-in random module.
 random.randint(1, 10) generates a random integer between 1 and 10.

Debugging and Errors Handling


Errors and Debugging
Debugging is the process of identifying and fixing errors in a program.
Errors in Python can be broadly classified into two categories:
 Syntax Errors: These are errors that occur when the code is not
written according to the rules of the Python language. For example,
forgetting a colon at the end of an if statement.
 Runtime Errors: These are errors that occur while the program is
running. They can be due to logical mistakes in the code or unexpected
input.

Types of Errors

Syntax Errors in Python


When the proper syntax of the language is not followed then a syntax
error is thrown.
Example: It returns a syntax error message because after the if statement
a colon: is missing. We can fix this by writing the correct syntax.
# initialize the amount variable
amount = 10000

# check that You are eligible to


# purchase Dsa Self Paced or not
if(amount>2999)
print("You are eligible to purchase Dsa Self Paced")

Output:

Python Logical Errors (Exception)


A logical error in Python, or in any programming language, is a type of
bug that occurs when a program runs without crashing but produces
incorrect or unintended results. Logical errors are mistakes in the
program’s logic that lead to incorrect behavior or output, despite the
syntax being correct.
Characteristics of Logical Errors
1. No Syntax Error: The code runs successfully without any syntax
errors.
2. Unexpected Output: The program produces output that is different
from what is expected.
3. Difficult to Detect: Logical errors can be subtle and are often harder to
identify and fix compared to syntax errors because the program
appears to run correctly.
4. Varied Causes: They can arise from incorrect assumptions, faulty
logic, improper use of operators, or incorrect sequence of instructions.

Example of a Logical Error


Consider a simple example where we want to compute the average of a
list of numbers:
numbers = [10, 20, 30, 40, 50]
total = 0

# Calculate the sum of the numbers


for number in numbers:
total += number

# Calculate the average (this has a logical error)


average = total / len(numbers) - 1

print("The average is:", average)

Analysis
 Expected Output: The average of the numbers [10, 20, 30, 40,
50] should be 30.
 Actual Output: The program will output The average is: 29.0.

Cause of Logical Error


The logical error is in the calculation of the average:
average = total / len(numbers) - 1
Instead, it should be:
average = total / len(numbers)
The incorrect logic here is the subtraction of 1, which results in a wrong
average calculation.

Runtime Errors:
 A runtime error in a program is an error that occurs while the program
is running after being successfully compiled.
 Runtime errors are commonly called referred to as “bugs” and are often
found during the debugging process before the software is released.
 When runtime errors occur after a program has been distributed to the
public, developers often release patches, or small updates designed to
fix the errors.
 Anyone can find the list of issues that they might face if they are a
beginner
 While solving problems on online platforms, many run time errors can
be faced, which are not clearly specified in the message that comes
with them. There are a variety of runtime errors that occur such
as logical errors, Input/Output errors, undefined object
errors, division by zero errors, and many more.

Basic Debugging Techniques


Some common techniques to debug Python code include:
 Print Statements: Using print() to display the values of variables at
different points in the code.
 Using a Debugger: Tools like the Python Debugger (PDB) allow you to
step through the code, inspect variables, and understand the flow of
execution.
 Reading Error Messages: Python provides detailed error messages
that can help pinpoint the location and cause of an error.

Python can be used for various dubbing techniques and tools,


including audio extraction, transcription, translation, text-to-speech, and
audio merging. Libraries like pydub, SpeechRecognition, gTTS, and
various translation APIs can be leveraged for these tasks. AI-powered
dubbing tools are also emerging, offering features like voice cloning and lip-
syncing.
Dubbing Techniques and Tools in Python:
1. 1. Audio Extraction:
Use libraries like pydub or FFmpeg (via Python) to extract audio from
video files.
2. 2. Transcription:
Utilize speech recognition libraries like SpeechRecognition or Whisper to
convert audio to text.
3. 3. Translation:
Employ translation APIs like Google Translate API or DeepL API to
translate the transcribed text into the target language.
4. 4. Text-to-Speech (TTS):
Generate synthesized speech using libraries like gTTS or pyttsx3 to create
the dubbed audio.
5. 5. Audio Merging:
Combine the original background audio with the dubbed audio track using
pydub or other audio manipulation libraries.
6. 6. Lip Syncing:
Use libraries like lipsync or Wav2Lip to synchronize the dubbed audio with
the character's lip movements.
7. 7. AI-Powered Dubbing:
Leverage AI models for tasks like voice cloning and automatic dubbing,
using services like ElevenLabs or Dubverse.

Key Python Libraries and Tools:


 pydub: For audio manipulation, including extraction, segmentation, and
merging.
 SpeechRecognition: For speech recognition.
 gTTS: For text-to-speech.
 pyttsx3: Another text-to-speech library.
 ElevenLabs API: For voice cloning and dubbing.
 Dubverse: An AI-powered dubbing tool.
 FFmpeg: For video and audio manipulation (can be used via Python).

Python Exception Handling


Python Exception Handling handles errors that occur during the execution
of a program. Exception handling allows to respond to the error, instead of
crashing the running program. It enables you to catch and manage errors,
making your code more robust and user-friendly. Let’s look at an example:
Handling a Simple Exception in Python
Exception handling helps in preventing crashes due to errors. Here’s a
basic example demonstrating how to catch an exception and handle it
gracefully:
# Simple Exception Handling Example
n = 10
try:
res = n / 0 # This will raise a ZeroDivisionError

except ZeroDivisionError:
print("Can't be divided by zero!")

Output
Can't be divided by zero!
Explanation: In this example, dividing number by 0 raises
a ZeroDivisionError. The try block contains the code that might cause an
exception and the except block handles the exception, printing an error
message instead of stopping the program.

Difference Between Exception and Error


 Error: Errors are serious issues that a program should not try to
handle. They are usually problems in the code’s logic or configuration
and need to be fixed by the programmer. Examples include syntax
errors and memory errors.
 Exception: Exceptions are less severe than errors and can be handled
by the program. They occur due to situations like invalid input, missing
files or network issues.

try, except, else and finally Blocks


 try Block: try block lets us test a block of code for errors. Python will
“try” to execute the code in this block. If an exception occurs, execution
will immediately jump to the except block.
 except Block: except block enables us to handle the error or
exception. If the code inside the try block throws an error, Python jumps
to the except block and executes it. We can handle specific exceptions
or use a general except to catch all exceptions.
 else Block: else block is optional and if included, must follow all except
blocks. The else block runs only if no exceptions are raised in the try
block. This is useful for code that should execute if the try block
succeeds.
 finally Block: finally block always runs, regardless of whether an
exception occurred or not. It is typically used for cleanup operations
(closing files, releasing resources).
Example:
try:
n = 0
res = 100 / n

except ZeroDivisionError:
print("You can't divide by zero!")

except ValueError:
print("Enter a valid number!")

else:
print("Result is", res)

finally:
print("Execution complete.")

Output
You can't divide by zero!
Execution complete.
Explanation:
 try block asks for user input and tries to divide 100 by the input
number.
 except blocks handle ZeroDivisionError and ValueError.
 else block runs if no exception occurs, displaying the result.
 finally block runs regardless of the outcome, indicating the completion
of execution.

You might also like