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

PYTHON

The document provides an overview of the Python programming language. It discusses that Python is an interpreted, object-oriented scripting language created in 1991. It notes that Python code is organized through indentation rather than brackets and that it supports features like automatic memory management, dynamic typing, functional programming, and is cross-platform. Several key characteristics and uses of Python are also summarized such as its ease of use, standard library, open source nature, and suitability for tasks like web development, science, and rapid prototyping.

Uploaded by

arahmanmyself
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)
118 views

PYTHON

The document provides an overview of the Python programming language. It discusses that Python is an interpreted, object-oriented scripting language created in 1991. It notes that Python code is organized through indentation rather than brackets and that it supports features like automatic memory management, dynamic typing, functional programming, and is cross-platform. Several key characteristics and uses of Python are also summarized such as its ease of use, standard library, open source nature, and suitability for tasks like web development, science, and rapid prototyping.

Uploaded by

arahmanmyself
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/ 68

PYTHON

~BY MOHD ZAID

* Overview
As we all know, before python there were many programming languages in use
such as c, c++ etc. Python was introduced in the year 1991 by Guido van Rossum
who was a dutch. Python is a high-level, interpreted, interactive and object-
oriented scripting language. Python is a feature rich high-level, interpreted,
interactive and object-oriented scripting language. It is said as interpreted
language because python is processed at the runtime. It does not need to be
compiled before executing. Python is said as object oriented because it supports
OOPS-Object Oriented Programming Language. Python is an open source and
easy to learn, cross-platform programming language. It is available for use
under Python Software Foundation License which is compatible to GNU General
Public License on all the major operating system platforms Linux, Windows and
Mac OS. Python leaves you free to choose to program in an object-oriented,
procedural, functional, aspect-oriented, or even logic-oriented way. These
freedoms make Python a great language to write clean and beautiful code. The
python consists of the following characteristics:
* It supports functional and structured programming languages.
* It supports the Automatic garbage collection.
* It provides the dynamic level data types.
* It is easily integrated with other programming languages like c, c++, java etc
Python was designed for readability, and has some similarities to the English
language with influence from mathematics. Python uses new lines to complete a
command, as opposed to other programming languages which often use
semicolons or parentheses. Python relies on indentation, using whitespace, to
define scope; such as the scope of loops, functions and classes. Other programming
languages often use curly-brackets for this purpose. The python can be used in
several ways such as:
* Python can be used on a server to create web applications.
* Python can be used alongside software to create workflows.
* Python can connect to database systems. It can also read and modify files.

* Python can be used to handle big data and perform complex mathematics.

* Python can be used for rapid prototyping, or for production-ready software


development.

Features of Python:

The important features of Python that make it widely popular. Apart from these 10
features where are number of other interesting features which make Python most of
the developer's first choice.

Python is Easy to Learn:

This is one of the most important reasons for the popularity of Python. Python has
a limited set of keywords. Its features such as simple syntax, usage of indentation
to avoid clutter of curly brackets and dynamic typing that doesn't necessitate prior
declaration of variable help a beginner to learn Python quickly and easily.

Python is Interpreter Based:

Python is an interpreter based language. The interpreter takes one instruction from
the source code at a time, translates it into machine code and executes it.
Instructions before the first occurrence of error are executed. With this feature, it is
easier to debug the program and thus proves useful for the beginner level
programmer to gain confidence gradually. Python therefore is a beginner-friendly
language.

Python is Interactive:

Standard Python distribution comes with an interactive shell that works on the
principle of REPL (Read – Evaluate – Print – Loop). The shell presents a Python
prompt >>>. You can type any valid Python expression and press Enter. Python
interpreter immediately returns the response and the prompt comes back to read the
next expression.

>>> 2*3+1
7
>>> print ("Hello World")
Hello World

The interactive mode is especially useful to get familiar with a library and test out
its functionality. You can try out small code snippets in interactive mode before
writing a program.

Python is Multi Paradigm:

Python is a completely object-oriented language. Everything in a Python program


is an object. However, Python conveniently encapsulates its object orientation to
be used as an imperative or procedural language – such as C. Python also provides
certain functionality that resembles functional programming. Moreover, certain
third-party tools have been developed to support other programming paradigms
such as aspect-oriented and logic programming.

Python's Standard Library:


Even though it has a very few keywords (only Thirty Five), Python software is
distributed with a standard library made of large number of modules and packages.
Thus Python has out of box support for programming needs such as serialization,
data compression, internet data handling, and many more. Python is known for its
batteries included approach.

Python is Open Source and Cross Platform:

Python's standard distribution can be downloaded


from https://www.python.org/downloads/ without any restrictions. You can
download pre-compiled binaries for various operating system platforms. In
addition, the source code is also freely available, which is why it comes under open
source category.

Python software (along with the documentation) is distributed under Python


Software Foundation License. It is a BSD style permissive software license and
compatible to GNU GPL (General Public License).

Python is a cross-platform language. Pre-compiled binaries are available for use on


various operating system platforms such as Windows, Linux, Mac OS, Android
OS. The reference implementation of Python is called CPython and is written in C.
You can download the source code and compile it for your OS platform.

A Python program is first compiled to an intermediate platform independent byte


code. The virtual machine inside the interpreter then executes the byte code. This
behaviour makes Python a cross-platform language, and thus a Python program
can be easily ported from one OS platform to other.

Python for GUI Applications:

Python's standard distribution has an excellent graphics library called TKinter. It is


a Python port for the vastly popular GUI toolkit called TCL/Tk. You can build
attractive user-friendly GUI applications in Python. GUI toolkits are generally
written in C/C++. Many of them have been ported to Python. Examples are PyQt,
WxWidgets, PySimpleGUI etc.
Python's Database Connectivity:

Almost any type of database can be used as a backend with the Python application.
DB-API is a set of specifications for database driver software to let Python
communicate with a relational database. With many third party libraries, Python
can also work with NoSQL databases such as MongoDB.

Python is Extensible:

The term extensibility implies the ability to add new features or modify existing
features. As stated earlier, CPython (which is Python's reference implementation)
is written in C. Hence one can easily write modules/libraries in C and incorporate
them in the standard library. There are other implementations of Python such as
Jython (written in Java) and IPython (written in C#). Hence, it is possible to write
and merge new functionality in these implementations with Java and C#
respectively.

Python's Active Developer Community:

As a result of Python's popularity and open-source nature, a large number of


Python developers often interact with online forums and conferences. Python
Software Foundation also has a significant member base, involved in the
organization's mission to "Promote, Protect, and Advance the Python Programming
Language".

Python also enjoys a significant institutional support. Major IT companies Google,


Microsoft, and Meta contribute immensely by preparing documentation and other
resources.

Pythonic Code Style:

Python leaves you free to choose to program in an object-oriented, procedural,


functional, aspect-oriented, or even logic-oriented way. These freedoms make
Python a great language to write clean and beautiful code .
Pythonic Code Style is actually more of a design philosophy and suggests to write
a code which is:

 Clean
 Simple
 Beautiful
 Explicit
 Readable
* First Python Program:
The First python program to be learn and understand is “Hello World!” program.
This is a traditional first program when learning a new programming language.The
“Hello World!” program gives out the output, Hello World! The program is as
follows:
Print (“Hello World!”)
Output: Hello World!
In order to understand this better let us take another program of swapping of two
numbers. The program is as follows:
X=5
Y=10
Temp=X
X=Y
Y=temp
Print (“The value of X after swapping:{}”)
Print (“The value of Y after swapping:{}”)
Output:
X=10
Y=5

Here is a basic Python program that generates a random number:


python
Copy code
import random

random_number = random.randint(1, 10)


print(random_number)
This program imports the random module, which contains functions for generating
random numbers. It generates a random integer between 1 and 10 using the
randint() function, stores it in the random_number variable, and prints it out.
Some ways you could expand on this:

 Allow the user to input the min and max values for the random number range
 Print out multiple random numbers by putting it in a loop
 Store the random numbers in a list then print the list
 Let the user guess the number and tell them if they guessed correctly
* Python Indentations
Indentation is a crucial aspect of Python programming. It defines the structure of
code and helps organize blocks of statements. Unlike other programming
languages that use curly braces ({ }) to define code blocks. Python relies on
indentation to distinguish between different levels of code organization.

Purpose of Indentation in Python

Indentation serves two primary purposes in Python:

1. Structure and Organization: Indentation clearly indicates the hierarchy of


code blocks, making it easier to read and understand complex programs. It
visually separates nested statements and enhances the readability of
conditional statements, loops, and functions.

2. Syntax Enforcement: Python's interpreter uses indentation to determine the


grouping of statements. Incorrect indentation can lead to syntax errors,
preventing the program from running correctly.

Rules of Indentation in Python

1. Consistent Indentation: All statements within a block must have the same
level of indentation.

2. Default Indentation: The default indentation is four spaces. However, you


can use any number of spaces, but it is recommended to maintain
consistency throughout your code.

3. Indentation Level: Each nested level of code should be indented further than
the parent level.

4. Mixing Spaces and Tabs: Avoid mixing spaces and tabs for indentation. It
can cause inconsistencies and lead to errors.

5. First Line Indentation: The first line of a code block should not have any
indentation.
Example of Indentation

Python
if x > 0:
print ("x is positive")
else:
print ("x is negative")

for i in range (5):


print (i + 1)

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

greet("John")

In this example, the indentation clearly indicates the structure of the code. The if
statement and its else block are indented four spaces, while the statements within
the for loop and the function definition are indented further.

Importance of Proper Indentation

Proper indentation is essential for writing clear, readable, and bug-free Python
code. It improves code comprehension and maintainability, making it easier for
both the programmer and others to understand the code's structure and logic.
Additionally, consistent indentation helps prevent syntax errors and ensures the
program's execution as intended.

By following Python's indentation conventions, you can write well-structured,


readable, and error-free code, enhancing the quality and maintainability of your
Python programs.
* Variables Types
To understand Python variables better, imagine there is an empty shelf where you
want to store a few items. But, before placing anything on the shelf, you add a label
to each item so that you can search for anything easily by looking at the label.

In the same way, in Python programming variables are like those labels. Here, we
can say that the memory space is like an empty shelf. The values which we store in
the variables are same like items we stored on the shelf. There you can store
different types of values (items) like numbers, decimals, letters, and sentences.
However, to store that data, we need to use variables (labels) so that Python can
access the data using the variables. So, variables are nothing but reserved memory
locations to store values. This means that when we create a variable we reserve
some space in memory. It is the basic unit of storage in a program. A variable is
created the moment we first assign a value to it. These variables need not explicit
or detailed declaration to reserve the memory space or location. Even though the
declaration in python happens automatically when you assign a value to a variable.
So, when we create a variable and assign it a value, Python stores that value (item)
in the memory (shelf) and remember the variable name(label). Those values can be
integers, numbers, decimals, letters etc. So, when we create variable, we assign a
value to that value is stored by Python in the memory. And these variables are
assigned by using the equal to sign (=) where the operand left to the operator is the
name of the variable and the operand to the right of the operator is the value stored
in the variable.

Now let us understand this in the context of code:


(Area of rectangle)
Length = 5
Breath = 3
area = length x breadth
Print (" The area of rectangle is:”)
Output:
The area of rectangle is:15
Rules

There are certain set of rules which should be followed while assigning the
variable and their values. They are:

 A variable name must start with a letter or the underscore character.


 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters and underscores
(A-z, -9, and -)
 The variables in python are case-sensitive (name, Name, NAME are three
different variables)

The python has types of variables like -

 Numeric: These can be either integers or floats.


Integer – It represents the whole numbers
Float – It represents numbers with decimal values

 Boolean: It represents a logical value that can be either True or False.


Numerically True is equal to 1 and False is equal to 0. It is used in
conditional statements, such as if-else statements and while loops, to control
the flow of a program.

for example-
is_student = true
is_teacher = false

 String: These are text values composed of a sequence of characters. They


can be enclosed in single quotes (‘…’) or double quotes (“…”).
For example:
My_name = “mohd”
 List: List data types represent an ordered collection of items. They can
contain elements of different data types, such as integers, strings, and even
other lists. Lists can be modified by adding or removing elements using
various built-in methods

For example:

My_list=[1,2,”computer”,[3,4,5]]

 Tuple:

Tuple are similar to lists but are immutable, meaning that they cannot be
modified after they are created. They are often used to store related values
that should not be changed. Tuples can be accessed using indexing, and
individual elements can be unpacked into separate variables.

For example:

My_tuple=(1,”apple”,True)

 Dictionary:

Dictionary data types represent a collection of key-value pairs. They are


often used to store data that can be accessed using a specific key.

For example:

My_dict={“name”:”mohd”,”age:”20”,”is_student”:”true”}
* Types Of Operators:
The operator is a symbol that performs a specific operation between two operands.
Python operators refer to special symbols that perform operations on values and
variables. They allow us to create complex expressions and manipulate the data.
Python supports a variety of operators, each with its own unique purpose and
syntax. The operands in python refer to the values on which the operator operates.
Mostly, operators can carry out arithmetic, relational, and logical operations. The
types of operators used in python are:

o Arithmetic operators
o Assignment operators
o Comparison Operators
o Logical Operators
o Identity Operators
o Membership Operators
o Bitwise Operators

Arithmetic Operator:
The use of arithmetic operators and operands in python takes place to perform
mathematical operations like addition, subtraction, multiplication and division. There
are 7 arithmetic operators in Python:

Addition: The additional operator is “+”. It is used to add 2 values.

Example:

Val1=2

Vl2=3

Res=Val1+Val2

Print(res)
Output:

Subtraction: The subtraction operator is “-”. It is used to subtract 2 values.

Example:

Val1=2

Vl2=3

Res=Val1-Val2

Print(res)

Output:

-1

Multiplication: The multiplication operator is “*”. It is used to multiply 2 values.

Example:

Val1=2

Vl2=3

Res=Val1*Val2

Print(res)

Output:
6

Division: The division operator is “/”. It is used to find the quotient when the division
of the first operand takes place by the second.

Example:

Val1=3

Vl2=2

Res=Val1/Val2

Print(res)

Output:

1.5

Modulus: The modulus operator is “%”. It is used to find the remainder when the
division of the first operand happens by the second.

Example:

Val1=3

Vl2=2

Res=Val1%Val2

Print(res)
Output:

Exponentiation: The exponentiation operator is “**”. It is used to find the


exponential value of the given base and exponent values.

Example:

Val1=2

Vl2=3

Res=Val1**Val2

Print(res)

Output:

Assignment Operators:

The Assignment operators is one the type of operators in python. The assignment
operator is used to assign value to the event, property, or variable. By Using the
assignment operators, the right expression's value is assigned to the left operand. It
assigns the values to the variables. There are multiple types of assignment
operators they are:
1) Python (=) Assign value Operator
This operator assigns values to the left-hand operand from the right-side operand.
Example: 5 = 2+3
In the above example, the right-hand operands are 2 & 3 and have contributed to
construct value 5.
2) Python (+=) Add AND Operator
It adds the value of the right operand to the value of the left-hand operand.
Example: x = 10, x + = 5, which will return the value as 15 by adding the right side
value to the left-hand one. Therefore, the answer is x= 15.
3) Python (-=) Subtract AND Operator
Subtract And operator (-=) subtracts or decreases the value of the left operand by
the value of the right operand and assigns the modified value back to left operand.
For example: if a = 20, b = 10 => a- = b will be equal to a = a- b and therefore, a =
10.
4) Python (*=) Multiply AND Operator
Multiply AND Operator multiplies the value of the left operand by the value of the
right operand and assigns the modified value back to then the left operand. For
example: if a = 10, b = 20 => a* = b will be equal to a = a* b and therefore, a =
200. multiplies the left-hand operand with the right-hand one and returns the value
as output.
Example:
x = 10, x*=5, the answer is x = 50.
5) Python (/=) Divide AND Operator
Divide And operator divides the left-hand operand with the right-hand operand
value and gives the result
Example:
x = 10, x/= 5 the result is x = 2
6) Python (%=) Modulus AND Operator
It divides the value of left-hand operand with the right-hand one and the reminder
that we get through this task will be placed as a value of x.
Example:
x = 10, x%= 5 the result is x = 0
7) Python **= Exponent AND operator
It gives us the exponential value of the left-hand operand when raised to the power
of the value found on the right-hand side.
Example:
x = 10, x**= 5 the result is x = 1,00,000
8) Python (//=) Floor Division
Floor division divides the value found on the left-hand side with the value of the
right-hand operand. The integer value becomes the left-hand Operand value.
Example:
x = 7, x//= 4 the result is x = 1

Comparison Operators

Comparison operators in Python are very important in Python's conditional


statements (if, else and elif) and looping statements (while and for loops). The
comparison operators also called relational operators. Some of the well known
operators are "<" stands for less than, and ">" stands for greater than operator.Python
uses two more operators, combining "=" symbol with these two. The "<=" symbol
is for less than or equal to operator and the ">=" symbol is for greater than or equal
to operator. Python has two more comparison operators in the form of "==" and "!=".
They are for is equal to and is not equal to operators. Hence, there are six
comparison operators in Python and they are listed below in this table:
< Less than a<b

> Greater than a>b

<= Less than or equal to a<=b

>= Greater than or equal to a>=b

== Is equal to a==b

!= Is not equal to a!=b

Comparison operators are binary in nature, requiring two operands. An expression


involving a comparison operator is called a Boolean expression, and always returns
either True or False.

a=5
b=7
print (a>b)
print (a<b)

It will produce the following

output −

False
True

Both the operands may be Python literals, variables or expressions. Since Python
supports mixed arithmetic, you can have any number type operands.

The following code demonstrates the use of Python's comparison operators with
integer numbers −

print ("Both operands are integer")


a=5
b=7
print ("a=",a, "b=",b, "a>b is", a>b)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following

output −

Both operands are integer


a= 5 b= 7 a>b is False
a= 5 b= 7 a<b is True
a= 5 b= 7 a==b is False
a= 5 b= 7 a! = b is True

Logical operators

Logical operators are used to combine Boolean values (True or False) to form more
complex expressions. Python has three logical operators:

 and: Returns True if both operands are True.


a and b
 or: Returns True if either operand is True.
a or b
 not: Reverses the result of its operand.
not a
For example:
the following code will print "True" because both a and b are True:
a = True
b = True
if a and b:
print("True")

The following code will print "True" because a is True:


a = True
b = False
if a or b:
print("True");

The following code will print "False" because a is not False:


a = True
if not a:
print("True")

Logical operators can be used to combine multiple conditions.


For example:
the following code will print "True" only if a is True and b is less than 10:
a = True
b=5
if a and b < 10:
print("True")

Logical operators can also be used to check for multiple conditions in a single
expression.
For example:
the following code will print "True" only if a is True or b is less than 10:
a = False
b=5
if a or b < 10:
print("True")

Remember that Python's logical operators use short-circuit evaluation. This means
that Python will stop evaluating an expression as soon as it can determine the final
result.
For example:
the following code will not print anything because Python knows that the final
result of the expression is False:
a = False
b = True
if a and b:
print("True")

This is because Python evaluates the first operand (a) and sees that it is False.
Since Python knows that the final result of the expression will be False, it does not
need to evaluate the second operand (b).
Short-circuit evaluation can be a useful tool for writing more efficient code.
However, it is important to be aware of its behavior so that you do not accidentally
write code that does not do what you expect it to do.
Identity Operators

As the name says, identity operators are used for locating the memory unit of the

objects, especially when both objects have the same name and can be differentiated

only using their memory location. There are two types of identity operators,

namely the ‘Is’ operator and ‘Is Not’ operator, where Is operator is used for

comparing if the objects are in the same location while returning ‘true’ or ‘false’

values as a result, and Is Not operator is used for comparing if the objects perform

the contrary operation with similar return values. There are two types of identity

operators in Python:

 Is

 Is Not

1. Is operator
Is operator helps users to know if two objects are the same or not? If two objects

refer to the same memory location, then Is operator returns “True.” However, if

two objects refer to separate memory locations, the “Is” operator will return

“False.”

Examples of Is Operator

Given below are the examples o:


Example #1

m = 70
n = 70
if (m is n):
print ("Result: m and n have same identity")
else:
print ("Result: m and n do not have same identity")

Output:

Here both m and n refer to the object; hence if calculates to true(in the above code)

and prints “Result: m and n have the same identity.”Here m and n refer to the value

“70”, which has a memory location of 12546.

Example #2

m = 70

n = "70"
if ( m is n ):
print ("Result: m and n have same identity")
else:
print ("Result: m and n do not have same identity")
Membership Operator

The membership operators are useful for quickly checking whether a particular
value is present in a large dataset, and they can also be used in control statements
to perform different actions based on the presence or absence of a specific element.
In this article, we will discuss what membership operators in Python are, how they
work, and provide some examples to help you understand them better.

Membership operators in Python are operators used to test whether a value exists
in a sequence, such as a list, tuple, or string. The membership operators available
in Python are:

 in: The in operator returns True if the value is found in the sequence.
 not in: The not in operator returns True if the value is not found in the
sequence

Membership operators are commonly used with sequences like lists, tuples, and
sets. They can also be used with strings, dictionaries, and other iterable objects.
Membership operators are useful in scenarios where you need to check whether a
value exists in a sequence or not. By using the in or not in operator, you can easily
check whether a value is present in a sequence or not, without having to loop
through the entire sequence.

Membership operators in Python are commonly used with sequences like lists,
tuples, and sets. They can also be used with strings, dictionaries, and other iterable
objects.

Example of Membership Operator in Python

Let’s have a better understanding of the membership operators in Python with the
help of the following code.

# membership operator in Python


# using "in" operator
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print ("Yes, banana is a fruit!")
# using "not in" operator
if "orange" not in fruits:
print ("Yes, orange is not in the list of fruits")

Output:

Yes, banana is a fruit!

Yes, orange is not in the list of fruits

Explanation:
In the example above, the in membership operator is used to check if "banana" is a
member of the fruits list, and the not in operator is used to check if "orange" is not
a member of the fruits list.

Types of Membership Operators in Python

There are two membership operators in Python i.e., "in" and "not in".

 The "in" operator is used to test whether a value is a member of a sequence.


It returns True if the specified value is found in the sequence and False
otherwise. The "in" operator can be used with sequences like lists, tuples,
strings, sets, and dictionaries.
 The "not in" operator is used to test whether a value is not a member of a
sequence. It returns True if the specified value is not found in the sequence
and False otherwise. The "not in" operator can also be used with sequences
like lists, tuples, strings, sets, and dictionaries.
Difference between ‘in’ and ‘not in’ Membership Operators

The primary distinction between the ‘in’ and ‘not in’ operators is that the ‘in’
checks whether a value exists within a sequence, whereas the ‘not in’ checks
whether a value does not exist within a sequence. In other words, the ‘in’ operator
verifies the presence of a given value, while the ‘not in’ operator verifies its
absence in the sequence.
Here are some examples to illustrate the difference between ‘in’ and ‘not in’
membership operators.

Example of Using ‘in’ Operator in Python


Below we have a code example that shows the working of the in operator in
Python.

Code Implementation:

fruits = ['apple', 'banana', 'orange']

if 'banana' in fruits:

print("Yes, 'banana' is a fruit!")

Output:

Yes, 'banana' is a fruit!

Explanation:
In this example, the ‘in’ operator checks whether the value ‘banana’ is present in
the list of fruits. Since ‘banana’ is present in the list, the condition is True, and the
message is printed.

Example of Using ‘not in’ Operator in Python


The following code shows the usage of the ‘not in’ operator in Python.

Code Implementation:

fruits = ['apple', 'banana', 'orange']

if 'grape' not in fruits:

print("No, 'grape' is not a fruit!")

Output:

No, 'grape' is not a fruit!


Explanation:
In this example, the ‘not in’ operator checks whether the value ‘grape’ is not
present in the list of fruits. Since ‘grape’ is not present in the list, the condition is
True, and the message is printed.

Bitwise operators

Bitwise operators are employed in python to perform bitwise operations on


numbers. The values are first converted to binary, and then manipulations are done
bit by bit, hence the phrase "bitwise operators." The outcome is then displayed in
decimal numbers. Python provides several bitwise operators, including:
Bitwise AND (&): The bitwise AND operator performs a logical AND operation
on each corresponding bit of two operands. It returns 1 only if both bits are 1,
otherwise, it returns 0.
Example:
Python
a = 5 # Binary representation: 101
b = 3 # Binary representation: 011
result = a & b
print(result)
Output: 1
Bitwise OR (|): The bitwise OR operator performs a logical OR operation on each
corresponding bit of two operands. It returns 1 if either bit is 1, otherwise, it
returns 0.
Example:
Python
a = 5 # Binary representation: 101
b = 3 # Binary representation: 011
result = a | b
print (result)
Output: 7

Bitwise XOR (^): The bitwise XOR operator performs a logical XOR operation on
each corresponding bit of two operands. It returns 1 if the bits are different,
otherwise, it returns 0.
Example:
Python
a = 5 # Binary representation: 101
b = 3 # Binary representation: 011
result = a ^ b
print(result)
Output: 6

Bitwise NOT (~): The bitwise NOT operator inverts each bit of the operand. It
changes 1 to 0 and 0 to 1.
Example:
Python
a = 5 # Binary representation: 101
result = ~a
print(result)
Output: -6

Bitwise Left Shift (<<): The bitwise left shift operator shifts the bits of the
operand to the left by the specified number of positions. It fills the vacated
positions with zeros.
Example:
Python
a = 5 # Binary representation: 101

result = a << 2
print(result)
Output: 20
Bitwise Right Shift (>>): The bitwise right shift operator shifts the bits of the
operand to the right by the specified number of positions. It discards the rightmost
bits.
Example:
Python
a = 20 # Binary representation: 10100

result = a >> 2
print(result)
Output: 5
Bitwise operators are commonly used in low-level programming tasks, such as bit
manipulation, data packing/unpacking, and hardware control. They can also be
used for more advanced applications, such as cryptography and image processing.
* Python Collections (Arrays):
An array is defined as a collection of items sorted at contiguous memory locations.
An array is like a container that holds similar types of multiple items together, this
helps in making calculation easy and faster. The combination of arrays helps to
reduce the overall size of the program. If you have a list of items that are stored in
multiple variables.

for example:

Animal1 = “Dog”

Animal2 = “Tiger”

Animal3 = “Lion”

Animal4 = “Elephant”

Animal5 = “Deer”

Then you can combine these all in a single variable in form of an array.

In python, the array can be handled by a module called “array”, which is helpful if
we want to manipulate a single type of data value. Below are two important terms
that can help in understanding the concept of an array.

1. Element: Each item stored in an array is called an element.


2. Index: The location of each element is defined by a numerical value
called index. Each element in an array has an index value by which it
can be identified.

Array Representation

The array can be declared in multiple ways depending upon the programming
language we are using. But few points are important that need to consider while
working with an array:
1. The starting index of an array is 0
2. Each element in an array is accessible by its index
3. The length or size of an array determines the capacity of the array to
store the elements
4.
The syntax for Array Representation

arrayName = array.array (dataType, [array,items])

Creating Python Array

In Python, the array can be created by importing the array module. You can now
create the array using array.array(). Instead of using array.array() all the time, you
can use “import array as arr”, the arr will work as an alias and you can create an
array using arr.array(). This alias can be anything as per your preference.

variable_name = array(typecode, [value_list])

For Example:

import array as arr

myarray = arr.array ( ‘i’, [1, 2, 3, 4, 5])

In the above code, the letter ‘i’ represents the type code and the value is of integer
type.

Here is a detailed explanation of the main collection data types in Python:

**Lists**

- Ordered collection of elements indexed by integer values starting from 0

- Written with square brackets []

- Can contain elements of different data types like strings, integers etc.
- Elements can be accessed by their index. List[0] refers to the first element.

- Lists are mutable. Elements can be added, deleted or updated in place.

```python

nums = [1, 2, 3]

nums.append(4) # Adds 4 at end of list

nums[0] = 5 # Updates first element to 5

print(nums) # [5, 2, 3, 4]

```

**Tuples**

- Ordered collection of elements indexed by integer values starting from 0

- Written with parentheses ()

- Can contain elements of different data types

- Immutable - cannot add, delete or modify elements after creation

- Appropriate for fixed data

```python

colors = ("red", "blue", "green")

print(colors[1]) # Access using index

```
**Sets**

- Unordered collection of unique elements

- Elements cannot be accessed via index. Only iteration is supported

- Written with curly braces {}

- Mainly used for mathematical set operations like union, intersection

- Mutable - can add or delete elements

```python

set1 = {1, 2, 3}

set2 = {3, 4, 5}

set1.update([4, 5]) # Add multiple elements

print (set1 & set2) # Prints intersection

```

**Dictionaries**

- Collection of key-value pairs

- Keys need to be unique and can be strings, integers etc

- Values can be any python data type

- Written with curly braces {}

- Elements accessed via keys rather than position

```python

student = {"name": "John", "age": 20, "skills": ["Python", "Math"]}

print(student["skills"]) # Prints list of skills


* Loop Control Statement:
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when
you need to execute a block of code several number of times.

Programming languages provide various control structures that allow for more
complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple


times. The following diagram illustrates a loop statement −

Python programming language provides following types of loops to handle looping


requirements.

Sr.No. Loop Type & Description

while loop
1
Repeats a statement or group of statements while a given condition is
TRUE. It tests the condition before executing the loop body.
for loop
2
Executes a sequence of statements multiple times and abbreviates the code
that manages the loop variable.

nested loops
3
You can use one or more loop inside any another while, for or do..while
loop.
Loop Control Statements

Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed.

Python supports the following control statements. Click the following links to
check their detail.

Let us go through the loop control statements briefly

Sr.No. Control Statement & Description

break statement
1
Terminates the loop statement and transfers execution to the statement
immediately following the loop.

continue statement
2
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.

pass statement
3
The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
Here is a program demonstrating the use of loop control statements in Python:

```python

# Program to show loop control statements

items = [1, 2, 3, 4, 5]

# Using break

for item in items:

if item == 3:

print ("Hit 3, breaking out!")

break

print(item)

print ("Loop exited early by break")

# Using continue

for item in items:

if item % 2 != 0:

continue

print (item, "is even")


print("Skipped odd numbers")

# Using pass

for item in items:

pass # No operation

print ("Loop with pass did nothing")

# Using else

for item in items:

print(item)

else:

print("Loop iteration complete")

```

Output:

Hit 3, breaking out!

Loop exited early by break

2 is even
4 is even

Skipped odd numbers

Loop with pass did nothing

Loop iteration complete

This program shows example usage of all loop control statements in Python - break,
continue, pass and else inside for loops.

The output shows how the flow gets altered for different control statements from the
normal execution.

Explaination of program:
```python
items = [1, 2, 3, 4, 5]
```
- Defines a list `items` that will be used to iterate over in the for loops.
```python
# Using break
for item in items:
```
- Starts a for loop to iterate over items list

```python
if item == 3:
print("Hit 3, breaking out!")
break
```
- Checks if current item is 3, prints a message and executes `break` to exit the loop
completely.

```python
print(item)
```
- Prints each item, but this will not execute for 3 because `break` was hit earlier.

```python
print("Loop exited early by break")
```
- Prints a message to indicate loop was terminated early by `break`.

```python
# Using continue
for item in items:
if item % 2 != 0:
continue
```
- Starts another loop over items. Inside loop, use `continue` to skip odd items.

```python
Print (item, "is even")
```
- This print statement only executes for even numbers since odds were skipped.

```python
Print ("Skipped odd numbers")
```
- Prints message to indicate odd numbers were skipped.

```python
# Using pass
for item in items:
pass
```
- Starts loop but `pass` means no operation is done inside loop body.
```python
Print ("Loop with pass did nothing")
```
- Indicates the pass loop did nothing.
```python
# Using else
for item in items:
print (item)
else:
print ("Loop iteration complete")
```
- Prints all items in loop using else to execute code block on clean completion.
So in summary, this program demonstrates how all the loop control statements can
be used by altering execution of the for loop.
* Python Functions:
A function is a block of code which only runs when it is called. we can pass data,
known as parameters, into a function. A function can return data as a result. A
function is a reusable block of code that can be called to perform a specific task.
Functions help break our program into smaller modular parts that are organized
and reusable.

In python, a function definition has the following syntax:


```python
def function_name(parameters):
statement(s)
return value
```
- `def`- keyword is used to define a function
- `function_name` - name given to the function
- `parameters` - arguments that will be passed to function, optional
- `statement(s)` - block of statements to execute
- `return` - optional, value to return from function

**Example**:
```python
def add_numbers(a, b):
sum = a + b
return sum

result = add_numbers(5, 7)
print(result) # 12
```
We define `add_numbers` function that accepts two arguments `a` and `b` and
returns their sum. This can be reused easily anywhere.

Some key points about functions:


- Functions encapsulate code in a way that it can be reused
- Functions improve modularization and code organization
- Python has many built-in functions like `print()`, `len()` etc.
- We can call functions from other functions

**Program to demonstrate Functions**


Here is a small program with examples of different functions:
```python
# Function without arguments
def show_message():
print("Welcome to Python!")

# Function with arguments


def area(radius):
area = 3.14*radius**2
print ("Area:", area)

# Function that returns a value


def sum_numbers (n1, n2):
total = n1 + n2
return total
show_message()
area(5)
s = sum_numbers(10, 20)
print(s)
```

Output:
```
Welcome to Python!
Area: 78.5
30
```
This demonstrates different ways functions can be defined and used in a Python
program.
* Python Lambda:
Python lambda functions are small, anonymous functions that can take any number
of arguments, but can only have a single expression. They are not defined using the
`def` keyword. Instead lambda keyword is used.

**Lambda Function Syntax**


```python
lambda arguments: expression
```
Here arguments are the input parameters (optional) and expression is a python
statement that gets evaluated and returned.

**Lambda Function Example**


```python
double = lambda x: x*2
print(double(5)) #10
```
This function takes a number and returns double its value. No name is given to the
function.

**Key Characteristics of Lambda Functions**


- They are small anonymous functions created dynamically at run-time
- Only single statement or expression, multiple are not allowed
- No return statement required, the expression result is automatically returned
- Very useful in areas requiring passing functions as arguments or doing small
calculations
**Program demonstrating Lambda Functions**
```python
# Square lambda function
square = lambda x: x**2
print(square(3))

# List sorting based on second element


points = [[1, 4],[5, 2],[3, 6]]
points.sort(key=lambda x: x[1])
print(points)

# Map numbers to square


nums = [1, 2, 3, 4]
squared_nums = map(lambda x: x**2, nums)
print(list(squared_nums))
```
Output:
```
9
[[5, 2], [1, 4], [3, 6]]
[1, 4, 9, 16]
```
So in summary, lambda functions provide a concise way to create small, unnamed
functions in Python which are especially useful when passing functions as
arguments or doing minor data processing tasks.
* Python Classes and objects:
Object-Oriented Programming (OOP):
• is a programming paradigm that focuses on designing software using objects
and classes.
• In Python, OOP is integral, allowing you to create reusable and organized
code. Here's an in-depth exploration of OOP concepts in Python
• Improved code reusability: OOP code can be reused more easily than
procedural code because it is organized around classes and objects. This can
save time and effort when developing large software projects.
• Enhanced code maintainability: OOP code is easier to maintain than
procedural code because it is more modular and less interconnected. This
can make it easier to fix bugs and add new features
Classes and Objects:
• Class: A blueprint that defines the properties (attributes) and behaviors
(methods) of objects.
• Object/Instance: Objects are instances of classes. They have their own set of
attributes and methods that can be used to store data and perform operations.
• Access Control: In Python, attributes and methods can be public, protected,
or private using naming conventions.
**Python Classes and Objects**

Classes provide a means of bundling data and functionality together. Creating a


new class creates a new type of object, allowing new instances of that type to be
made. Each class instance can have attributes attached to it for maintaining its
state.
**Class Definition Syntax:**
class ClassName:
# Instance attributes
def __init__(self, attr1, attr2):
# Constructor
def method_name(self, arg):
# Class methods
```
- `class` keyword indicates start of class definition
- `ClassName` - name given to the class
- `__init__()` method - constructor which gets called when new instance is created
- Other methods defined indicate functionality this type of object supports

**Creating Objects**
Objects can be created from a class as follows:
```
obj1 = ClassName(attr1, attr2) # Create object and initialize
obj1.attribute = value # Access attributes
obj1.method() # Call methods
```
**Example:**
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
print("Hello, my name is", self.name)
p1 = Person ("John", 36)
p1. greet()
print(p1.name)
print(p1.age)
```
Output:
```
Hello, my name is John
John
36
```
In this example, a Person class is defined with a constructor initializing name and
age attributes. Greet () method prints a greeting. p1 object is created which can
access class properties and methods.
So in essence, classes define a blueprint consisting of data and behaviors while
objects allow creating instances of these types with real data associated with them.
* Python Modules:
The Module is defined as to be the same as a code library. A file containing a set of
functions you want to include in your application. Python modules are files
containing Python code that can be imported into other Python files. They allow
you to reuse code, organize your code into smaller units, and share code with
others. Modules are a fundamental part of Python programming and are essential
for creating larger, more complex programs. Modules allow logical organization
and reuse of code. Modules can be libraries shipped with Python or created by
programmers.

```python

# module.py

variable = 10

def function ():

# Logic

class ClassName:

# Class definition

```

**Importing Modules**

To reuse modules, they need to be imported in Python script using `import`


statement:

```python

import module
print(module.variable)

module.function()

```

`module.object` syntax is used to access module attributes after importing.

**Program showing Module Usage**

```python

# Import built-in math module

import math

print(math.pi)

print(math.sqrt(16))

# Import local module

import module

print(module.variable)

module.function()

```

So modules organizing code into reusable logical units which can be imported into
other Python code. Python ships with standard library containing modules offering
commonly used utility. We can also create our own module files.

Benefits of Using Modules


Modules provide several advantages in Python programming:
1. Code Reusability: Modules allow you to write code once and use it multiple
times in different parts of your program or even in different programs
altogether. This eliminates code duplication and promotes code reuse.
2. Modular Programming: Modules encourage modular programming by
breaking down large, complex programs into smaller, more manageable
units. This makes code more organized, easier to understand, and simpler to
maintain.
3. Encapsulation: Modules encapsulate code and data, hiding implementation
details and exposing only the necessary functions or variables to other
modules. This promotes information hiding and code abstraction.
4. Sharing and Collaborating: Modules can be easily shared with others,
allowing for collaboration and code reuse between programmers. This is
particularly useful in open-source projects and team-based development.

Examples of Using Modules in Python

There are numerous examples of how modules are used in Python. Some common
examples include:
1. The Standard Library: The Python Standard Library contains a vast
collection of modules that provide various functionalities, such as file
operations, networking, data manipulation, and more.
2. Third-party Libraries: There are countless third-party libraries available for
Python, providing specialized tools and functionalities for various domains,
such as web development, machine learning, data analysis, and scientific
computing.
3. Custom Modules: Programmers often create their own modules to organize
their code, share it with others, or encapsulate reusable functionalities for
specific tasks or projects.

Conclusion
Python modules are an essential part of the language, enabling modular
programming, code reuse, and information hiding. They play a crucial role in
organizing large programs, sharing code with others, and leveraging existing
libraries to build powerful applications. Understanding and utilizing modules
effectively is a fundamental skill for any Python programmer.
* Python PIP:

PIP stands for "Package Installer for Python". It is a package management system
used to install, upgrade, and manage software packages written in Python. PIP is
the de facto standard for installing Python packages and is widely used by Python
developers.PIP offers several advantages for managing Python packages:

1. Ease of Use: PIP provides a simple and user-friendly command-line


interface for installing and managing packages.
2. Package Repository: PIP has access to a vast repository of Python
packages, including the Python Package Index (PyPI), which contains
thousands of open-source packages.
3. Dependency Resolution: PIP automatically resolves package dependencies,
ensuring that all the required libraries are installed when you install a
package.
4. Virtual Environments: PIP supports virtual environments, allowing you to
isolate packages for specific projects without interfering with other projects
or the system-wide Python installation.
Installing Packages with PIP

To install a package using PIP, simply open a terminal or command prompt and
run the following command:

pip install <package-name>


For example, to install the requests package, you would run:
pip install requests
This command will download the requests package from the PyPI and install it in
your current Python environment.
Upgrading Packages with PIP

To upgrade an existing package to the latest version, use the following


command:

pip install --upgrade <package-name>


For instance, to upgrade the requests package to the latest version, you would run:
pip install --upgrade requests
Uninstalling Packages with PIP

To uninstall a package, use the following command:

pip uninstall <package-name>


For example, to uninstall the requests package, you would run:
pip uninstall requests
Managing Packages with PIP

PIP provides additional commands for managing packages, such as:

 pip list: Lists all installed packages.


 pip show <package-name>: Displays information about a specific package.
 pip freeze: Generates a list of installed packages and their versions.

PIP is an essential tool for Python developers, providing a convenient and efficient
way to install, upgrade, and manage Python packages. By utilizing PIP, you can
ensure that you have the necessary libraries available to develop and maintain your
Python applications.
* Python Try and Except:
The try-except block in Python is a fundamental error handling mechanism that
allows you to catch and handle exceptions that occur during program execution. It
provides a structured way to deal with unexpected errors and maintain the
program's stability.Before understanding about the exception handlling we first
need to understand the difference between error and exception. so, what are
errors.? errors are the problems in a program due to which the program stops the
execution.the execution. and now exceptions. Exceptions are nothing but the
problems that can occur during the Program execution which can be Caught and
handled within the Program itself. The exception does not stop the execution of
program whereas, of the error directly stops the program. These exceptions are
caused by the typical mistakes by the programmer or the coder. When the
exception occurs the normal flow of the Program is interruped and control is
transferred to an exception handler. The exceptions can be like: Syntax errors, Type
errors, name errors, key-value errors, zero division errors.
To handle the exceptions the simple way in Python is to use try and except block.
let us see what is try block. The toy block is used check some code for errors that is
the code inside the toy block will execute when there is no error found in the
program and where as the code inside the except block will execute whenever the
code in the try block encounters the errors to continue the flow of Program. If the
try block does not get executed that means if any exception left or occurs then the
try block will be skipped and the except block will be executed. If any exception
Occurs within the code of except block it cannot handle it so it then Passed on to
the outer try statements.Then also if the exception is left or unhandled then it leads
to the Stopping of execution. The execution gets stopped.
* Program:
Here's an example of a try-except block:
Python
try:
# Code that might throw an exception
Print (10 / 0)
except ZeroDivisionError:
print ("Division by zero is not allowed")
In this example: the try block attempts to divide 10 by 0. This operation will raise
a Zero Division Error exception, which is caught by the except block. If the
exception occurs, the code inside the except block will be executed, and the
message "Division by zero is not allowed" will be printed to the console.
Anatomy of the try-except Block:
1. try Block: This block contains the code that might throw an exception. If an
exception occurs, the normal flow of the program is interrupted, and control
is transferred to the except block.
2. except Block(s): This block contains the code that will be executed if an
exception occurs. You can have multiple except blocks, each specifying a
specific exception type to handle.
3. except Exception as e:: This is a generic except block that catches any type
of exception. The as e: clause captures the exception object and assigns it to
the variable e. You can use e to access information about the exception, such
as its type and message.
4. else Block (Optional): This block is executed if no exception occurs in the
try block. It's typically used to perform cleanup tasks or handle successful
execution scenarios.
5. finally Block (Optional): This block is always executed, regardless of
whether an exception occurs or not. It's commonly used to release resources,
close files, or perform cleanup actions that should happen in any case.

Benefits of Using try-except:

1. Improved Program Stability: By catching and handling exceptions, you


prevent unexpected errors from crashing the program and allow it to
continue functioning gracefully.
2. Error Handling and Recovery: The except blocks provide a way to handle
specific exceptions and perform appropriate actions, such as displaying error
messages, logging the error, or taking corrective measures.
3. Error Diagnosis: Capturing exceptions and their information allows you to
diagnose the problem, identify the cause of the error, and implement fixes or
improvements.
4. Clean Code and Separation of Concerns: Separating error handling logic
from the main program code makes the code cleaner, more readable, and
easier to maintain.
* Python Reg Ex:
Regular expressions, often abbreviated as regex or reg exp, are a powerful tool for
matching patterns in text. They provide a concise and expressive way to search,
extract, and manipulate text based on specific patterns or combinations of
characters. Regex is widely used in various applications, including text processing,
data validation, and natural language processing.

Basic Syntax of Regular Expressions

Regular expressions use a combination of literal characters, special metacharacters,


and quantifiers to define patterns. Here's a breakdown of the basic components:
1. Literal Characters: Literal characters match themselves exactly. For
instance, the regex a match the letter "a" in any text.
2. Metacharacters: Metacharacters have specific meanings and represent
patterns. Some common metacharacters include:
 . (dot): Matches any single character except for a newline.
 * (asterisk): Matches the preceding character zero or more times.
 + (plus sign): Matches the preceding character one or more times.
 ? (question mark): Matches the preceding character zero or one time.
 ^{} (caret and curly braces): Matches the beginning of the string followed
by the specified pattern zero or more times.
 }$ (dollar sign and curly braces): Matches the end of the string preceded by
the specified pattern zero or more times.
3. Quantifiers: Quantifiers specify the number of times a pattern should
match. The most common quantifiers are *, +, and ?, as mentioned earlier.

Matching Patterns with Regular Expressions

To match patterns using regular expressions, you can use the re module in Python.
The re module provides functions for searching, extracting, and replacing text
based on regex patterns.
Example Program: Matching Phone Numbers
Here's an example of a Python program that uses regular expressions to match
phone numbers in a text:
Python
import re

text = "My phone number is 123-456-7890. You can also reach me at 987-654-
3210."

pattern = r"\d{3}-\d{3}-\d{4}" # Regex pattern for phone numbers

matches = re.findall(pattern, text)

for match in matches:


print(match)
In this example, the re.findall() function is used to find all occurrences of the
phone number pattern in the text variable. The pattern r"\d{3}-\d{3}-\d{4}"
matches a sequence of three digits, a hyphen, three digits, another hyphen, and four
digits. The matches list contains all the extracted phone numbers.
* Python File Handling:
File handling is the process of reading, writing, and manipulating data stored in
files. Python provides built-in functions and modules for performing various file
operations, enabling you to interact with and manage files effectively.

Opening Files in Python


You can open files, read from them, write to them, and close them when you are
done.

To open a file, you use the open() function. This takes the file path and mode as
parameters. Some common modes are:

- "r" - Read mode which is used when you want to read data from the file.
- "w" - Write mode which overwrites existing contents if the file exists. If the file
does not exist, it creates a new file.
- "a" - Append mode which appends new data to the end of the file if it exists. If
the file does not exist, it creates a new file.

Here is an example program that opens a file in write mode, writes some data, and
closes the file:

```python
f = open("test.txt", "w")
f.write("This is my sample file")
f.close()
```

This opens test.txt in the current directory for writing. It writes the text "This is my
sample file" to the file and then closes it.

To read from a file, you need to open it in read mode:

```python
f = open("test.txt", "r")
data = f.read()
print(data)
f.close()
```

This opens test.txt for reading, reads the contents into the data variable, prints the
data, and closes the file.

Some key points:

- Always close files when done to free resources


- Use exception handling to catch errors like file not found
- Use modes like append to add data instead of overwriting
- Use readline() or readlines() to read line by line

So in summary, Python files give access to persistent storage allowing programs to


save and retrieve data from files on the disk.
The fundamental step in file handling is opening a file. The open() function is used
for this purpose. It takes two arguments: the file path and the access mode. The
access mode specifies how the file will be opened, such as for reading (r), writing
(w), or appending (a).
Python
file = open("myfile.txt", "r") # Open file for reading
Reading Files in Python
Once a file is opened, you can read its contents using various methods. The read()
method reads the entire file into a string. The readline() method reads one line from
the file at a time.
Python
file_content = file.read() # Read entire file
line = file.readline() # Read one line
Writing to Files in Python
To write data to a file, use the write() method. You can pass a string or any other
data type to write to the file.
Python
file.write("This is a new line of text.") # Write to file
Closing Files in Python
It is crucial to close files after you are done using them. The close() method
releases the resources associated with the file and ensures data integrity.
Python
file.close() # Close the file
Example Program: Copying a File
Here's an example of a Python program that copies the contents of one file to
another:
Python
def copy_file(source_file, destination_file):
with open(source_file, "r") as source:
with open(destination_file, "w") as destination:
for line in source:
destination.write(line)

if __name__ == "__main__":
copy_file("myfile.txt", "newfile.txt")
In this example, the copy_file() function takes two arguments: the source file path
and the destination file path. It uses the with statement to open both files in context
manager mode, ensuring that the files are automatically closed when the block
exits. The for loop iterates over each line in the source file and writes it to the
destination file.

Conclusion
File handling in Python is an essential skill for working with text data and
interacting with the file system. By understanding the basic concepts and utilizing
the provided functions and modules, you can effectively read, write, and
manipulate data stored in files, enabling you to perform various tasks such as data
analysis, configuration management, and logging.
* Python MySQL and MySQL CRUD:

Python MySQL

Python MySQL is a combination of two powerful technologies: the Python


programming language and the MySQL relational database management system
(RDBMS). Together, they enable developers to build robust and efficient
applications that interact with MySQL databases.

MySQL CRUD

CRUD stands for Create, Read, Update, and Delete, which are the four
fundamental operations that can be performed on data in a database. These
operations are essential for managing and manipulating data effectively.
Python MySQL CRUD Examples
Here are some examples of how to perform CRUD operations in Python using
MySQL:

Create
Python

import mysql.connector

# Establish connection to MySQL database


db = mysql.connector.connect(host="localhost", user="username",
password="password", database="database_name")

# Create a cursor object


cursor = db.cursor()

# Create a table named 'customers'


sql = """CREATE TABLE customers (
customer_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
email VARCHAR(255)
)"""
cursor.execute(sql)

# Close the connection


db.close()

Read
Python

import mysql.connector

# Establish connection to MySQL database


db = mysql.connector.connect(host="localhost", user="username",
password="password", database="database_name")

# Create a cursor object


cursor = db.cursor()

# Select all data from the 'customers' table


sql = "SELECT * FROM customers"
cursor.execute(sql)

# Fetch all results as a list of tuples


results = cursor.fetchall()

# Print the results


for row in results:
print(row)

# Close the connection


db.close()

Update
Python

import mysql.connector

# Establish connection to MySQL database


db = mysql.connector.connect(host="localhost", user="username",
password="password", database="database_name")
# Create a cursor object
cursor = db.cursor()

# Update the email address for customer with ID 1


sql = "UPDATE customers SET email = '[email protected]' WHERE
customer_id = 1"
cursor.execute(sql)

# Commit the changes to the database


db.commit()

# Close the connection


db.close()

Delete
Python

import mysql.connector

# Establish connection to MySQL database


db = mysql.connector.connect(host="localhost", user="username",
password="password", database="database_name")

# Create a cursor object


cursor = db.cursor()

# Delete customer with ID 2


sql = "DELETE FROM customers WHERE customer_id = 2"
cursor.execute(sql)

# Commit the changes to the database


db.commit()

# Close the connection


db.close()
These examples demonstrate the basic CRUD operations that can be performed
using Python and MySQL. With these building blocks, you can develop more
complex applications that interact with your MySQL database.
* Multithreading:
Before jumping on our concept let us recall how the computer program execution
is done. So as we know that normally a program gets executed sequentially i.e
from start to end. For example: if it starts with 1 then it will execute in a sequence
like 1 and then 2 and 3 and so on>>>After hearing the' multithreading what comes
to your mind. I strongly believe that you got an idea of the half word right ; multi
what does multi means : more than one, nothing but many . And the word thread
means smallest unit of execution with in a process. And the process is nothing but
the Program which is in execution.so, multithreading is nothing but a mechanism
in which one main task is divided into multiple sub-tasks. That means we will take
one single Task and divide that into multiple tasks. This makes the execution faster
in an overlapping manner as compared to single thread.
For example:
let us suppose that a faculty member assigned some task to a student. think that
arranging the files. If the student arranges those 100 Files alone and or if he divides
the task like 1-50, 50-100, and ask his/her friends to help. And then he/she merges
tha all files and submit it to the faculty. In the same way in python programming,
the program with a single thread and then it is divided into multiple thread and
after the sub threads completes their work they are merged back into the main
thread. so, which scenario the task win be Completed in efficient and fast way. so
that would be this Scenario right. This Scenario is nothing but our, multithreading.
so now let us see the multithreading in the context of code.
Program:
" Import threading
Import time

def count_up ( ) :
for i in range (1, 1001):
Print (i)
time. sleep (o. 1)
def count_ down ( ):
for i in range(1000,-1,-1)
Print (i)
time. sleep (o.1)

thread 1 =threading.thread(target=count_up)
thread =threading.thread(target=count_down)

thread 1. Start ( )
thread 2. Start ( )

thread 1. Join ( )
thread 2. Join ( )
Explaination:
The functions count_up and count_down in the provided multithreading example
are commonly referred to as counter functions. These functions perform the simple
task of incrementing or decrementing a counter variable and printing the updated
value. In this case, count_up increments the counter from 1 to 1000, while
count_down decrements the counter from 1000 to 1.

Explanation of the code:

1. Importing the threading module: The first line of the code imports the
threading module, which provides the necessary functions for creating and
managing threads.
2. The time.sleep(0.1) statement introduces a slight delay between each
number, allowing the threads to interleave and run concurrently.
3. Creating threads: Two threads are created using the threading.Thread class.
The target parameter specifies the function to be executed by the thread, and
the args parameter provides a tuple of arguments to be passed to the
function.
4. Starting threads: The start() method of each thread object is called to start
the execution of the thread. Once a thread is started, it runs concurrently
with the main thread.
5. Waiting for threads to finish: The join() method of each thread object is
called to wait for the thread to finish executing before proceeding. This
ensures that the main thread does not exit before the worker threads have
completed their tasks.
6. Printing message from the main thread: Once both threads have finished
executing, the main thread prints a message indicating that it has completed
its work.

You might also like