Python unit-1 notes
Python unit-1 notes
Python:
Python is a versatile and widely-used high-level programming language known
for its simplicity and readability. It was created by Guido van Rossum and first
released in 1991. Python is an interpreted language, which means that you can
write and execute code directly without the need for compilation, making it a
great choice for beginners and experienced programmers alike. There are some
key features and characteristics of Python:
Readability: Python's syntax is designed to be clear and easy to read, with a
minimalistic and consistent structure. This makes it an excellent language for
both writing and maintaining code
Versatility: Python can be used for a wide range of applications, including web
development, data analysis, machine learning, scientific computing,
automation, and more. It has a rich ecosystem of libraries and frameworks to
support these various domains
Interpreted: Python code is executed line by line by the Python interpreter.
This makes it easy to write and test code quickly without the need for a
separate compilation step.
Dynamic Typing: Python uses dynamic typing, which means that you don't
need to declare the data type of a variable explicitly. The interpreter infers the
data type based on the value assigned to it.
Indentation: Python uses indentation (whitespace) to define code blocks, such
as loops and functions. Proper indentation is not just a stylistic choice but is
essential for the code to work correctly.
Large Standard Library: Python comes with a comprehensive standard library
that includes modules for tasks like file handling, regular expressions,
networking, and more. This library saves you from reinventing the wheel and
allows you to perform various tasks out of the box.
Community and Ecosystem: Python has a large and active community of
developers and enthusiasts. This community contributes to the language's
growth and maintains numerous open-source libraries and frameworks.
Cross-Platform: Python is available on multiple platforms, including Windows,
macOS, and various Unix-based systems, making it highly portable.
Variables
In Python, variables are used to store data values. A variable is essentially a
name that refers to a particular value or object in memory.
variable naming rules in python:
=>Python has a set of reserved words (keywords) that cannot be used as
variable names.
=>Avoid using keywords like if, while, for, class, def, and others as variable
names.
=>Variable names should be descriptive, indicating the purpose or content of
the variable.
=>variable names in Python are case-sensitive. This means that Python treats
variable names with different letter casing as distinct and separate variables
=>my_variable and My_Variable are not the same variable. They are treated as
two separate variables due to the difference in letter casing.
=>variables name only contain letters, digits and underscore(_)
=>a variable name cannot stat with a digit.
Valid variable name
Age=21
_colour=”pink”
total_score= 50
my_variable = 42
My_Variable = 100
Invalid variable name
class=10
user-name=”pinky”
1name=”sid”
Scope of variable
1.Local scope:
Local variables are declared and defined within a specific block of code,
typically within a function. They are only accessible within the scope (block)
where they are defined. Local variables are scoped to the function or block in
which they are declared. They cannot be accessed from outside that scope.
Ex 1
def my_function():
x = 10 # x is a local variable
print(x)
output 10
Ex 2
def f():
# local variable
s = "I love python"
print(s)
# function call
f()
output I love python
Ex3
def f():
# local variable
s = "I love python"
print("Inside Function:", s)
# function call
f()
print(s)
output Inside function:I love python
Name error’s’ is not defined
2. Global scope:
Global variables are declared at the top level of a script or module .They are
accessible from anywhere within the program. Global variables are available
throughout the entire program, including all functions and blocks.
Ex1
global_var = 20 #global_var is a global variable
def my_function():
print(global_var) # Accessing global_var from within a function
my_function()
# This will print 20
Ex2
# This function uses global variable s
def f():
print(s)
# Global scope
s = "I love python"
f()
output I love python
ex3
def f():
s = "Me too."
print(s)
# Global scope
s = "I love python"
f()
print(s)
output
Me too.
I love python
Deleting variables
you can delete a variable using the del statement. When you delete a variable,
it is removed from memory, and you can no longer access its value.
x = 10
print(x) # Outputs 10
# Deleting variable x
del x
# Trying to access x after deletion will result in an error
print(x) # This will result in a NameError: name 'x' is not defined
Operators in python:
These operators are fundamental for performing mathematical calculations,
making comparisons, and controlling the flow of your Python programs.
Understanding how to use them effectively is essential for writing Python code
Types of operators in python
Arithmetic
Comparison
Logical
Bitwise
Assignment
Identity
Membership
1.Arithmetic operators:
Arithmetic operators in Python perform basic mathematical operations on
operands. The addition operator (+) adds two values, the subtraction operator
(-) subtracts the right operand from the left, the multiplication operator (*)
multiplies two values, and the division operator (/) divides the left operand by
the right, always producing a floating-point result.
Float division or division(/):quotient returned by this operator is always a float
number, no matter if two numbers are integers.
print(5/5) o/p 1.0
print(10/2) o/p 5.0
print(-10/2) o/p -5.0
print(20.0/2) o/p 10.0
print(-7/-2) o/p 3.5
floor division operator (//):the quotient returned by this operator is
dependent on arguments being passed. If any of the numbers is float, it returns
output in float.The floor division operator (//) rounds down to the nearest
value.
print(5//5) o/p 1
print((3//2) o/p 1
print(10//3) o/p 3
print(-5//2) o/p -3
print(-7//-2) o/p 3
print(-5.0//2) o/p -3.0
print(5.0//2) o/p 2.0
Modulus operator(%): while the modulus operator (%) returns the remainder
when dividing the left operand by the right.
Example: 17 // 3 equals 5
exponentiation operator (**):
the exponentiation operator (**) raises the left operand to the power of the
right. These operators are crucial for performing a wide range of mathematical
calculations in Python.
Example: 2 ** 3 equals 8.
2.Comparison operators:
Comparison operators in Python are used to compare two values and return a
Boolean result (either True or False) based on the comparison. Comparison
operators are sometimes referred to as "relational operators" in Python
1. Equal to ==:
• Example: 5 == 5 evaluates to True because 5 is equal to 5.
2. Not equal to !=:
• Example: 5 != 3 evaluates to True because 5 is not equal to 3.
3. Less than <:
• Example: 3 < 5 evaluates to True because 3 is less than 5.
4. Greater than >:
• Example: 5 > 3 evaluates to True because 5 is greater than 3.
5. Less than or equal to <=:
• Example: 3 <= 5 evaluates to True because 3 is less than or equal to 5.
6. Greater than or equal to >=:
• Example: 5 >= 3 evaluates to True because 5 is greater than or equal to 3.
3.Logical operators:
Logical operators are symbols or words used in computer programming and
mathematics to perform logical operations on boolean values (true or false).
These operators allow you to combine, compare, and manipulate boolean
values to make decisions and control the flow of a program.
The three most common logical operators are:
Logical AND (and) Operator:
The AND operator returns true if both of its operands are true. Otherwise, it
returns False.
x = True
y = False
result = x and y # result is False
Logical OR (or) Operator:
The or operator returns True if at least one of the operands is True. It returns
False only when both operands are False
x = True
y = False
result = x or y # result is True
Logical NOT (not) Operator:
The not operator is a unary operator that negates the boolean value of its
operand. It returns True if the operand is False, and False if the operand is True.
x=True
print(not x)
result is False
5.The assignment operator:
The assignment operator in programming languages is used to assign a value to
a variable. It is often denoted by the equals sign (=) and is used to store a value
in a variable.
x=5 # Assign the value 5 to the variable x
name = "John" # Assign the string "John" to the variable name
is_true = True # Assign the boolean value True to the variable is_true
x = 10
example-2:
x=10
x += 5 # Equivalent to x = x + 5, so x becomes 15
example 3
y = 20
y -= 3 # Equivalent to y = y - 3, so y becomes 17
z=7
z *= 2 # Equivalent to z = z * 2, so z becomes 14
6.Bitwise operators:
Bitwise operators in Python are used to manipulate individual bits of integers.
Python provides several bitwise operators:
& (Bitwise AND): This operator performs a bitwise AND operation on each pair
of corresponding bits of two integers. It returns a new integer where each bit is
1 only if the corresponding bits in both operands are 1.
a = 5 # 0101 in binary
b = 3 # 0011 in binary
result = a & b # 0001 in binary
print(result) # Output: 1
| (Bitwise OR): This operator performs a bitwise OR operation on each pair of
corresponding bits of two integers. It returns a new integer where each bit is 1
if at least one of the corresponding bits in both operands is 1.
a = 5 # 0101 in binary
b = 3 # 0011 in binary
result = a | b # 0111 in binary
print(result) # Output: 7
^ (Bitwise XOR): This operator performs a bitwise XOR (exclusive OR) operation
on each pair of corresponding bits of two integers. It returns a new integer
where each bit is 1 if the corresponding bits in the operands are different.
a = 5 # 0101 in binary
b = 3 # 0011 in binary
result = a ^ b # 0110 in binary
print(result) # Output: 6
~ (Bitwise NOT): This operator performs a bitwise NOT operation on an integer,
flipping all its bits (changing 1s to 0s and vice versa). It is a unary operator.
a = 5 # 0101 in binary
result = ~a # -6 (two's complement of 0101 is 1010)
print(result)
<< (Left Shift): This operator shifts the bits of an integer to the left by a
specified number of positions. It effectively multiplies the integer by 2 raised to
the power of the shift count.
a = 5 # 0101 in binary
result = a << 2 # 20 (010100 in binary)
print(result)
>> (Right Shift): This operator shifts the bits of an integer to the right by a
specified number of positions. It effectively divides the integer by 2 raised to
the power of the shift count (integer division).
a = 20 # 010100 in binary
result = a >> 2 # 5 (0101 in binary)
print(result)
7. Idenity operator: is and is not are identity operators. Both check if two
values are located on same same part of memory. Two variables that are equal
do not imply that they are identical.
a=10
b=20
c=a
print( a is not b) o/p True
print(a is c) o/p True
8 .membership operator: in and not in are membership operators that are
used to test whether a value or variable is in a sequence.
in – True if value is found in sequence
not in- True if value is not found in the sequence
my_list=[1,2,3,4,5]
print(3 in my_list) o/p True
print(10 in my_list) o/p False
Type Conversion:
In Python, you can perform data type conversions to change the type of a value
from one data type to another.
1.Implicit Type Conversion :
Python automatically performs implicit type conversion when you mix different
data types in expressions. For example, when you add an int and a float,
Python converts the int to a float before performing the addition. Generally
python promotes conversion of lower data type to higher data type.
a=5 # int
b = 2.5 # float
c= a + b # Implicit conversion of 'a' to float
print(type(c))
o/p 7.5
<class ‘float’>
2.Explicit Type Conversion (Type Casting):
Explicit type conversion also known as type casting.You can explicitly convert
one data type to another using built-in functions.
there are some common type casting functions
int():it Converts into an integer
float_number = 3.14 integer_number = int(float_number) # Converts 3.14 to 3
float():it Converts to a floating-point number.
integer_number = 42 float_number = float(integer_number) # Converts 42 to 42.0