0% found this document useful (0 votes)
3 views120 pages

Python Unit1

The document provides an introduction to Python programming, including its history, features, applications, and installation process. It covers fundamental concepts such as variables, data types, operators, and identifiers, along with examples and rules for naming variables. Additionally, it discusses constants, comments, and the use of the IDLE environment for coding in Python.

Uploaded by

rudravsharma2580
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 views120 pages

Python Unit1

The document provides an introduction to Python programming, including its history, features, applications, and installation process. It covers fundamental concepts such as variables, data types, operators, and identifiers, along with examples and rules for naming variables. Additionally, it discusses constants, comments, and the use of the IDLE environment for coding in Python.

Uploaded by

rudravsharma2580
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

ANSHU SHARMA

PYTHON
UNIT-1

Anshu Sharma
ANSHU SHARMA

Introduction
• An ordered set of instruction to be executed by a computer to carry out
a specific task is called a program.
• As we all know computer understand only 0 and 1’s which is called
machine language or low language.
• This led to advent of high level programming language like Python,
C++, java, PHP which is easier for human being to understand.

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA

History
• Python is a programming language which was created by Guido Van
Rossum in 1991.
• It got its name from a BBC comedy show “Monty Python Flying
Circus”.

Anshu Sharma
ANSHU SHARMA

• Python is a high-level language.


• It is a free and open source language
• It is case- sensitive
• It is designed to be simple and easy to learn
• Python supports the object-oriented programming approach, allowing
developers to create applications with organized and reusable code
• It is an interpreted language
• Python has a lot of functionality, which makes it popular to use.

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA

Features of Python
• Easy to learn, read and maintain
• Broad standard library
• Interactive mode
• Portability and compatibility
• Extendable
• Databases and scalable

Anshu Sharma
ANSHU SHARMA

Applications of Python
• Web Development
• Desktop Application
• Software Development
• Database Assess
• Network Programming
• Game Development
• 3D Graphics

Anshu Sharma
ANSHU SHARMA

Python Installation
For Windows:
Step 1: Visit the official Python website at [Link]/downloads/
Step 2: Click on the “Download Python “ button
Download the Python installer that matches your system requirements.
• Step 3: Run Executable Installer
On the Python Releases for Windows page, select the link for the latest
Python 3.x.x release
Step 4: Add Python to the path
Step 5: Verify (Go to the command prompt, type python –version)

Anshu Sharma
ANSHU SHARMA

Step 1: [Link]

Anshu Sharma
ANSHU SHARMA

Step 2:

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA

Type cmd on search bar

Anshu Sharma
ANSHU SHARMA

IDLE in Python
• IDLE stands for Integrated Development and Learning Environment.
It is the default editor and interpreter provided with Python.
Uses of IDLE
• Helps to write Python programs
• Allows users to run and test code easily
• Provides an interactive shell for quick execution of commands
Main Features
• Python Shell: Executes commands instantly
• Editor Window: Used to write and save complete programs

Anshu Sharma
ANSHU SHARMA

Python Shell

Anshu Sharma
ANSHU SHARMA

Variables
• A variable is a named location used to store data in memory.
• It is a container that holds data that can be changed later in the
program.
In Python, we don’t actually assign a value to the variables. Instead,
Python gives the reference of the object to the variable.
• There is no need to specify the datatype of a variable
• A variable is a name given to a memory location.

Anshu Sharma
ANSHU SHARMA

• Variables are used to store values that can be used later in the program.
• For example, you can create a variable called "name" and assign it a
value like this:

• Here, "name" is the variable name, and "Yadnyesh" is the value


assigned to it. Python will automatically determine the type of the
variable based on the value assigned to it. In this case, the type of the
variable "name" is a string.

Anshu Sharma
ANSHU SHARMA
• Variables in Python can hold different types of data, such as numbers,
strings, lists, or even more complex objects.
• You can change the value of a variable at any time by assigning a new
value to it. For instance:

Anshu Sharma
ANSHU SHARMA
• Python also allows you to perform operations on variables. For
example, you can add, subtract, Multiple divide variables containing
numbers. You can even combine variables of different types using
operators. For instance:

Anshu Sharma
ANSHU SHARMA

Rules for Naming Variables


Variable name must start with a letter or underscore (_)
It can contain letters, numbers, and underscore
Variable names are case-sensitive
Cannot use Python keywords like if, for, class
Valid Variable Names: student_name = "Rahul"
_age = 21
marks1 = 90
Invalid Variable Names:
1name = "Anshu" # cannot start with number
class = 10 # keyword not allowed
my-name = 5 # hyphen not allowed
Anshu Sharma
ANSHU SHARMA

Types of Variables
• Integer → x = 10
• Float → y = 5.5
• String → name = "Python"
• Boolean → is_active = True

Anshu Sharma
ANSHU SHARMA

Program to show different types of variables


# Integer variable # String variable
a = 10 c = "Python Programming"
print("Value of a =", a) print("\nValue of c =", c)
print("Type of a =", type(a)) print("Type of c =", type(c))

# Float variable # Boolean variable


b = 25.5 d = True
print("\nValue of b =", b) print("\nValue of d =", d)
print("Type of b =", type(b)) print("Type of d =", type(d))

Anshu Sharma
ANSHU SHARMA

Identifiers
• In Python, identifiers are the names you use to name variables, functions,
classes, or other objects. They are like labels that help you identify different
parts of your program.
Rules for Python Identifiers:
• Must start with a letter (A-Z or a-z) or an underscore (_).
Examples: name, _value
• Cannot start with a digit (0-9).
Invalid: 1name
• Can only contain letters, digits, and underscores.
Valid: my_var1
Invalid: my-var, my var
• Cannot use Python keywords (like if, else, while, def, etc.) as identifiers.
• Case-sensitive: name, Name, and NAME are different identifiers.
Anshu Sharma
ANSHU SHARMA

• Examples of Valid Identifiers: • Examples of Invalid Identifiers:


➢Age ➢3name (starts with a digit)
➢total_score ➢my-name (contains a hyphen)
➢_myVar ➢for (a Python keyword)
➢count123

Anshu Sharma
ANSHU SHARMA

Constants
• Constants in Python are values that you decide should not change
while your program is running.
• How to Use Constants:
• Python doesn’t have a special way to create constants, so we use a naming
convention to show that a value is constant.
• Write constant names in ALL CAPITAL LETTERS.
• Examples:
• DAYS_IN_A_WEEK = 7
• PI = 3.14159
• GRAVITY = 9.8

Anshu Sharma
ANSHU SHARMA

Comments
• In Python, comments are lines of text in your code that are ignored by
the Python interpreter. They are used to explain what the code does,
make it more readable, or temporarily disable a piece of code.
• Types of Comments
• Single line comment:
Start the comment with # symbol
X=10 # this is single line comment

Anshu Sharma
ANSHU SHARMA

• Multi-line Comments
For longer explanations, use triple quotes (''' or """) to write comments
across multiple lines.
'‘’
This is a multi-line comment.
'''

Anshu Sharma
ANSHU SHARMA

Keywords
• In Python, keywords are special words that have a specific meaning
and purpose in the programming language. They are reserved and
cannot be used as names for variables, functions, or other identifiers.

Anshu Sharma
ANSHU SHARMA

Basic Data Types

Anshu Sharma
ANSHU SHARMA

Data types in Python refer to the different kinds of values that can be assigned
to variables. They determine the nature of the data and the operations that can
be performed on them. Python provides several built-in data types, including:
Numeric:
• Python supports different numerical data types, including integers (whole
numbers), floating-point numbers (decimal numbers), and complex numbers
(numbers with real and imaginary parts).
• Integers (int): Integers represent whole numbers without any fractional part.
For example, age = 25.
• Floating-Point Numbers (float): Floating-point numbers represent numbers
with decimal points or fractions. For example, pi = 3.14.
• Complex Numbers (complex): Complex numbers have a real and imaginary
part. They are donated by a combination of a real and imaginary number,
suffixed with j or J. For example, z = 2 + 3j.
Anshu Sharma
ANSHU SHARMA

a=5
• print(type(a))
Output: <class ‘int’>

b = 5.0
• print(type(b))
Output: <class ‘float’>

c = 2 + 4j
• print(type(c))
Output: <class ‘complex no’>
Anshu Sharma
ANSHU SHARMA
Strings (str): Strings represent sequences of characters enclosed within single or double
quotes. For example, name = "John".
s = 'Welcome to the Geeks World'
print(s)
# check data type
print(type(s))
# access string with index
print(s[1])
print(s[2])
print(s[-1])

OUTPUT: Welcome to the Geeks World


<class 'str'>
e
l
d

Anshu Sharma
ANSHU SHARMA
Lists (list): Lists are ordered sequences of elements enclosed in square
brackets. Each element can be of any data type.
For example, numbers = [1, 2, 3, 4].
# Empty list
• a = []
# list with int values
• a = [1, 2, 3]
• print(a)
# list with mixed int and string
• b = ["Geeks", "For", "Geeks", 4, 5]
• print(b)
Output
• [1, 2, 3]
• ['Geeks', 'For', 'Geeks', 4, 5]

Anshu Sharma
ANSHU SHARMA

Example: Basic List Operation


fruits = ["apple", "banana", "orange"]
print(fruits) ['apple', 'banana', 'orange’]

[Link]("grape")
print(fruits) ['apple', 'banana', 'orange', 'grape']

[Link]("orange")
print(fruits) ['apple', 'banana', 'grape']

Anshu Sharma
ANSHU SHARMA

• Tuples (tuple): Tuples are similar to lists but are immutable, meaning
their elements cannot be changed once defined. They are enclosed in
parentheses.
• For example, coordinates = (3, 4).

# initiate empty tuple


• t1 = ()
• t2 = ('Geeks', 'For')
• print("\nTuple with the use of String: ", t2)
Output
• Tuple with the use of String: ('Geeks', 'For')

Anshu Sharma
ANSHU SHARMA
Set:
Sets (set): Sets are unordered collections of unique elements enclosed in
curly braces. They are useful for mathematical operations such as union,
intersection, and difference.
For example, fruits = {'apple', 'banana', 'orange’}.
Sets can be created by using the built-in set() function with an iterable
object or a sequence by placing the sequence inside curly braces,
separated by a ‘comma’. The type of elements in a set need not be the
same; various mixed-up data type values can also be passed to the set.

s2 = set(["Geeks", "For", "Geeks"])


print("Set with the use of List: ", s2)
OUTPUT: Set with the use of List: {'Geeks', 'For'}

Anshu Sharma
ANSHU SHARMA
• Dictionary:
Dictionaries are key-value pairs enclosed in curly braces. Each value is
associated with a unique key, allowing for efficient lookup and
retrieval. For example, person = {'name': 'John', 'age': 25, 'city': 'New
York'}.
• Boolean:
Boolean (bool): Booleans represent truth values, either True or False.
They are used for logical operations and conditions. For example,
is_valid = True.

Anshu Sharma
ANSHU SHARMA

• Sequence Type:
Sequences represent a collection of elements and include data types like
strings, lists, and tuples. Strings are used to store textual data, while lists
and tuples are used to store ordered collections of items.

Anshu Sharma
ANSHU SHARMA

# Example variables of different types


•a=5
• b = "Hello"
• c = [1, 2, 3]
• d = {'name': 'Alice', 'age': 30}

# Using type() to get data types


• print(type(a)) # <class 'int'>
• print(type(b)) # <class 'str'>
• print(type(c)) # <class 'list'>
• print(type(d)) # <class 'dict'>

Anshu Sharma
ANSHU SHARMA

Operators in Python
• Operators in Python are symbols or special characters that are used to perform
specific operations on variables and values.
• Here are some important categories of operators in Python:
• Arithmetic operators
• Comparison operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators

Anshu Sharma
ANSHU SHARMA
Arithmetic Operators:
Arithmetic operators in Python are used to perform mathematical calculations on numeric
values. The basic arithmetic operators include:
• Addition (+): Adds two operands together. For example, if we have a = 10 and b = 10,
then a + b equals 20.

• Subtraction (-): Subtracts the second operand from the first operand. If the first operand is
smaller than the second operand, the result will be negative. For example, if we have
a = 20 and b = 5, then a - b equals 15.

• Division (/): Divides the first operand by the second operand and returns the quotient. For
example, if we have a = 20 and b = 10, then a / b equals 2.0.

• Multiplication (*): Multiplies one operand by the other. For example, if we have a = 20
and b = 4, then a * b equals 80.

• Modulus (%): Returns the remainder after dividing the first operand by the second
operand. For example, if we have a = 20 and b = 10, then a % b equals 0.

Anshu Sharma
ANSHU SHARMA

• Exponentiation (**) or Power: Raises the first operand to the power of the second
operand. For example, if we have a = 2 and b = 3, then a ** b equals 8.

• Floor Division (//): Provides the floor value of the quotient obtained by dividing
the two operands. It returns the largest integer that is less than or equal to the
result. For example, if we have a = 20 and b = 3, then a // b equals 6.

Anshu Sharma
ANSHU SHARMA
Operator Name Definition Syntax Example
+ Addition Adds two numbers. a+b 10 + 5 = 15
Subtracts second number from
- Subtraction a-b 10 - 5 = 5
first.

* Multiplication Multiplies two numbers. a*b 10 * 5 = 50

Divides first number by


/ Division a/b 10 / 5 = 2.0
second (gives float result).
Returns remainder after
% Modulus a%b 10 % 3 = 1
division.
Divides and returns only
// Floor Division a // b 10 // 3 = 3
integer part (quotient).

Raises first number to the


** Exponentiation a ** b 2 ** 3 = 8
power of second.

Anshu Sharma
ANSHU SHARMA
Comparison Operators:
Comparison operators in Python are used to compare two values and
return a Boolean value (True or False) based on the comparison.
Common comparison operators include:
• Equal to (==): Checks if two operands are equal.
• Not equal to (!=): Checks if two operands are not equal.
• Greater than (>): Checks if the left operand is greater than the right
operand.
• Less than (<): Checks if the left operand is less than the right operand.
• Greater than or equal to (>=): Checks if the left operand is greater than
or equal to the right operand.
• Less than or equal to (<=): Checks if the left operand is less than or
equal to the right operand.
Anshu Sharma
ANSHU SHARMA
Operator Name Definition Syntax Example

Checks if two values are


== Equal to a == b 10 == 10 → True
equal.

Checks if two values are


!= Not equal to a != b 10 != 5 → True
not equal.

Checks if first value is


> Greater than a>b 10 > 5 → True
greater than second.

Checks if first value is less


< Less than a<b 10 < 5 → False
than second.

Checks if first value is


>= Greater than or equal to greater than or equal to a >= b 10 >= 10 → True
second.

Checks if first value is less


<= Less than or equal to a <= b 5 <= 10 → True
than or equal to second.
Anshu Sharma
ANSHU SHARMA

• a = 13
• b = 33
• print(a > b) // False
• print(a < b) // True
• print(a == b) // False
• print(a != b) // True
• print(a >= b) // False
• print(a <= b) // True

Anshu Sharma
ANSHU SHARMA

Assignment Operators:
Assignment operators are used to assign values to variables.
They include:
• Equal to (=): Assigns the value on the right to the variable on the left.

• Com pound a ssignment opera tors ( +=, -=, *=, /=) : Perform the specified
arithmetic operation and assign the result to the variable.

Anshu Sharma
Operator Name Definition Syntax ANSHU SHARMA
Example

= Assignment Assigns value to a variable. a = 10 a = 10

+= Add and Assign Adds value and assigns result. a += b a = 5; a += 2 → 7

Subtracts value and assigns


-= Subtract and Assign a -= b a = 5; a -= 2 → 3
result.
Multiplies value and assigns
*= Multiply and Assign a *= b a = 5; a *= 2 → 10
result.
Divides value and assigns
/= Divide and Assign a /= b a = 10; a /= 2 → 5.0
result.
Finds remainder and assigns
%= Modulus and Assign a %= b a = 10; a %= 3 → 1
result.

Performs floor division and


//= Floor Divide and Assign a //= b a = 10; a //= 3 → 3
assigns result.

**= Power and Assign Raises power and assigns result. a **= b a = 2; a **= 3 → 8

Anshu Sharma
ANSHU SHARMA
a = 10
b=a
• print(b) // 10
b += a
• print(b) //20
b -= a
• print(b) //10
b *= a
• print(b) //100

Anshu Sharma
ANSHU SHARMA

Logical Operators:
Logical operators in Python are used to perform logical operations on
Boolean values. The main logical operators are:
• Logical AND (and): Returns True if both operands are True,
otherwise False.
• Logical OR (or): Returns True if at least one of the operands is True,
otherwise False.
• Logical NOT (not): Returns the opposite Boolean value of the
operand.

Anshu Sharma
ANSHU SHARMA

Operator Name Definition Syntax Example

Returns True if both


and Logical AND a and b (10>5 and 5>2) → True
conditions are True.

Returns True if at least one


or Logical OR a or b (10>5 or 5<2) → True
condition is True.

Reverses the result (True


not Logical NOT not a not(10>5) → False
becomes False).

Anshu Sharma
ANSHU SHARMA
Bitwise Operators:
Bitwise operators perform operations on individual bits of binary numbers.
Some common bitwise operators in Python are:
• Bitwise AND (&): Performs a bitwise AND operation on the binary
representations of the operands.
• Bitwise OR (|): Performs a bitwise OR operation on the binary
representations of the operands.
• Bitwise XOR (^): Performs a bitwise exclusive OR operation on the binary
representations of the operands.
• Bitwise complement (~): Inverts the bits of the operand. Left shift (<<):
Shifts the bits of the left operand to the left by the number of positions
specified by the right operand.
• Right shift (>>): Shifts the bits of the left operand to the right by the number
of positions specified by the right operand.
• Right shift (>>): Shifts the bits of the left operand to the right by the number
of positions specified by the right operand.
Anshu Sharma
ANSHU SHARMA
Operator Name Definition Syntax Example

& Bitwise AND Sets bit to 1 if both bits are 1. a&b 5&3→1

Sets bit to 1 if any


| | Bitwise OR `a
one bit is 1.

Sets bit to 1 if bits are


^ Bitwise XOR a^b 5^3→6
different.

Inverts all bits (gives negative


~ Bitwise NOT ~a ~5 → -6
result).

Shifts bits to the left


<< Left Shift a << n 5 << 1 → 10
(multiplies by 2).

Shifts bits to the right (divides


>> Right Shift a >> n 5 >> 1 → 2
by 2).
Anshu Sharma
ANSHU SHARMA

BITWISE AND (&)


a = 5 # 0101
A&B
A (Bit) B (Bit) b = 3 # 0011
(Result)
0 0 0 print(a & b)

0 1 0
0101
1 0 0 & 0011
------
1 1 1
0001 = 1

Anshu Sharma
ANSHU SHARMA

BITWISE OR ( | )
a = 5 # 0101
A|B
A (Bit) B (Bit) b = 3 # 0011
(Result)
0 0 0 print(a & b)

0 1 1
0101
1 0 1 | 0011
------
1 1 1
0111 = 7

Anshu Sharma
ANSHU SHARMA

BITWISE XOR ( ^ )
a = 5 # 0101
A^B
A (Bit) B (Bit) b = 3 # 0011
(Result)
0 0 0 print(a & b)

0 1 1
0101
1 0 1 ^ 0011
------
1 1 0
0110 = 6

Anshu Sharma
ANSHU SHARMA

BITWISE XOR ( ^ )
a = 5 # 0101
A^B
A (Bit) B (Bit) b = 3 # 0011
(Result)
0 0 0 print(a & b)

0 1 1
0101
1 0 1 ^ 0011
------
1 1 0
0110 = 6

Anshu Sharma
ANSHU SHARMA

BITWISE NOT ( ~ )
a = 5 # 0101
A (Bit) ~A (Result) print(~a)
0 1
1010
1 0

Anshu Sharma
ANSHU SHARMA

Left Shift Operator (<<) Right Shift Operator (>>)


a << n a >> n
a = number a = number
n = bits n = bits
Multiply by 2 Divide by 2
a << n = a * (2^n) a>>n=a//(2^n)

5 << 2 = 5 * 4 = 20 15>>3= 15//(2^3)= 1

Anshu Sharma
ANSHU SHARMA

Precedence

NOT → Left, right →And → Xor →OR


Highest Lowest

Anshu Sharma
ANSHU SHARMA

Membership Operators:
Membership operators are used to test whether a value is a member of a
sequence (e.g., string, list, tuple).
They include:
• In: Returns True if the value is found in the sequence.
• Not in: Returns True if the value is not found in the sequence.

Anshu Sharma
ANSHU SHARMA

Operator Name Definition Syntax Example

Returns True if a value


in Membership IN is present in a x in y "a" in "apple" → True
sequence.

Returns True if a value


Membership NOT "z" not in "apple" →
not in is not present in a x not in y
IN True
sequence.

Anshu Sharma
ANSHU SHARMA
Control Statements
If statement
An `if` statement in Python checks whether a condition is true or false. If the
condition is true, the code inside the `if` block runs. If false, the code is
skipped. It's used to make decisions in the program, executing specific
actions based on conditions
Syntax:
if condition: # Code to execute if the condition is True

Example:
x = 10
if x > 5: # Check if x is greater than 5
print("x is greater than 5")
Output:
x is greater than 5
Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA
if-else
If the condition is false, you can use else to specify what happens.

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

Output:
x is less than or equal to 5

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA

if-elif-else
You can check multiple conditions using elif
if [condition 1]:
print statement
elif [ condition 2]:
print statement
elif [condition 3]:
print statement
else:
statement

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA

Example:
temperature = 25
if temperature < 15:
print("It's cold.")
elif temperature < 30:
print("It's warm.")
else:
print("It's hot.")
Output:
It's warm.

Anshu Sharma
ANSHU SHARMA
Match-case statement
Powerful way to handle conditional logic
Used for pattern matching, similar to a switch statement
Syntax:
match variable:
case pattern1:
# Code to execute if variable matches pattern1
case pattern2:
# Code to execute if variable matches pattern2
case _:
# Default case (if no pattern matches)

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA
Example:
color = "red"
match color:
case "red":
print("The color is red.")
case "blue":
print("The color is blue.")
case "green":
print("The color is green.")
case _:
print("Unknown color.")
Output:
The color is red
Anshu Sharma
ANSHU SHARMA

Loops
• While Loop
A while loop in Python is used to repeatedly execute a block of code as
long as a given condition is True. Once the condition becomes False, the
loop stops.
Syntax:
while condition:
# Code to execute as long as the condition is True

Anshu Sharma
ANSHU SHARMA
Example:
count = 0
while count < 5: # Condition: keep looping while count is less than 5
print(count)
count += 1 # Increment count by 1 each time

Output:
0
1
2
3
4

Anshu Sharma
ANSHU SHARMA
• For loop
A for loop in Python is used to iterate over a sequence and execute a block of
code for each item in that sequence.
Syntax:
for item in sequence:
# Code to execute for each item in the sequence

Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry Anshu Sharma
ANSHU SHARMA
Example:
for i in range(5): # Loop from 0 to 4
print(i)

Output:
0
1
2
3
4

Anshu Sharma
ANSHU SHARMA

Using Range in for loop:


• The range() function in Python is co mmo n ly used in for loops
to iterate over a sequence of numbers.
• Here's a basic rundown of how it works:
• start: The starting value of the sequence (inclusive). If omitted, it
defaults to 0.
• stop: The ending value of the sequence (exclusive). The loop will run
until it reaches this value.
• step: The amount by which the sequence is
incremented. If omitted, it defaults to 1.

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA
for i in range (1,11,1):
print(i)

Output:
1
2
3
4
5
6
7
8
9
10

Anshu Sharma
ANSHU SHARMA
• Nested Loop
A nested loop in Python means putting one loop inside another. This is useful
when we need to repeat actions within another repeated action.
Example: Printing rows and column
for row in range(1, 4): # Outer loop for rows
for column in range(1, 4): # Inner loop for columns
print(f"Row {row}, Column {column}")

Output:
Row 1, Column 1
Row 1, Column 2
Row 1, Column 3
Row 2, Column 1
Row 2, Column 2
Row 2, Column 3
Row 3, Column 1
Row 3, Column 2
Row 3, Column 3
Anshu Sharma
ANSHU SHARMA
• Break
The break statement in Python is used to exit a loop prematurely. When
break is encountered, the program immediately stops the execution of the
current loop (either for or while) and continues with the code after the loop.
Example:
for i in range(1, 6):
if i == 3: # When i is 3, exit the loop
break
print(i)
print("Loop ended.")

Output:
1
2
Loop ended.
Anshu Sharma
ANSHU SHARMA
• Continue
The continue statement in Python is used to skip the current iteration of a
loop and move to the next iteration.
• Example:
for i in range(1, 6):
if i == 3: # Skip when i is 3
continue
print(i)
• Output:
1
2
4
5

Anshu Sharma
ANSHU SHARMA
String
• In Python, a string is a sequence of characters enclosed within single quotes
('), double quotes ("), or triple quotes (''' or """). Strings are one of the most
commonly used data types and are immutable, meaning their content cannot
be changed after they are created.
• # Single-quoted strings
string1 = 'Hello, World!'
• # Double-quoted strings
string2 = "Python Strings"
• # Triple-quoted strings (used for multi-line strings or docstrings)
string3 = '''This is a
multi-line string'''
• string4 = """Another example
of a multi-line string"""

Anshu Sharma
ANSHU SHARMA

1. Single-Quoted Strings
Use single quotes (') to define a string:

string1 = 'Hello, World!'


print(string1) # Output: Hello, World!

Anshu Sharma
ANSHU SHARMA

2. Double-Quoted Strings
Use double quotes (") to define a string:

string2 = "Python Programming"


print(string2) # Output: Python Programming

Anshu Sharma
ANSHU SHARMA

3. Triple-Quoted Strings
Use triple quotes (''' or """) for:

string3 = '''This is a
multi-line string'''
print(string3)

Anshu Sharma
ANSHU SHARMA

Length of String
• The length of a string in Python can be determined using the built-in
len() function.
• Syntax:
len(string)
Example:
string = "Hello, World!"
length = len(string)
print(length) # Output: 13

Anshu Sharma
ANSHU SHARMA

Concatenation of a String
• Concatenation of strings in Python means joining two or more strings
together. This is done using the + operator
• Example:
string1 = "Hello"
string2 = "World"
result = string1 + " " + string2
print(result) # Output: Hello World

Anshu Sharma
ANSHU SHARMA

“a”+”b” # output: ab
“1”+”2” #output:12
“123”+”abc” #output:123abc

* you cannot add no and string using +


Ex:
‘python’+’123’ #0ut: ‘python123’

Anshu Sharma
ANSHU SHARMA

• If you try to add a string to a non-string (like a number), you’ll get an


error. Convert the non-string using str():
• Example:
name = "Alice"
age = 25
result = name + " is " + str(age) + " years old."
print(result) # Output: Alice is 25 years old.

Anshu Sharma
ANSHU SHARMA

Strings are immutable. They cannot be changed


S=‘python’
So S[0]=p
If we want to change the 0th value i.e s[0]=‘I’
It will show an error

Anshu Sharma
ANSHU SHARMA

Indexing

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA

S=‘aaa’
• Id(s)
• 375269286

S=‘bbb’
• id(s)
• 8789695
• Have different memory location

Anshu Sharma
• S=‘python’ ANSHU SHARMA

• Len(s) # 6
• S(len(s)-1) #n [6-1=5 and in forward indexing n is at 5]

• String=‘wonder’
for ch in string: # one by one character to traverse kia hai
print(ch) #if we want in one line (print(ch,end=‘ ‘)
#output:wonder
Output: print(ch,end=‘$’)
#out:w$o$n$d#e$r
W
O
N
D
E
R
Anshu Sharma
ANSHU SHARMA

• Srting=‘wonder’
• For I in range(0,len(string)) # I me ky aiega index
• Print(i) # out:012345
• Agar hume character print karana hai toh hum jse likhte the s[0]
• Haya bhi print(string[i],end=‘ ‘)

Anshu Sharma
ANSHU SHARMA

String Replication
5*”@” will result into @@@@@
“go”*3 will result into gogogo

• We cannot multiply string and string using * only number *number or


string * number is allowed
• s=‘python’
• S*50 #it will print python 50 times
• ‘ab’*’df’
• # it will show error
Anshu Sharma
ANSHU SHARMA

• S1=123
• S2=456
• S3=‘abc’
• S4=‘des’
• Print(s1+s2) #579
• Print(s3+s4) #’abcdes’
• Print(s1*s3) #print abc 123 times
• Print(s3*s4) #show error

Anshu Sharma
ANSHU SHARMA

• str=1=“program”
• Str2=“python”
• Str3=“Python”

• Str1==str2 #false
• str1!=str2 #true
• Str2==“python” #true
• Str2>str3 #true
• Str3<str1 #true

Anshu Sharma
ANSHU SHARMA

• A-Z = 65-90
• a-z =97-122
• 0-9 = 48-57

• Ord(‘A) # 65 [ ASCII value ]


• Ord(‘a’) #97
• Chr(97) # ‘a’ [char]

Anshu Sharma
ANSHU SHARMA

• ‘aaa’==‘aaa’ # true
• ‘aab’<‘aaa’ #false

Anshu Sharma
ANSHU SHARMA

String Slicing
• Slicing is a way to extract portion of a string by specifying the start and end
indexes. The syntax for slicing is string[start:end], where start starting index and
end is stopping index (excluded).
• Syntax: name of string[start:stop:step]
s = “welcome"
# Retrieves characters from index 1 to 3: ‘elc'
print(s[1:4])
# Retrieves characters from beginning to index 2: ‘wel'
print(s[:3])
# Retrieves characters from index 3 to the end: ‘come'
print(s[3:])
# Reverse a string
print(s[::-1]) emoclew
Anshu Sharma
ANSHU SHARMA
• Str=‘welcome’
For I in range(len(str));
Print(I,’:’,str[i])
output: 0:w ……so on
• Str=‘welcome’
Str[2:6]
Output: lcom
• Str[1:6:2]
Output: ecm
• Str[1:5:2]
Output: ec

Anshu Sharma
ANSHU SHARMA
• Str[:4]
Output:welc
• Str[2:]
Output: lcome
• Str[1::2]
Output: ecm
• Str[:4]+str[4:]
Output: welcome
• Str[::-1]
Output: emoclew [output in reverse]

Anshu Sharma
ANSHU SHARMA

Deleting a String
s = "GfG"
# Deletes entire string
del s
• After deleting the string using del and if we try to access s then it will
result in a NameError because the variable no longer exists

Anshu Sharma
ANSHU SHARMA

Common String Methods


• len(): The len() function returns the total number of characters in a
string.
s = "GeeksforGeeks"
print(len(s))
# output: 13

Anshu Sharma
ANSHU SHARMA

• upper() and lower(): upper() method converts all characters to


uppercase. lower() method converts all characters to lowercase.
s = "Hello World"
print([Link]()) # output: HELLO WORLD
print([Link]()) # output: hello world

Anshu Sharma
ANSHU SHARMA

• To make first character capital


• S=input(“string”)
• S=[Link]()
• Print(s)
• Output:
• welcome -→ Welcome

Anshu Sharma
ANSHU SHARMA

Anshu Sharma
ANSHU SHARMA

• text = "Hello, world!"

• # Check if the string starts with "Hello"


• print([Link]("Hello")) # Output: True

• # Check if the string ends with "world!"


• print([Link]("world!")) # Output: True

• # Check multiple options


• print([Link](("Hi", "Hello"))) # Output: True (either hi or hello)
• print([Link](("!", "."))) # Output: True

Anshu Sharma
ANSHU SHARMA

Inserting substring into string


• In Python, you can insert a substring into a string using different methods,
such as string slicing, join(), replace(), or using f-strings.
1. Using String Slicing
You can insert a substring at a specific position using string slicing (str[:index]
+ new_substring + str[index:]).

Example: Insert at a Specific Position


text = "Hello World!"
new_text = text[:6] + "Beautiful " + text[6:] # Insert after "Hello "
print(new_text)
# Output: "Hello Beautiful World!"

Anshu Sharma
ANSHU SHARMA
• 2. Using join() Method
The join() method is useful for inserting between elements when splitting a
string.
Example: Insert After a Space
text = "I love Python"
words = [Link](" ") # Split into a list: ["I", "love", "Python"]
new_text = " ".join([words[0], "really", words[1], words[2]]) # Insert "really"
print(new_text)
# Output: "I really love Python“
Explanation:
split(" ") → Converts string into a list: ["I", "love", "Python"]
" ".join([...]) → Joins words back with a space " " between them.
Anshu Sharma
ANSHU SHARMA
3. Using replace() Method
You can replace a specific word or pattern with a modified version.

Example: Insert Before a Word


text = "I love Python“
new_text = [Link]("Python", "programming in Python")
print(new_text)
# Output: "I love programming in Python"
Explanation:
• replace("Python", "programming in Python")
• replaces "Python" with "programming in Python".
Anshu Sharma
ANSHU SHARMA
• 4. Using F-strings for Dynamic Insertion
F-strings (f"") allow inserting values dynamically.

Example: Insert Using Variables


name = "Alice"
greeting = f"Hello, {name}! Welcome to Python."
print(greeting)
• # Output: "Hello, Alice! Welcome to Python.“
• Explanation: f"Hello, {name}! Welcome to Python." dynamically
inserts "Alice".

Anshu Sharma
ANSHU SHARMA

Formatting Strings
• Using f-strings
The simplest and most preferred way to format strings is by using f-
strings.
name = "Alice"
age = 22
print(f"Name: {name}, Age: {age}")

Output
Name: Alice, Age: 22

Anshu Sharma

You might also like