PYTHON
PYTHON
* 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.
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.
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 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.
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.
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
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.
1. Consistent Indentation: All statements within a block must have the same
level of indentation.
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")
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.
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.
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.
There are certain set of rules which should be followed while assigning the
variable and their values. They are:
for example-
is_student = true
is_teacher = false
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:
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:
Example:
Val1=2
Vl2=3
Res=Val1+Val2
Print(res)
Output:
Example:
Val1=2
Vl2=3
Res=Val1-Val2
Print(res)
Output:
-1
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:
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
== Is equal to a==b
a=5
b=7
print (a>b)
print (a<b)
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 −
output −
Logical operators
Logical operators are used to combine Boolean values (True or False) to form more
complex expressions. Python has three logical operators:
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
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
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.
Let’s have a better understanding of the membership operators in Python with the
help of the following code.
Output:
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.
There are two membership operators in Python i.e., "in" and "not in".
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.
Code Implementation:
if 'banana' in fruits:
Output:
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.
Code Implementation:
Output:
Bitwise operators
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.
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
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.
For Example:
In the above code, the letter ‘i’ represents the type code and the value is of integer
type.
**Lists**
- 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.
```python
nums = [1, 2, 3]
print(nums) # [5, 2, 3, 4]
```
**Tuples**
```python
```
**Sets**
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
```
**Dictionaries**
```python
Programming languages provide various control structures that allow for more
complicated execution paths.
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.
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
items = [1, 2, 3, 4, 5]
# Using break
if item == 3:
break
print(item)
# Using continue
if item % 2 != 0:
continue
# Using pass
pass # No operation
# Using else
print(item)
else:
```
Output:
2 is even
4 is even
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.
**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.
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.
**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
# Logic
class ClassName:
# Class definition
```
**Importing Modules**
```python
import module
print(module.variable)
module.function()
```
```python
import math
print(math.pi)
print(math.sqrt(16))
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.
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:
To install a package using PIP, simply open a terminal or command prompt and
run the following command:
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.
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."
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.
```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.
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
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
Read
Python
import mysql.connector
Update
Python
import mysql.connector
Delete
Python
import mysql.connector
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.
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.