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

Python unit-1 notes

Python is a high-level, versatile programming language known for its readability and simplicity, created by Guido van Rossum in 1991. It features dynamic typing, a large standard library, and is widely used in various applications such as web development and data analysis. The document also covers variables, their scope, operators, operator precedence, and the importance of indentation in defining code blocks.
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)
3 views

Python unit-1 notes

Python is a high-level, versatile programming language known for its readability and simplicity, created by Guido van Rossum in 1991. It features dynamic typing, a large standard library, and is widely used in various applications such as web development and data analysis. The document also covers variables, their scope, operators, operator precedence, and the importance of indentation in defining code blocks.
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/ 19

Python unit-1

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

Operator precedence and associativity:


Operator precedence and associativity are important concepts in programming
and mathematics that determine the order in which operators are evaluated
when expressions are processed. These rules ensure that expressions are
evaluated consistently and correctly.
Operator Precedence: Operator precedence defines the order in which
operators are evaluated in an expression. Operators with higher precedence
are evaluated before operators with lower precedence. This helps avoid
ambiguity in expressions.
Operator Associativity:Operator associativity defines the order in which
operators of the same precedence are evaluated when they appear in a
sequence . There are two common types of associativity
Left Associative: Operators are evaluated from left to right.
Example:
Z=5 - 3 + 1
print(z) # 3 output
z=6 / 2 * 3
print(z) # 9
x = y = 10
print(x) # 10
Right Associative: Operators are evaluated from right to left.
Example:
z=2 ** 3 ** 2
•First, 3 ** 2 is evaluated, which is 9.
• Then, 2 ** 9 is evaluated, which is 512.
print(z) # 512

operator precedence from highest to lowest and their associativity


precedence Operator Description Associativity
1 () parenthesis L-R
2 ** exponentiation R-L
3 +x,-x,~x Unary plus, unary R-L
minus, bitwise not
4 *, /,//,% Multiplication,division, L-R
floor division, modulus
5 +, - Addition, subtraction
6 <<, >> Bitwise shift L-R
7 & Bitwise and L-R
8 ^ Bitwise xor L-R
9 | Bitwise or L-R
10 ==, !=, >,<,>=,<=, is Comparison, identity, L-R
,is not, in, not in membership
11 Not Logical not R-L
12 And Logical and L-R
13 Or Logical or L-R
14 If-else conditional R-L
15 =, +=, -=, *= assignment R-L
python block:
In Python, code blocks or code sections are defined using
indentation(whitespace). Python uses indentation to indicate blocks of code,
rather than using curly braces {} or other delimiters like some other
programming languages. This is one of the distinctive features of Python's
syntax. Indentation is essential for proper code execution and is used to group
statements together within loops, conditional statements, functions, and
classes.
Indentation Level: Statements that are at the same indentation level are
considered part of the same block of code. Typically, each level of indentation
is four spaces, but you can also use tabs or any consistent number of spaces as
long as it's the same throughout your code
Colon (:): A colon is used at the end of a line to indicate the start of an
indented block. This is commonly used in conditional statements, loops,
function definitions, and class definitions.
There is example of Python code that demonstrates the use of indentation to
define code blocks:
# Example 1
if True:
# statement1
print("This is inside the if block.")
print("Still inside the if block.")
# The if block ends here, as indicated by the change in indentation level
# This is not inside any block
print("This is not indented and is outside any block.")
# Example 2: Iterate over a range of numbers
for i in range(1, 6):
print(i)
example of python code block with code:
x=10
if x>5:
print(“x is graeter than 5”) # this line is part of the if block
else:
print(“x is not graeter than 5”) # this line is part of the else block

Data types in python:


Data types are the classification or categorization of data items. It represents
the kind of value that tells what operations can be performed on a particular
data. Since everything is an object in python programming, data types are
actually classes and variables are instances (object) of these classes. The
following are the standard or built-in data types in Python
It tells the Python interpreter how to handle a specific piece of data and
determines what operations can be performed on that data. Python is a
dynamically typed language, which means that the data type of a variable is
determined automatically based on the value assigned to it
Key features of data type
There are some key points regarding data types in python:
1.Dynamic typing:
Dynamic typing, also known as duck typing, is a feature of Python and some
other dynamically-typed programming languages. In dynamically-typed
languages like Python, the data type of a variable is determined at runtime,
rather than being explicitly declared by the programmer. This means you can
assign different types of values to the same variable without explicitly
specifying its data type.
2.No Type Declarations: You do not need to declare the data type of a variable
when you create it. You simply assign a value to a variable, and Python figures
out the data type based on the assigned value.
x = 5 # x is an integer
y = "Hello" # y is a string
3.Dynamic reassignment:
Dynamic reassignment refers to the ability to change the value of a variable
during the execution of a program. In dynamically-typed programming
languages like Python, variables can be reassigned with new values of different
data types as needed, and the variable's type is determined at runtime.
=>In statically-typed languages, such as C++ or Java, variable types are
determined at compile-time, and you cannot easily reassign a variable to a
different data type. In contrast, dynamically-typed languages like Python offer
more flexibility in this regard.
Example:
x = 10 # x is assigned an integer value
print(x) # Output: 10
x = "Hello" # x is reassigned a string value
print(x) # Output: Hello
x = [1, 2, 3] # x is reassigned a list value
print(x) # Output: [1, 2, 3]
4.checking data types:
In Python, you can check the data type of a variable or an object using the
type() function.
Using type():
x = 42
y = "Hello, World!"
z = [1, 2, 3]
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'str'>
print(type(z)) # Output: <class 'list'>
Data types in python:
Integer (int): it Represents whole numbers.
x=5
Floating-Point (float):Represents real numbers with a decimal point
y = 3.14
String (str):Represents sequences of characters, enclosed in either single (' ') or
double (" ") quotes.
Str=”abc”
Boolean (bool):it Represents binary values, True or False.
is_valid = True
List:Represents an ordered collection of elements. Lists can hold elements of
different data types. Lists are mutable, meaning you can change their contents
(add, remove, modify elements).
my_list = [1, 2, "three", 4.0] numbers = [1, 2, 3, 4]names = ["Alice", "Bob",
"Charlie"]
Tuple:Similar to lists but immutable, meaning you cannot change their contents
after creation. Often used for storing a fixed sequence of values
point = (3, 4) dimensions = (10, 20, 30)
Dictionary (dict) :Stores key-value pairs, allowing you to associate values with
unique identifiers ( "keys")
student = { "name": "Bob","age": 20,"grade": "A"}
Set :it is Unordered collections of unique elements.
my_set = {1, 2, 3, 4, 5}

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

str():it Converts into string


my_integer = 42my_string = str(my_integer) # Converts 42 to '42'
list(), tuple(), set():it Converts to lists, tuples, and sets, respectively.
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
my_set = set(my_list)
=>performing some opration on list, tuple and set :
# Creating a list
my_list = [1, 2, 3, 4, 5]
# Adding an element to the list
my_list.append(6)
# Printing the list
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)
# Accessing an element in the tuple
first_element = my_tuple[0]
# Printing the first element
print(first_element) # Output: 1
# Creating a set
my_set = {1, 2, 3, 4, 5}
# Adding an element to the set
my_set.add(6)
# Printing the set
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
else# Code will execute if condition1 2 and 3 are False

You might also like