0% found this document useful (0 votes)
5 views70 pages

Python Programming Course Materials

Python program

Uploaded by

amal40495
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)
5 views70 pages

Python Programming Course Materials

Python program

Uploaded by

amal40495
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

Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

MODULE 2

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 1


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Introduction to features and applications of python

Python is a high-level, interpreted programming language that is versatile, easy to


learn, and widely used for a variety of applications. Some of the key features and
applications of Python include:

Features:

1. Easy to learn: Python has a simple and intuitive syntax that makes it easy to
learn for beginners, as well as for experienced programmers.
2. Object-oriented: Python supports object-oriented programming (OOP)
concepts such as classes, objects, inheritance, and polymorphism.
3. Interpreted: Python is an interpreted language, which means that there is no
need to compile the code before running it.
4. Dynamic: Python is a dynamically-typed language, which means that variables
are not required to be declared before use.
5. Extensive libraries: Python has a large collection of libraries that offer a wide
range of functionality, including data analysis, machine learning, web
development, and more.
6. Cross-platform: Python can be run on different operating systems such as
Windows, macOS, and Linux.

Applications:

1. Web development: Python is widely used for web development, thanks to its
popular web frameworks such as Django and Flask.
2. Data analysis and visualization: Python has powerful libraries such as NumPy,
Pandas, and Matplotlib that are widely used for data analysis, processing, and
visualization.
3. Machine learning: Python has a rich ecosystem of machine learning libraries
such as scikit-learn, TensorFlow, and PyTorch that are used for building and
training machine learning models.
4. Scripting: Python is often used for scripting tasks such as automation, file
handling, and system administration.
5. Game development: Python can be used to develop games using popular
game engines such as Pygame and Panda3D.
6. Scientific computing: Python is widely used for scientific computing and
research in fields such as physics, chemistry, and biology.

In summary, Python is a versatile and powerful programming language that is used


in a variety of applications and industries. Its ease of use, extensive libraries, and
cross-platform compatibility make it a popular choice for programmers and
developers.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 2


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Python Versions
Python is an evolving language with different versions, each with its unique features
and improvements. Here are the most commonly used versions of Python:

1. Python 2.x: This version was the first major release of Python, and it has been
around for over a decade. Python 2.x was the standard version until Python 3.x
was introduced. However, Python 2.x is no longer supported and has reached
its end of life.
2. Python 3.x: Python 3.x was introduced in 2008, and it's the current standard
version of Python. It comes with several improvements and new features
compared to Python 2.x, including better Unicode support, improved print
function, and better syntax for exceptions. Python 3.x is backward-
incompatible with Python 2.x, meaning that the code written in Python 2.x
may need to be modified to run on Python 3.x.
3. Python 3.10: Python 3.10 is the latest major version of Python, released in
October 2021. It comes with new features, including structural pattern
matching, improved error messages, and improved time zone handling.
4. Other Versions: In addition to the above, there are other versions of Python,
including Jython, IronPython, and PyPy. Jython is an implementation of Python
that runs on the Java Virtual Machine (JVM), IronPython runs on the .NET
framework, while PyPy is a faster implementation of Python that uses just-in-
time compilation (JIT).

It's worth noting that different versions of Python may have different syntax and
functionalities. Therefore, it's essential to choose the appropriate version for your
project and ensure compatibility with other libraries and frameworks that you may be
using.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 3


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Installation of python
To install Python, you can follow these steps:

1. Go to the official Python website: [Link]


2. Click on the "Download" button for the latest version of Python (currently
Python 3.10.0).
3. Select the appropriate version for your operating system (Windows, Mac, or
Linux).
4. Click on the installer file and follow the installation wizard.
5. On the "Customize installation" page, make sure to check the "Add Python to
PATH" option, which will allow you to run Python from the command line.
6. Continue following the installation wizard until Python is successfully installed
on your computer.
7. After installation, you can open a terminal or command prompt and type
"python" to launch the Python interpreter and start coding.

Alternatively, you can use a package manager like Homebrew (for Mac) or apt-get
(for Linux) to install Python. In that case, you can simply type the appropriate
command in the terminal to install Python.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 4


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Python Command Line mode and Python IDEs;


Python can be run and executed in different ways, including the command-line mode
and integrated development environments (IDEs). Here's a brief introduction to both:

1. Command Line Mode: The Python command-line mode, also known as the
interactive mode, allows you to write and execute Python code line by line in
the terminal or command prompt. To access the Python command-line mode,
simply open the terminal or command prompt and type "python" or
"python3" (depending on the version you have installed). You will see the
Python prompt (>>>) indicating that you are in the interactive mode. You can
then start writing Python code and see the output immediately after pressing
the Enter key.
2. IDEs: Integrated development environments (IDEs) provide a more
comprehensive and user-friendly environment for developing and running
Python code. Some popular Python IDEs include PyCharm, Visual Studio Code,
Spyder, and IDLE. IDEs provide features such as code completion, debugging,
syntax highlighting, and easy access to documentation and libraries. IDEs are
also useful for managing large projects that consist of multiple files and
require complex dependencies.

Both the command-line mode and IDEs have their advantages and disadvantages,
and the choice depends on personal preference and the nature of the project. For
simple and quick Python code execution, the command-line mode may be sufficient,
while IDEs are more suitable for large and complex projects that require more
advanced features and tools.

Simple Python Program.

Certainly! Here's a simple Python program that asks the user for their name and
greets them:

Python code
name = input("What is your name? ")
print("Hello, " + name + "!")

When you run this program, it will prompt the user to enter their name. Once the
user enters their name and hits enter, the program will print out a personalized
greeting.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 5


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Identifiers in python
In Python, an identifier is a name that is used to identify a variable, function, class,
module, or other object in a Python program. Identifiers follow some basic rules:

1. An identifier can only contain alphanumeric characters (a-z, A-Z, 0-9) and
underscores (_).
2. An identifier cannot start with a digit.
3. Python identifiers are case sensitive. This means that "hello" and "Hello" are
two different identifiers.
4. There are some reserved words that cannot be used as identifiers, such as if,
else, for, and while.

Here are some examples of valid and invalid Python identifiers:

Valid Identifiers:

o my_variable
o myVariable
o MY_VARIABLE
o my_function
o myClass

Invalid Identifiers:

o 1myvariable
o my-variable
o my variable
o if
o else

It's important to choose meaningful and descriptive names for identifiers to make your code
easier to understand and maintain.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 6


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Keywords in python

In Python, keywords are reserved words that have special meanings and purposes in
the language. These words cannot be used as identifiers (variable names, function
names, etc.) because they are already used for specific programming tasks.

Here is a list of the current Python keywords (as of Python 3.10):

False class from or None continue

finally and def global pass break

for not try lambda as if

return while del import with elif

assert else in yield async await

You can see that these words are used for a variety of tasks, such as creating and
defining functions and classes, controlling program flow with conditional statements
(if, else, and elif), and looping with for and while loops.

It's important to avoid using these keywords as variable names or other identifiers in
your program, because doing so can cause errors or unexpected behaviour.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 7


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Statements and Expressions in python

In Python, a statement is a line of code that performs an action or declares a variable.


Statements are executed one by one in the order they appear in a program.
Examples of statements in Python include if statements, for loops, while loops,
function definitions, variable assignments, and class definitions.

An expression, on the other hand, is a piece of code that returns a value. It can be a
single value, a variable, or a combination of values and operators. Expressions can be
used within statements, but they are not statements themselves. Examples of
expressions in Python include arithmetic operations such as addition and subtraction,
function calls, and variable references.

Here are some examples of statements and expressions in Python:

Statements:

x=5 # variable assignment

if x > 0: # if statement

print("Positive number")

for i in range(5): # for loop statement

print(i)

Expressions:

2+3 # addition expression that returns the value 5

len("hello") # function call expression that returns the length of the string "hello"

x>0 # comparison expression that returns a boolean value

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 8


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Variables in python

In Python, a variable is a name that refers to a value. Variables are used to store
values that can be used later in the program. Python is a dynamically-typed
language, which means that the data type of a variable is determined at runtime,
based on the value that is assigned to it.

In Python, you can assign a value to a variable using the equals sign (=). For example,
to assign the value 10 to a variable called "x", you would write:

x = 10

After this assignment, the variable "x" will refer to the value 10. You can then use the
variable "x" in expressions and statements throughout your program.

Variables in Python can have any name that is a valid identifier. An identifier is a
name that conforms to certain rules, such as not starting with a number and not
containing spaces. For example, the following are all valid variable names in Python:

age

name

my_var

x1

It's a convention in Python to use lowercase letters and underscores to separate


words in variable names, and to use descriptive names that indicate the purpose of
the variable.

You can also assign different types of values to variables in Python, such as strings,
numbers, or Boolean values. The data type of the variable will be determined based
on the value that is assigned to it. For example, the following code creates three
variables of different data types:

x = 10 # x is an integer

y = "hello" # y is a string

z = True # z is a Boolean value

You can also assign the same value to multiple variables at once by separating the variable
names with commas:

a, b, c = 1, 2, 3

After this assignment, the variable "a" will refer to the value 1, "b" will refer to the value 2,
and "c" will refer to the value 3.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 9


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Operators in Python are symbols or keywords that perform operations on one or


more operands (values or variables) to produce a result. Python has several
categories of operators, including arithmetic operators, comparison operators, logical
operators, assignment operators, membership operators, and identity operators.

1. Arithmetic operators: These operators perform mathematical operations on


operands, such as addition, subtraction, multiplication, division, modulo, and
exponentiation. Here are some examples:
o + # addition
- # subtraction
• # multiplication
o / # division
o % # modulo (remainder)
o ** # exponentiation
o // # floor division (quotient without remainder)

2. Comparison operators: These operators compare two values and return a


Boolean value (True or False) based on whether the comparison is true or
false. Here are some examples:
o == # equal to
o != # not equal to
➢ # greater than
o < # less than
o >= # greater than or equal to
o <= # less than or equal to

3. Logical operators: These operators perform logical operations on Boolean


values and return a Boolean result. Here are some examples:
➢ and # logical AND
➢ or # logical OR
➢ not # logical NOT

4. Assignment operators: These operators are used to assign a value to a


variable, and also perform an operation on the variable in the same statement.
Here are some examples:
➢ = # simple assignment
➢ += # increment and assign
➢ -= # decrement and assign
➢ *= # multiply and assign
➢ /= # divide and assign
➢ %= # modulo and assign
➢ **= # exponentiate and assign
➢ //= # floor divide and assign

5. Membership operators: These operators test whether a value is a member of a


sequence, such as a list, tuple, or string. Here are some examples:
➢ in # membership test
➢ not in # non-membership test

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 10


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

6. Identity operators: These operators test whether two variables refer to the
same object in memory. Here are some examples:
➢ is # identity test
➢ is not # non-identity test

These are the main categories of operators in Python. Understanding how they work and
how to use them can help you write more powerful and expressive Python code.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 11


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Precedence and Association in python

In Python, operators have a precedence level, which determines the order in which
they are evaluated in an expression. Operators with a higher precedence level are
evaluated before operators with a lower precedence level. If two operators have the
same precedence level, the evaluation order is determined by their association.

The following table shows the precedence and association of operators in Python
(from highest to lowest):

Precedence Operators Description Association


1 () Parentheses Left-to-right
2 ** Exponentiation Right-to-left

Multiplication, division, modulo, floor


3 *, /, %, // division Left-to-right

4 +, - Addition, subtraction Left-to-right

5 <, <=, >, >= Comparison operators Left-to-right


6 ==, != Equality operators Left-to-right

7 not Logical NOT Right-to-left


8 and Logical AND Left-to-right

9 or Logical OR Left-to-right

=, +=, -=, *=, /=, %=, //=,


10 **= Assignment operators Right-to-left

As an example, consider the following expression:


2 + 3 * 4 ** 2 / 6

The order of evaluation is determined by the precedence and association of the operators.
First, the exponentiation operator (**) is evaluated, followed by the multiplication operator
(*), then the division operator (/), and finally the addition operator (+). Applying the
precedence and association rules, the expression is evaluated as follows:

2 + ((3 * (4 ** 2)) / 6)

2 + ((3 * 16) / 6)

2+8

10

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 12


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

So the result of the expression is 10.

Understanding the precedence and association of operators in Python is important


for writing correct and efficient expressions. You can use parentheses to group
expressions and override the default order of evaluation if needed.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 13


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Data Types in python

In Python, every value has a specific data type. The data type determines the kind of
operations that can be performed on the value, as well as how the value is stored in
memory. Here are some of the most common data types in Python:

1. Numeric types: Numeric types are used to represent numbers. In Python, there
are three numeric types: integers, floating-point numbers, and complex
numbers.
2. Boolean type: The boolean type represents truth values, which can be either
True or False.
3. String type: The string type is used to represent text. Strings are sequences of
characters, and they can be enclosed in single or double quotes.
4. List type: The list type is used to represent sequences of values. Lists are
ordered collections of values, and they can contain values of different data
types.
5. Tuple type: Tuples are similar to lists, but they are immutable, meaning their
values cannot be changed once they are created.
6. Set type: The set type is used to represent collections of unique values. Sets
are unordered collections of values, and they can contain values of different
data types.
7. Dictionary type: The dictionary type is used to represent mappings between
keys and values. Dictionaries are unordered collections of key-value pairs, and
they can contain values of different data types.

Here are some examples of data types in Python:

➢ x=5 # integer
➢ y = 3.14 # floating-point number
➢ z = 2 + 3j # complex number
➢ b = True # boolean
➢ s = "hello" # string
➢ l = [1, 2, 3] # list
➢ t = (4, 5, 6) # tuple
➢ st = {1, 2, 3, 3, 3} # set
➢ d = {"a": 1, "b": 2} # dictionary

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 14


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Indentation; in python

In Python, indentation is used to indicate the scope or block of code for control flow
statements, functions, classes, and other structures that require grouping of
statements. Indentation is not optional in Python; it is a fundamental part of the
language syntax.

The recommended standard for indentation in Python is to use four spaces for each
level of indentation. You can use tabs instead of spaces, but it's generally not
recommended because it can cause issues with different text editors or software that
interpret tabs differently.

Here are some examples of how indentation is used in Python:

# if statement
x=5
if x > 0:
print("x is positive") # indented block of code

# for loop
for i in range(5):
print(i) # indented block of code

# function definition
def my_function():
print("This is my function") # indented block of code

# class definition
class MyClass:
def __init__(self):
self.x = 0 # indented block of code

def my_method(self):
print("This is my method") # indented block of code

Note that the first line of a compound statement ends with a colon (:) and the
following line(s) are indented to indicate the block of code that belongs to that
statement.

Indentation is one of the distinctive features of Python, and it helps to create


readable and consistent code. Therefore, it's important to be consistent with your use
of indentation and always use the same number of spaces or tabs throughout your
code.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 15


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Comments; in python

In Python, comments are used to document code and provide information to other
developers who may read your code. Comments are ignored by the Python
interpreter and have no effect on the program's execution.

There are two ways to write comments in Python:

1. Single-line comments: To write a single-line comment, start the line with the
hash character (#). Everything after the hash symbol on that line is treated as a
comment and is ignored by the Python interpreter.

Here's an example of a single-line comment in Python:

# This is a single-line comment

2. Multi-line comments: To write a multi-line comment, you can enclose the


comment text in triple quotes ("""). This creates a string literal that is not
assigned to any variable and is ignored by the Python interpreter.

Here's an example of a multi-line comment in Python:

"""
This is a multi-line comment.
It can span multiple lines and is enclosed in triple quotes.
Multi-line comments are typically used to provide a description of a function or class.
"""
It's a good practice to include comments in your code to explain what your code does, why
you made certain design decisions, or to provide instructions for other developers who may
use or modify your code in the future. However, it's important to avoid excessive
commenting that may make the code difficult to read.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 16


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Built-in Functions- Console Input and Console Output


Python has several built-in functions for console input and console output, which are
used to interact with the user in the console.

1. Console Output: The most commonly used function for console output is
print(), which is used to print the specified text or variable values to the
console. The print() function can take one or more arguments separated by
commas, and it automatically adds a newline character at the end of the
printed text.

Here's an example of using the print() function in Python:

print("Hello, world!") # prints a string to the console


x=5
y = 10
print("The sum of", x, "and", y, "is", x + y) # prints multiple values to the console

2. Console Input: The most commonly used function for console input is input(),
which is used to prompt the user to enter a value from the console. The
input() function takes an optional prompt string as an argument, which is
displayed to the user in the console before waiting for the user's input.

Here's an example of using the input() function in Python:

name = input("Enter your name: ") # prompts the user to enter a string value
age = int(input("Enter your age: ")) # prompts the user to enter an integer value
print("Your name is", name, "and you are", age, "years old.") # prints the user's input to the console

Note that the input() function always returns a string, even if the user enters a
number. If you want to convert the input to a specific data type, such as integer or
float, you can use the corresponding type casting function, such as int() or float(),
as shown in the example above.

These are the two basic functions for console input and console output in Python.
There are also many other built-in functions and libraries available in Python for
more advanced console input and output operations, such as formatting and
handling user input errors.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 17


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Type Conversions; in python

In Python, type conversion is the process of converting a value of one data type to
another data type. Python provides several built-in functions for type conversion,
including:

1. int(): This function is used to convert a value to an integer data type. It can
convert a string or a float value to an integer value.

Here's an example of using the int() function in Python:

x = int("123") # converts the string "123" to an integer value


y = int(3.14) # converts the float 3.14 to an integer value

2. float(): This function is used to convert a value to a floating-point data type.


It can convert a string or an integer value to a float value.

Here's an example of using the float() function in Python:

x = float("3.14") # converts the string "3.14" to a float value


y = float(123) # converts the integer 123 to a float value

3. str(): This function is used to convert a value to a string data type. It can
convert an integer, float, or any other data type to a string value.

Here's an example of using the str() function in Python:

x = str(123) # converts the integer 123 to a string value


y = str(3.14) # converts the float 3.14 to a string value

4. bool(): This function is used to convert a value to a boolean data type. It can
convert any value to a boolean value, with some values (such as 0, empty
strings, and None) being considered as False, and all other values being
considered as True.

Here's an example of using the bool() function in Python:

4. bool(): This function is used to convert a value to a boolean data type. It can
convert any value to a boolean value, with some values (such as 0, empty
strings, and None) being considered as False, and all other values being
considered as True.

Here's an example of using the bool() function in Python:

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 18


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

x = bool(0) # converts the integer 0 to False


y = bool("hello") # converts the string "hello" to True
z = bool(None) # converts the value None to False

Type conversion is a useful tool in Python, as it allows you to work with different types of
data and perform operations that require values of specific data types. However, it's
important to keep in mind that type conversion can sometimes result in data loss or errors,
so it's important to use it carefully and ensure that the resulting data is accurate and valid.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 19


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Python Libraries; in python


In Python, a library is a collection of modules and functions that can be used to
perform specific tasks. Python has a large number of libraries, many of which are
built-in to the language, while others can be installed using third-party package
managers like pip. Here are some of the most commonly used Python libraries:

1. math: This library provides various mathematical functions, such as


trigonometric functions, logarithmic functions, and more.
2. random: This library provides functions for generating random numbers,
shuffling lists, and selecting random elements from a list.
3. datetime: This library provides classes for working with dates and times,
including functions for parsing and formatting dates and times, calculating
time differences, and more.
4. os: This library provides functions for working with the operating system,
including functions for creating, deleting, and renaming files and directories,
and for accessing environment variables.
5. sys: This library provides functions for interacting with the Python interpreter,
including functions for accessing command line arguments, manipulating the
system path, and more.
6. re: This library provides functions for working with regular expressions,
including functions for searching, replacing, and matching patterns in strings.
7. json: This library provides functions for working with JSON (JavaScript Object
Notation) data, including functions for encoding and decoding JSON data.
8. requests: This library provides functions for making HTTP requests, including
functions for sending GET and POST requests, setting headers, and handling
cookies.
9. numpy: This library provides functions for working with arrays and matrices,
including functions for performing mathematical operations on arrays,
manipulating arrays, and more.
10. pandas: This library provides functions for working with data in a tabular
format, including functions for reading and writing data to and from CSV,
Excel, and other file formats, and for performing data analysis and
manipulation.

There are many other Python libraries available, depending on your needs and the
tasks you want to perform. When working on a project, it's often helpful to research
and identify the most appropriate libraries to use, as they can save time and simplify
complex tasks.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 20


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Importing Libraries with Examples; in python


In Python, to use a library, you need to import it into your code. Here are some ways
to import libraries in Python, along with examples:

1. Importing the entire library:

To import the entire library, you can use the import keyword, followed by the name of
the library. This makes all the functions and modules in the library available in your
code.

Example:

import math

print([Link](16)) # prints 4.0

2. Importing a specific function or module:

To import a specific function or module from a library, you can use the from keyword,
followed by the name of the library and the name of the function or module.

Example:

from datetime import date

today = [Link]()
print(today) # prints the current date in the format YYYY-MM-DD

In this example, the date module is imported from the datetime library, and the
today() function is used to get the current date.

3. Importing a library with an alias:

You can use an alias to rename a library when importing it, using the as keyword.

Example:

import numpy as np

arr = [Link]([1, 2, 3])


print(arr) # prints [1 2 3]

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 21


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

In this example, the numpy library is imported with the alias np, making it easier to
reference the library in the code.

4. Importing a library from a different directory:

If the library you want to use is located in a different directory, you can add the
directory to the Python path and then import the library as usual.

Example:

import sys
[Link]("/path/to/library/directory")

import mylibrary

result = [Link]()
print(result)

In this example, the sys module is used to add the directory containing the mylibrary
module to the Python path, and then the mylibrary module is imported and used in
the code.

These are just a few examples of how to import libraries in Python. There are many
other ways to import libraries, depending on your needs and the structure of your
code.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 22


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Illustrative programs. in python

Here are some illustrative programs in Python:

1. Hello World:
print("Hello, World!")

his program simply prints the string "Hello, World!" to the console.

2. Basic Arithmetic:
x=5
y=2

print("x + y =", x + y) # Addition


print("x - y =", x - y) # Subtraction
print("x * y =", x * y) # Multiplication
print("x / y =", x / y) # Division
print("x % y =", x % y) # Modulus (remainder)
print("x ** y =", x ** y) # Exponentiation
print("x // y =", x // y) # Floor Division

This program performs some basic arithmetic operations on two variables x and y,
and prints the results to the console.

3. Looping:
for i in range(10):
print(i)

This program uses a for loop to iterate over the numbers from 0 to 9, and prints each
number to the console.

4. Conditional Statements:
x = 10

if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")

This program uses an if statement to check whether a variable x is positive, negative,


or zero, and prints the corresponding message to the console.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 23


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

5. String Manipulation:
s = "Hello, World!"

print([Link]()) # Convert to uppercase


print([Link]()) # Convert to lowercase
print([Link]()) # Capitalize the first letter
print([Link]("Hello", "Hi")) # Replace "Hello" with "Hi"

This program demonstrates some basic string manipulation operations, such as


converting a string to uppercase or lowercase, capitalizing the first letter of a string,
and replacing substrings in a string.

These are just a few examples of the types of programs that can be written in Python.
The language is very versatile and can be used for a wide range of applications, from
simple scripts to complex software systems.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 24


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

MODULE 3

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 25


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Types of Control Flow; in python

In Python, there are three types of control flow statements:

1. Conditional Statements (if/elif/else): Conditional statements are used to


execute different blocks of code based on a condition. The basic syntax is:
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition1 is False and condition2 is True
else:
# Code to execute if both condition1 and condition2 are False
Example:

x=5

if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
2. Loops (for/while): Loops are used to execute a block of code repeatedly. The
basic syntax is:

For loop:

for variable in sequence:


# Code to execute for each value of variable in sequence

Example:

for i in range(10):
print(i)
While loop syntax:
while condition:
# Code to execute as long as condition is True
Example:
i=0
while i < 10:
print(i)
i += 1

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 26


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

3. Control Flow Keywords (break/continue): Control flow keywords are used to


modify the behavior of loops. The basic syntax is:

Break: Used to exit a loop when a certain condition


is met.

for variable in sequence:


if condition:
break
Example
for i in range(10):
if i == 5:
break
print(i)
Continue: Used to skip the current iteration of a loop
and move on to the next iteration
for variable in sequence:
if condition:
continue
# Code to execute for each value of variable that
does not satisfy the condition
Example:
for i in range(10):
if i % 2 == 0:
continue
print(i)
hese are the three basic types of control flow statements in Python. They allow you to write
programs that can make decisions, repeat tasks, and modify their behavior based on certain
conditions.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 27


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Control Flow Statements- in python


In Python, control flow statements are used to control the execution of code based on
certain conditions. There are three main types of control flow statements: conditional
statements, loops, and function calls.

1. Conditional Statements: Conditional statements are used to execute code only


if certain conditions are met. In Python, the conditional statements are
expressed with the keywords if, elif (short for "else if"), and else.

2. Loops: Loops are used to repeat a set of statements multiple times. In Python,
there are two types of loops: for loop and while loop.

3. Function Calls: Functions are reusable blocks of code that can be called
multiple times with different input parameters. In Python, you can define a
function using the def keyword.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 28


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

if statement in python

In Python, the "if" statement is a conditional statement that allows you to execute code only
if a certain condition is met. The basic syntax of the "if" statement in Python is as follows:

if condition:
# code to execute if condition is True

In this syntax, "condition" is a boolean expression that evaluates to either True or


False. If the condition is True, the code block under the "if" statement is executed. If
the condition is False, the code block is skipped.

Here's an example:

x = 10

if x > 5:
print("x is greater than 5")

In this example, the "if" statement checks if the value of "x" is greater than 5. Since the value
of "x" is 10, the condition is True and the code block under the "if" statement is executed,
which prints the message "x is greater than 5" to the console.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 29


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

else statement in python

In Python, the "else" statement is used in conjunction with the "if" statement to specify code
that should be executed when the condition of the "if" statement is False. The basic syntax of
the "if-else" statement in Python is as follows:

if condition:
# code to execute if condition is True
else:
# code to execute if condition is False

In this syntax, if the "condition" of the "if" statement is True, the code block under
the "if" statement is executed. Otherwise, the code block under the "else" statement
is executed.

Here's an example:

x=3

if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")

In this example, the "if" statement checks if the value of "x" is greater than 5. Since the value
of "x" is 3, the condition is False, and the code block under the "else" statement is executed,
which prints the message "x is less than or equal to 5" to the console.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 30


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

elif statement in python

In Python, the "elif" statement is short for "else if". It's used to add additional conditions to
the "if" statement. The basic syntax of the "if-elif-else" statement in Python is as follows:

if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition1 is False and condition2 is True
else:
# code to execute if condition1 and condition2 are False

In this syntax, the "if" statement is followed by one or more "elif" statements, which
can test additional conditions. The "else" statement is optional, and if included, it
executes if all the conditions tested by the "if" and "elif" statements are False.

Here's an example:

x=7

if x < 5:
print("x is less than 5")
elif x < 10:
print("x is between 5 and 10")
else:
print("x is greater than or equal to 10")

In this example, the "if" statement checks if the value of "x" is less than 5. Since the value of
"x" is 7, the condition is False, and the code block under the first "elif" statement is executed,
which prints the message "x is between 5 and 10" to the console.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 31


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

While loop in python

In Python, the "while" loop is a control flow statement that allows you to execute a
block of code repeatedly as long as a certain condition is True. The basic syntax of
the "while" loop in Python is as follows:

while condition:
# code to execute repeatedly while condition is True

In this syntax, "condition" is a boolean expression that is tested at the beginning of


each iteration of the loop. If the condition is True, the code block under the "while"
statement is executed. After the code block is executed, the condition is tested again,
and if it's still True, the code block is executed again. This process continues until the
condition is False, at which point the loop is exited and the program continues with
the next statement.

Here's an example:

i=0

while i < 5:
print(i)
i += 1

In this example, the "while" loop repeatedly prints the value of "i" to the console as long as
it's less than 5. The loop starts with the value of "i" set to 0, and the condition "i < 5" is True.
The code block under the "while" statement is executed, which prints the value of "i" to the
console and increments the value of "i" by 1. This process continues until the value of "i" is 5,
at which point the condition "i < 5" is False, and the loop is exited.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 32


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Break in python

In Python, the "break" statement is a control flow statement that allows you to exit a
loop prematurely, before the condition that controls the loop has become False.
When a "break" statement is executed, the program immediately exits the loop and
continues with the next statement outside of the loop.

The "break" statement is typically used when you want to exit a loop under a certain
condition, for example, if you've found the value you're looking for in a list, or if a
certain computation has reached a certain threshold.

Here's an example:

fruits = ["apple", "banana", "cherry", "date", "elderberry"]

for fruit in fruits:


if fruit == "date":
break
print(fruit)

In this example, the "for" loop iterates over the list of fruits, and the "fruit" variable
takes on the value of each fruit in turn. The "if" statement checks if the value of "fruit"
is equal to "date", and if it is, the "break" statement is executed, which immediately
exits the loop. As a result, only the values of "apple", "banana", and "cherry" are
printed to the console.

It's worth noting that "break" only exits the innermost loop that it's contained in. If
you have nested loops, and you want to exit the outer loop, you can use a labeled
"break" statement.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 33


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

continue statements, in python

In Python, the "continue" statement is a control flow statement that allows you to
skip the current iteration of a loop and move on to the next iteration. When a
"continue" statement is executed, the program skips any remaining code in the
current iteration of the loop and immediately begins the next iteration.

The "continue" statement is typically used when you want to skip over certain values
in a sequence, or when you want to implement certain conditions for certain values.

Here's an example:

fruits = ["apple", "banana", "cherry", "date", "elderberry"]

for fruit in fruits:


if len(fruit) < 6:
continue
print(fruit)

In this example, the "for" loop iterates over the list of fruits, and the "fruit" variable
takes on the value of each fruit in turn. The "if" statement checks if the length of the
current fruit is less than 6, and if it is, the "continue" statement is executed, which
skips the rest of the code block for the current iteration and immediately moves on
to the next iteration. As a result, only the values of "banana", "cherry", and
"elderberry" are printed to the console.

It's worth noting that "continue" only skips the remaining code in the current
iteration of the loop. The loop continues with the next iteration, and any remaining
iterations are executed as normal.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 34


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

for loop statement in python

In Python, the "for" loop is a control flow statement that allows you to execute a block of
code repeatedly for each item in a sequence (such as a list, tuple, or string). The basic syntax
of the "for" loop in Python is as follows:

for item in sequence:


# code to execute for each item in sequence

In this syntax, "item" is a variable that is assigned the value of each item in the
"sequence" in turn. The code block under the "for" statement is executed once for
each item in the sequence.

Here's an example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(fruit)

In this example, the "for" loop iterates over the items in the list "fruits" and assigns
each item to the variable "fruit" in turn. The code block under the "for" statement is
executed once for each item in the list, which prints the value of the "fruit" variable to
the console.

You can also use the built-in "range" function to create a sequence of numbers to
iterate over:

for i in range(5):
print(i)
In this example, the "for" loop iterates over the numbers 0 through 4 and assigns each
number to the variable "i" in turn. The code block under the "for" statement is executed once
for each number in the sequence, which prints the value of the "i" variable to the console.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 35


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Illustrative programs. of control flow

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 36


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

range() and exit () functions;

range() is a built-in function in Python that returns a sequence of numbers. It can


take one to three arguments, which are the starting value, the stopping value, and
the step value. The sequence starts at the starting value and ends at the stopping
value, and each successive number in the sequence is incremented by the step value.

Here's an example:

for i in range(1, 10, 2):


print(i)

In this example, the range() function generates a sequence of odd numbers from 1 to
9, incrementing by 2 at each step. The "for" loop iterates over this sequence, and the
"i" variable takes on the value of each number in turn. The code block under the "for"
statement is executed for each value of "i", which simply prints the value to the
console.

exit() is a built-in function in Python that is used to terminate a program. It takes an


optional argument, which is the exit code, that indicates the reason for the program's
termination. The exit code is typically a non-zero integer value that indicates an error
condition or other type of abnormal termination.

Here's an example:

import sys

if some_error_condition:
[Link](1)

In this example, the [Link]() function is used to terminate the program with an exit code
of 1 if the some_error_condition evaluates to True. This indicates that the program
terminated abnormally due to an error condition. Note that the sys module is imported to
use the exit() function.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 37


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Illustrative programs. of control flow

Here are a few illustrative programs that demonstrate the use of control flow
statements in Python:

1. Program to calculate the factorial of a number using a while loop:

n = int(input("Enter a number: "))


fact = 1
while n > 1:
fact *= n
n -= 1
print("Factorial =", fact)

In this program, a while loop is used to calculate the factorial of the input number.
The loop continues as long as the value of "n" is greater than 1. In each iteration of
the loop, the value of "fact" is multiplied by the current value of "n", and "n" is
decremented by 1. After the loop has finished, the final value of "fact" is printed to
the console.

2. Program to check if a number is prime using a for loop and a break statement:

n = int(input("Enter a number: "))


for i in range(2, n):
if n % i == 0:
print(n, "is not prime")
break
else:
print(n, "is prime")

In this program, a for loop is used to check if the input number is prime. The loop
iterates over a range of numbers from 2 to the input number minus 1. In each
iteration of the loop, the current number is divided by the input number using the
modulo operator. If the remainder is 0, the input number is not prime, and the loop
is exited using a "break" statement. If the loop completes without finding a divisor,
the input number is prime, and the "else" block is executed.

3. Program to generate the first "n" Fibonacci numbers using a for loop:
n = int(input("Enter a number: "))
fib = [0, 1]
for i in range(2, n):
[Link](fib[i-1] + fib[i-2])
print("Fibonacci sequence:", fib)

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 38


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

In this program, a for loop is used to generate the first "n" Fibonacci numbers. The program
initializes a list with the first two numbers in the sequence (0 and 1), and then uses a loop to
generate the remaining numbers. In each iteration of the loop, the program appends the
sum of the previous two numbers in the sequence to the list. After the loop has finished, the
entire Fibonacci sequence is printed to the console.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 39


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

MODULE 4

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 40


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Types of Functions; in python

In Python, there are several types of functions that you can define and use in your
code:

1. Built-in functions: These are functions that are part of the Python language
itself and are always available to use. Examples include print(), len(), range(),
input(), abs(), and max().
2. User-defined functions: These are functions that you define yourself in your
code to perform specific tasks. You can define a function using the def
keyword, followed by the function name, parentheses, and a colon. The
function body is indented below the header. Here's an example of a simple
user-defined function:

def greet(name):

print("Hello, " + name + "!")

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 41


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Function Definition- Syntax, in python

In Python, a function is a reusable block of code that performs a specific task. The basic
syntax for defining a function in Python is as follows:

def function_name(parameters):
"""docstring"""
statements
[return expression]

Here's what each part of the syntax means:

• def: This keyword is used to define a function in Python.


• function_name: This is the name of the function. It should be a descriptive name
that reflects the purpose of the function.
• parameters: These are the inputs to the function. They are optional and can be
left empty if the function does not require any input.
• docstring: This is an optional documentation string that provides information
about the purpose of the function. It is enclosed in triple quotes and appears
as the first line of the function definition.
• statements: These are the lines of code that are executed when the function is
called. They can include any valid Python code, including other function calls
and control flow statements.
• return: This keyword is used to return a value from the function. It is optional
and can be omitted if the function does not need to return a value. If present,
the expression following return is the value returned by the function.

Here's an example of a function that takes two parameters and returns their sum:

def add_numbers(a, b):


"""Returns the sum of two numbers."""
return a + b

Once defined, this function can be called from other parts of the program with the
appropriate arguments:

result = add_numbers(2, 3)
print(result) # Output: 5

In general, functions help to make code more modular and easier to read and maintain.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 42


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Function Calling in python

To call a function in Python, you simply need to use the function name followed by
parentheses, and any arguments that the function requires. Here's an example of calling a
built-in function:

print("Hello, world!")

In this example, the print() function is called with a string argument "Hello, world!".

Here's an example of calling a user-defined function:

def greet(name):
print("Hello, " + name + "!")

greet("Alice")

Here's an example of calling a lambda function:

add = lambda x, y: x + y
result = add(3, 5)
print(result)

In this example, the add lambda function is called with the arguments 3 and 5. The result is
assigned to a variable result and printed to the console.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 43


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Passing Parameters/arguments, in python

In Python, you can pass parameters or arguments to a function in several ways,


including:

1. Positional Arguments: Positional arguments are the most common way


of passing arguments to a function. In this case, the arguments are
passed based on their position in the function call. The function
definition must have parameters in the same order as the arguments
passed in the function call. Here's an example:

def add_numbers(a, b):


return a + b
result = add_numbers(2, 3)
print(result) # Output: 5

In this example, 2 and 3 are positional arguments passed to the


function add_numbers. They are assigned to the function parameters a
and b respectively.

2. Keyword Arguments: Keyword arguments are passed to a function with


the parameter name followed by the value separated by an equal sign.
In this case, the order of the arguments does not matter . Here's an
example:
def greet(name, message):
print(message + ", " + name + "!")
greet(message="Hello", name="Alice")

In this example, name and message are the parameters of the function
greet. They are assigned the values "Alice" and "Hello" respectively
using keyword arguments.

3. Default Arguments: You can set default values for parameters in the function
definition. If the argument is not passed in the function call, the default value
is used instead.

Here's an example

def greet(name, message="Hello"):


print(message + ", " + name + "!")
greet("Alice") # Output: "Hello, Alice!"
greet("Bob", "Hi") # Output: "Hi, Bob!"
In this example, message is a default argument that is set to "Hello". If a value is not provided
for message in the function call, the default value is used.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 44


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

the return statement; in python

In Python, the return statement is used to exit a function and return a value to the
caller. It can be used in both built-in and user-defined functions.

The syntax of the return statement is simple. It consists of the keyword return
followed by an expression or a variable whose value you want to return. Here's an
example:

def add_numbers(a, b):

return a + b

In this example, the add_numbers function takes two arguments a and b, adds them
together, and returns the result using the return statement.

If the return statement is used without an expression or variable, it simply returns


None. For example:

def say_hello():
print("Hello, World!")
return

In this example, the say_hello function prints "Hello, World!" and returns None
because there is no expression or variable after the return keyword.

The return statement can also be used to return multiple values. In Python, you can
return multiple values as a tuple. Here's an example:

def divide_numbers(a, b):


quotient = a // b
remainder = a % b
return quotient, remainder
In this example, the divide_numbers function takes two arguments a and b, calculates the
quotient and remainder of dividing a by b, and returns them as a tuple using the return
statement.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 45


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Default Parameters; in python

In Python, default parameters are used to define a default value for a function
parameter. When a function is called and a value is not passed for a parameter that
has a default value defined, the default value will be used.

Here's an example of a function with default parameters:

def greet(name, greeting='Hello'):


print(f"{greeting}, {name}!")

greet('John') # Output: Hello, John!


greet('Emily', 'Hi') # Output: Hi, Emily!

In the above example, the greeting parameter has a default value of 'Hello'. When the
greet() function is called with only the name parameter, the default greeting of 'Hello'
is used. When the function is called with both name and greeting parameters, the value
of greeting provided by the caller is used.

Default parameters can also be defined with mutable objects like lists or dictionaries.
However, it is important to understand that if the mutable object is modified within
the function, the changes will persist in subsequent calls to the same function. Here's
an example:

def add_item(item, my_list=[]):


my_list.append(item)
return my_list

print(add_item('apple')) # Output: ['apple']


print(add_item('banana')) # Output: ['apple', 'banana']
print(add_item('orange', ['grape'])) # Output: ['grape', 'orange']

In the above example, the add_item() function has a default parameter of an empty list [].
When the function is called with only the item parameter, the default list is used. However, if
the my_list parameter is not provided, the same default list is used across subsequent
function calls. In the second call, 'banana' is added to the list, and in the third call, 'orange' is
added to the same list, which already contains 'apple' and 'banana'

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 46


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Command line Arguments; in python

Command line arguments are values passed to a program when it is run from the
command line. In Python, you can access these arguments using the sys module,
which provides access to some variables used or maintained by the Python
interpreter.

Here's an example of a simple Python program that prints the command line
arguments passed to it:

import sys

# Get the command line arguments


args = [Link]

# Print each argument


for arg in args:
print(arg)

In this example, we import the sys module and get the command line arguments
using the [Link] variable. This variable is a list that contains the name of the script
followed by any arguments passed to the script.

We then iterate over the args list and print each argument to the console.

To run this program with command line arguments, you would type something like
this:

python [Link] arg1 arg2 arg3

This would pass three arguments (arg1, arg2, and arg3) to the [Link] script. The script
would then print each argument to the console.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 47


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Key Word Arguments; in python

In Python, keyword arguments are a way of passing arguments to a function by


specifying the argument name along with its value. This allows you to pass
arguments to a function in any order and makes the code more readable.

Here's an example of a function that takes two keyword arguments:

def greet(name, message):


print(f"{message}, {name}!")

# Call the function with keyword arguments


greet(name="Alice", message="Hello")

In this example, the greet function takes two keyword arguments: name and message.
We call the function using the keyword arguments syntax, where we specify the
argument names and their values. This allows us to pass the arguments in any order.

The output of this code would be Hello, Alice!.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 48


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Illustrative [Link] python functions

Here are some simple Python functions with explanations:

Example 1: A function that adds two numbers


def add_numbers(a, b):
return a + b
This function takes two parameters, a and b, and returns their sum. For example:

print(add_numbers(3, 4)) # Output: 7

Example 2: A function that returns the length of a string


def string_length(s):

return len(s)

This function takes a single parameter, s, which is a string, and returns its length. For
example:

print(string_length("Hello, world!")) # Output: 13

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 49


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

MODULE 5

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 50


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Creating and Storing Strings; in python

In Python, you can create a string by enclosing a sequence of characters in single quotes ( ')
or double quotes ("). Here are some examples:

# Creating a string with single quotes


string1 = 'Hello, world!'

# Creating a string with double quotes


string2 = "Hello, Python!"

# Creating a string with single quotes and double quotes


string3 = 'He said, "Hello!"'

In Python, single and double quotes can be used interchangeably to create strings. However,
if you need to include a quote character inside a string that is already enclosed in quotes of
the same type, you can use the other type of quote character to create the string. For
example:

string4 = "She said, 'Hello!'"

In this example, single quotes are used to enclose the string because double quotes
are already used inside the string.

In addition to using single or double quotes to create a string, you can also use triple
quotes (''' or """) to create a multi-line string:

string5 = '''This is a
multi-line
string.'''

In this example, the string spans multiple lines and is enclosed in triple quotes. The
string includes newlines (\n) between each line of text.

Once you have created a string, you can manipulate it in various ways, such as slicing,
concatenating, and formatting.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 51


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

How do you sort string in python

In Python, you can sort a string using the sorted() function or the sort() method.
Both functions return a sorted list of the characters in the string.

Here's an example using the sorted() function:

string = "hello world"


sorted_string = sorted(string)
print(sorted_string)

In this example, we create a string "hello world" and pass it to the sorted() function.
The function returns a sorted list of the characters in the string, which we store in the
sorted_string variable. We then print the sorted list.

The output of this code would be:

[' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']

You can also use the sort() method to sort a string. Here's an example:

string = "hello world"


string_list = list(string)
string_list.sort()
sorted_string = "".join(string_list)
print(sorted_string)

In this example, we convert the string to a list of characters using the list() function,
sort the list using the sort() method, and then join the sorted list back into a string
using the join() method. We then print the sorted string.

The output of this code would be:

dehllloorw

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 52


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Accessing Sting Characters; in python

In Python, you can access individual characters in a string using indexing. String
indexing is zero-based, which means that the first character of a string has an index
of 0, the second character has an index of 1, and so on.

Here's an example:

string = "hello"

print(string[0]) # Output: 'h'

print(string[1]) # Output: 'e'

print(string[2]) # Output: 'l'

print(string[3]) # Output: 'l'

print(string[4]) # Output: 'o'

In this example, we create a string "hello" and use indexing to access each character
in the string. We print each character using the print() function.

You can also use negative indexing to access characters from the end of the string.
The last character of a string has an index of -1, the second to last character has an
index of -2, and so on.

Here's an example using negative indexing:

string = "hello"

print(string[-1]) # Output: 'o'

print(string[-2]) # Output: 'l'

print(string[-3]) # Output: 'l'

print(string[-4]) # Output: 'e'

print(string[-5]) # Output: 'h'

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 53


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

the str() function; in python

In Python, the str() function is used to convert an object to a string. This function
takes an object as an argument and returns a string representation of the object.

Here's an example:

number = 42
string = str(number)
print(string) # Output: '42'

In this example, we create an integer variable number with a value of 42. We then pass this
variable to the str() function to convert it to a string. The resulting string is stored in the
string variable, which we then print using the print() function.

The str() function can be used to convert a wide range of objects to strings, including
numbers, booleans, lists, dictionaries, and more. Here are some examples:

# Convert a boolean to a string


boolean = True
string = str(boolean)
print(string) # Output: 'True'

In each of these examples, we use the str() function to convert an object to a string. The
resulting string is then printed using the print() function.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 54


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

python concatenation operation on string

In Python, you can concatenate two or more strings using the + operator. This operation
combines two or more strings into a single string. Here's an example:

string1 = "hello"
string2 = "world"
result = string1 + " " + string2
print(result) # Output: 'hello world'

In this example, we create two strings string1 and string2 and concatenate them with a
space in between using the + operator. The resulting string is stored in the result variable,
which we then print using the print() function.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 55


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

python comparison operation on string

Python allows comparison operations to be performed on strings using various


comparison operators. Here are some examples:

1. Equal to: the == operator can be used to check if two strings are equal:
string1 = "hello"
string2 = "world"

if string1 == "hello":
print("string1 is equal to 'hello'")

if string1 == string2:
print("string1 is equal to string2")
else:
print("string1 is not equal to string2")
OUTPUT
string1 is equal to 'hello'
string1 is not equal to string2
2. Not equal to: the != operator can be used to check if two strings are not
equal:
string1 = "hello"
string2 = "world"
if string1 != string2:
print("string1 is not equal to string2")
OUTPUT
string1 is not equal to string2
3. Greater than or less than: the > and < operators can be used to compare two
strings based on their lexicographical order:
string1 = "apple"
string2 = "banana"
if string1 > string2:
print("string1 comes after string2 in lexicographical order")
else:
print("string1 comes before string2 in lexicographical order")

OUTPUT
string1 comes before string2 in lexicographical order

Note that the comparison of strings is case sensitive, which means that the uppercase letters
have a different ASCII code than the lowercase letters and are considered greater in
lexicographical order.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 56


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Slicing and Joining, In python

Slicing and joining are two important string operations in Python. Slicing is used to
extract a part of a string, while joining is used to concatenate a list of strings into a
single string. Here's how you can use these operations in Python:

1. Slicing:

Slicing allows you to extract a range of characters from a string by specifying the
start and end indices. You can also use slicing to extract individual characters from a
string.

Here's an example that demonstrates slicing a string in Python:

string = "Hello, World!"


print(string[0:5]) # Output: Hello
print(string[7:]) # Output: World!
print(string[-6:-1]) # Output: World

In this example, we have a string "Hello, World!" and we use slicing to extract
different parts of the string.

The first print() statement extracts the characters from index 0 to 5, which
corresponds to the substring "Hello".

The second print() statement extracts the characters from index 7 to the end of the
string, which corresponds to the substring "World!".

The third print() statement extracts the characters from the second-to-last character
to the fifth-to-last character, which corresponds to the substring "World". Note that
we use negative indexing to specify the start and end indices.

2. Joining:

Joining is used to concatenate a list of strings into a single string. You can use the
join() method to join a list of strings together.

Here's an example that demonstrates joining a list of strings in Python:

fruits = ["apple", "banana", "cherry"]


separator = ", "
result = [Link](fruits)
print(result) # Output: apple, banana, cherry

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 57


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

In this example, we have a list of strings fruits and a separator string ", ". We use the
join() method to join the strings in the list together with the separator. The resulting string
is stored in the result variable, which we then print using the print() function. Note that the
separator is inserted between each pair of adjacent strings in the list.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 58


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Traversing; in python

Traversing is a process of iterating over the elements of a collection or sequence,


such as a string, list, or tuple, and performing some operation on each element. In
Python, you can use various constructs to traverse sequences, including loops and
comprehensions.

Here's an example that demonstrates how to traverse a string using a for loop in
Python:

string = "Hello, World!"


for character in string:
print(character)

In this example, we have a string "Hello, World!" and we use a for loop to iterate
over each character in the string. The loop iterates once for each character in the
string, and the print() function is called on each iteration to output the character.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 59


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 60


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Format Specifiers; in python

In Python, format specifiers are used to format strings by defining placeholders for
variables that are later filled in with values.

The basic syntax for using format specifiers in Python is as follows:

"{field_name:conversion_specifier}".format(value)

Here, field_name is the name of the field that is being filled in, and
conversion_specifier is the conversion specifier that defines how the value should be
formatted. The value argument is the actual value that will be substituted into the
string.

Here are some commonly used conversion specifiers in Python:

• %d: formats an integer value


• %f: formats a floating point value
• %s: formats a string value
• %c: formats a character (a single character string)
• %x: formats an integer as a hexadecimal value
• %o: formats an integer as an octal value
• %e or %E: formats a floating point value in scientific notation
• %g or %G: formats a floating point value in either decimal or scientific notation,
depending on the magnitude of the value

For example, to format an integer value, you could use the following code:

age = 30
print("I am %d years old." % age)

The output of this code would be:


I am 30 years old.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 61


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Escape Sequences; in python

Escape sequences in Python are special characters that are used to represent non-
printable characters in a string or to insert special characters in a string. An escape
sequence is represented by a backslash followed by a character or a combination of
characters.

Here are some commonly used escape sequences in Python:

• \n: inserts a new line character


• \t: inserts a tab character
• \': inserts a single quote character
• \": inserts a double quote character
• \\: inserts a backslash character

For example, to insert a new line character in a string, you could use the escape
sequence \n like this:

print("Hello\nworld")

The output of this code would be:


Hello
World

To insert a single quote character in a string that is enclosed in single quotes, you
can use the escape sequence \' like this:

print('It\'s a beautiful day')

The output of this code would be:


It's a beautiful day

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 62


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Raw and Unicode Strings; in python

In Python, there are two types of string literals: raw strings and Unicode strings.

1. Raw Strings: A raw string is a string that is prefixed with an r character. It tells
Python to interpret backslashes (\) literally, rather than as escape characters.
This is useful when you want to include backslashes in your string, such as
when working with regular expressions or file paths.

Here's an example that demonstrates how to use a raw string in Python:

path = r'C:\Users\JohnDoe\Documents'
print(path)

In this example, we have a string path that contains a file path. The string is prefixed
with an r character to indicate that it is a raw string. The backslashes in the string are
interpreted literally, so the resulting output includes the backslashes.

2. Unicode Strings: A Unicode string is a string that is encoded using the


Unicode standard. It is prefixed with a u character. Unicode strings can include
characters from any language or writing system, including non-Latin scripts.

Here's an example that demonstrates how to use a Unicode string in Python:

unicode_string = u'こんにちは'

print(unicode_string)

In this example, we have a string unicode_string that contains the Japanese greeting "
こんにちは". The string is prefixed with a u character to indicate that it is a Unicode
string. Because the Unicode standard supports Japanese characters, the string is
encoded correctly and the resulting output displays the Japanese characters.

Note that in Python 3, all strings are Unicode strings by default, so you don't need to
prefix them with a u character. However, you can still use the u prefix for backwards
compatibility with Python 2.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 63


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Python String Methods;

In Python, a string is a sequence of characters enclosed within either single quotes or double
quotes. Python provides a number of built-in methods for manipulating strings. Here are
some commonly used string methods in Python:

1. len(): returns the length of the string.


string = "Hello, World!"
print(len(string)) # output: 13
2. lower(): converts all characters in the string to lowercase.
string = "Hello, World!"
print([Link]()) # output: hello, world!
3. upper(): converts all characters in the string to uppercase.
string = "Hello, World!"
print([Link]()) # output: HELLO, WORLD!

4. strip(): removes whitespace from the beginning and end of the string.
string = " Hello, World! "
print([Link]()) # output: Hello, World!

5. replace(): replaces a substring within the string with another substring.


string = "Hello, World!"
print([Link]("Hello", "Hi")) # output: Hi, World!

6. split(): splits the string into a list of substrings based on a specified delimiter.
string = "apple,banana,orange"
fruits = [Link](",")
print(fruits) # output: ['apple', 'banana', 'orange']

7. join(): joins a list of strings into a single string with a specified delimiter.
fruits = ['apple', 'banana', 'orange']
string = ",".join(fruits)
print(string) # output: apple,banana,orange

8. startswith(): checks if the string starts with a specified substring.


string = "Hello, World!"
print([Link]("Hello")) # output: True
print([Link]("Hi")) # output: False
9. endswith(): checks if the string ends with a specified substring.
string = "Hello, World!"
print([Link]("World!")) # output: True
print([Link]("World")) # output: False

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 64


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

Illustrative programs in python Strings

Here are some illustrative programs in Python that demonstrate various string
manipulations:

1. Program to print a string

string = "Hello, World!"


print(string)

2. Program to get the length of a string

string = "Hello, World!"


length = len(string)
print("Length of the string is", length)

3. Program to convert a string to lowercase

string = "Hello, World!"


lowercase_string = [Link]()
print(lowercase_string)

4. Program to convert a string to uppercase

string = "Hello, World!"


uppercase_string = [Link]()
print(uppercase_string)

5. Program to remove whitespace from a string

string = " Hello, World! "


trimmed_string = [Link]()
print(trimmed_string)

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 65


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

QUESTION BANK

Unit 2

1 Define Python

How do a you install python? & write a Simple Python Progam with eg.

OR

write a note on python IDE and how you write your first python program

2 Define Identifer, Keywords, Expressions, Variables ,operators,data types, comments, indentation

3 which operator has highest operator precedences. lowest operator precedence.

4 define Built in functions types do Convert data type. you

5How do you convert data type

6 "define few python libraries with eg

7 how do you import library in python with eg "

additional question to read

Define compiler, Interpreter, program , debugging , syntax errors, exception/runtime errors,


VARIABLES, KEywords , operator expression composition commnet.

What are the conditions to write varible names & with eg

DEfine keywords and write some of the keywords avaible in python language

How do you evaluate expression in command line / interpreter.

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 66


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

________________________________________________________________________________

UNIT 3

1. Explain the types of control flow


2. Explain control flow statemtns with eg
3. Explain the following (any 2) with eg

1) IF

2) ELSE

3) ELIF

3) WHILE

4) BREAK

5) CONTINUE

6) FOR LOOP STATEMENTS

4. Write a note on

1) range ()

2) exit()

additional questions

5. Write a note on comparision operator

or write a note on Boolean expression

6. what are logical operators explain

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 67


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

______________________________________________________________________________

UNIT 4

1. Define function call

Or Explain types of Functions

2. how do you define a function and its use

or

How do you add new functions / own function in orogram

3. Explain the flow of exceution of program


4. How do you pass an arguments/parameter
5. What are default parameters / local parameters explain with eg
6. Write a note on return statements with eg
7. What and how command line arguments are executed in programs with eg

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 68


Open Elective: PYTHON PROGRAMING FOR 2 YEAR BCOM/BBA/BA (3 SEMESTER)

______________________________________________________________________________

UNIT 5

1. How do you create & sort array in String

[Link] how you can access string characters

[Link] String explain the Str() functions with eg

[Link] operations on String

or

4. Write a note on

1) Concatentaion

2) Comparision

3) Slicing & joinig

4) traversing

[Link] are format specifiers

[Link] Escape sequence are used in python program

[Link] are String Menthods and explain with eg

NOTES, TEXTBOOK, QUESTION BANK 4 GFGC GBD – PREPARED by MUHAMMAD YOUSUF 69

You might also like