0% found this document useful (0 votes)
4 views20 pages

Python Notes

The document provides an overview of operators, decision-making statements, loops, and string manipulation in Python. It categorizes operators into arithmetic, assignment, relational, logical, bitwise, membership, and identity operators, and explains their usage with examples. Additionally, it covers decision-making constructs like if statements, loops such as for and while, and various string methods and properties.

Uploaded by

kartikchourey888
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views20 pages

Python Notes

The document provides an overview of operators, decision-making statements, loops, and string manipulation in Python. It categorizes operators into arithmetic, assignment, relational, logical, bitwise, membership, and identity operators, and explains their usage with examples. Additionally, it covers decision-making constructs like if statements, loops such as for and while, and various string methods and properties.

Uploaded by

kartikchourey888
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Operators

Operators are keywords which are used to perform mathematical operations between operands.

 Arithmetic Operators(+,-,%,/,//,*,**)

 Assignment Operators

 Relational Operators

 Logical Operators(and,or,not)

 Bitwise Operators

 Membership Operators(in,not in)

 Identity Operators(is,is not)

Arithmetic Operators
 Used to perform mathematical calculations.

Operator Meaning Example Output


+ Addition 5 + 2 7
- Subtraction 5 - 2 3
* Multiplication 5 * 2 10
/ Division 5 / 2 2.5
// Floor Division 5 // 2 2
% Modulus (Remainder) 5 % 2 1
** Exponent 5 ** 2 25

a = 10

b=3

print(a + b) # 13

print(a // b) # 3

print(a % b) # 1

Assignment Operators
Used to assign values to variables.
Operator Example Meaning
= x = 5 Assign value
+= x += 2 x = x + 2
-= x -= 2 x = x - 2
*= x *= 2 x = x * 2
/= x /= 2 x = x / 2
x=5

x += 3

print(x) # 8

Relational (Comparison) Operators


Used to compare two values. Result is True or False.

Operator Meaning Example


== Equal to 5 == 5 → True
!= Not equal 5 != 3 → True
> Greater than 5 > 3 → True
< Less than 5 < 3 → False
>= Greater than equal 5 >= 5 → True
<= Less than equal 5 <= 3 → False
a = 10

b = 20

print(a < b) # True

Logical Operators
Used to combine conditions.

Operator Meaning
and True if both conditions are True
or True if at least one condition is True
not Reverse the result

a=5

print(a > 2 and a < 10) # True


print(a > 10 or a < 10) # True

print(not(a > 2)) # False

Bitwise Operators
Used to perform operations on binary numbers.

Operator Meaning
& AND
` `
^ XOR
~ NOT
<< Left Shift
>> Right Shift
a = 5 # 101

b = 3 # 011

print(a & b) # 1

print(a | b) # 7

Membership Operators
Used to check whether a value exists in a sequence (list, tuple, string).

Operator Meaning
in Value exists
not in Value does not exist
l = [1, 2, 3, 4]
print(2 in l) # True
print(5 not in l) # True

Identity Operators
Used to compare memory location of two objects.
Operator Meaning
Operator Meaning
is Same object
is not Different object
a = [1,2,3]

b=a

c = [1,2,3]

print(a is b) # True

print(a is c) # False

Decision Making Statements in Python


Decision making statements allow a program to choose different actions based on conditions.

In real life also we take decisions:

 If it is raining → take umbrella


 If marks > 40 → pass
 Else → fail

Same concept is used in Python.

Python decision making statements are:

 if
 if-else
 if-elif-else
 Nested if
 Short-hand if (Ternary operator)

1️⃣ if Statement
🔹 Description:

The if statement is used to execute a block of code only when the condition is True.
If the condition is False, the block is skipped.
🔹 Syntax:
if condition:
statements

🔹 Example:
age = 20

if age >= 18:


print("You can vote")

🔹 Explanation:

 Condition: age >= 18


 It returns True
 So the print statement executes.

If age was 15, nothing would print.

2️⃣ if-else Statement


🔹 Description:

Used when we have two possible situations.


If condition is True → run if block
Otherwise → run else block

🔹 Syntax:
if condition:
statements
else:
statements

🔹 Example:
num = 7

if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")

🔹 Explanation:

 If remainder is 0 → Even
 Otherwise → Odd
 Only one block will execute.
3️⃣ if-elif-else Statement
🔹 Description:

Used when we need to check multiple conditions.

elif means → "else if"

Python checks conditions one by one.


The first True condition block runs.

🔹 Syntax:
if condition1:
statements
elif condition2:
statements
elif condition3:
statements
else:
statements

🔹 Example:
marks = 82

if marks >= 90:


print("Grade A")
elif marks >= 70:
print("Grade B")
elif marks >= 40:
print("Grade C")
else:
print("Fail")

🔹 Explanation:

 82 is not ≥ 90
 82 is ≥ 70 ✅
 So "Grade B" prints
 After one True condition, rest are skipped.

4️⃣ Nested if Statement


🔹 Description:

When an if statement is placed inside another if, it is called Nested if.

Used when we need to check conditions inside conditions.


🔹 Example:
num = 12

if num > 0:
if num % 2 == 0:
print("Positive Even")
else:
print("Positive Odd")
else:
print("Negative Number")

🔹 Explanation:

 First checks number is positive


 Then checks even or odd
 So multiple level checking is done.

5️⃣ Short-hand if (One-line if)


🔹 Description:

Used when only one statement is needed.

🔹 Example:
a = 10
b = 5

if a > b: print("A is greater")

Simple and short.

6️⃣ Ternary Operator (Short-hand if-else)


🔹 Description:

Used to write if-else in one line.


Very useful for assigning values.

🔹 Syntax:
value_if_true if condition else value_if_false

🔹 Example:
a = 15
b = 20
result = "A bigger" if a > b else "B bigger"
print(result)

🔹 Explanation:

 Condition is False
 So "B bigger" gets stored in result.

⭐ Important Points
✔ Indentation is compulsory in Python
✔ Colon : must be used after condition
✔ Conditions always return True or False
✔ Only one block runs in if-elif-else
✔ Nested if is used for complex checking

Loops in Python
🔹 What is a Loop?

A loop is used to repeat a block of code multiple times until a condition becomes false or until
all items are processed.
Loops help to:

 Reduce code repetition


 Automate repetitive tasks
 Work with lists, strings, and numbers

🔁 Types of Loops in Python


Python has two main types of loops:

1. for loop
2. while loop

It also supports:

 Nested loops
 Loop control statements (break, continue, pass)

1️⃣ for Loop


🔹 Description:

The for loop is used when we know how many times we want to repeat something or when we
want to iterate over a sequence (like list, tuple, string, range).

🔹 Syntax:
for variable in sequence:
statements

🔹 Example 1: Print numbers 1 to 5


for i in range(1, 6):
print(i)

🔹 Explanation:

 range(1,6) generates numbers from 1 to 5


 Loop runs 5 times
 Each time i gets a new value
🔹 Example 2: Loop through a list
fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:


print(fruit)

This prints each item one by one.

2️⃣ while Loop


🔹 Description:

The while loop runs as long as the condition is True.

Used when we do not know exact number of iterations.

🔹 Syntax:
while condition:
statements

🔹 Example:
i = 1

while i <= 5:
print(i)
i += 1

🔹 Explanation:

 Loop starts with i = 1


 Runs until i <= 5
 i += 1 increases value
 Stops when condition becomes False

⚠ Important: If condition never becomes False, it creates an infinite loop.

3️⃣ Nested Loop


🔹 Description:

A loop inside another loop is called a nested loop.

🔹 Example:
for i in range(1, 4):
for j in range(1, 3):
print(i, j)

🔹 Explanation:

 Outer loop runs 3 times


 Inner loop runs 2 times for each outer loop
 Total executions = 3 × 2 = 6

4️⃣ Loop Control Statements


🔹 (a) break

Stops the loop immediately.

for i in range(1, 6):


if i == 3:
break
print(i)

Output:

1
2

Loop stops when i == 3.

🔹 (b) continue

Skips current iteration and moves to next.

for i in range(1, 6):


if i == 3:
continue
print(i)

Output:
1
2
4
5

🔹 (c) pass

Does nothing (placeholder).

for i in range(5):
pass

Used when loop is required but code is not written yet.

📘 String in Python
🔹 What is a String?

A string is a sequence of characters enclosed in:

 Single quotes ' '


 Double quotes " "
 Triple quotes ''' ''' or """ """

Strings are used to store text data.

🔹 Example of String
name = "John"
city = 'Mumbai'
message = """Hello
Welcome to Python"""

🔹 Important Properties of Strings

1. Strings are immutable (cannot be changed after creation).


2. Strings are ordered (each character has an index).
3. Indexing starts from 0.

🔢 String Indexing
Each character has a position (index).

Example:

text = "Python"
Character P y t h o n

Index 0 1 2 3 4 5

Negative Index -6 -5 -4 -3 -2 -1

🔹 Accessing Characters
text = "Python"

print(text[0]) # P
print(text[3]) # h
print(text[-1]) # n

✂️String Slicing
🔹 What is Slicing?

Slicing is used to extract a part (substring) of a string.

🔹 Syntax:
string[start : stop : step]

 start → Starting index


 stop → Ending index (not included)
 step → Jump value (optional)

📌 Basic Slicing Example


text = "Python"

print(text[0:4]) # Pyth
print(text[2:5]) # tho

Explanation:

 0:4 → characters from index 0 to 3


 Stop index is not included.

📌 Slicing Without Start or Stop


text = "Python"

print(text[:4]) # Pyth
print(text[2:]) # thon
print(text[:]) # Python

📌 Negative Slicing
text = "Python"

print(text[-4:-1]) # tho
📌 Using Step in Slicing
text = "Python"

print(text[0:6:2]) # Pto

Explanation:

 Start at 0
 Go till 6
 Jump 2 steps each time

🔁 Reverse a String Using Slicing


text = "Python"

print(text[::-1]) # nohtyP

Explanation:

 Step -1 means move backward

❌ String is Immutable
You cannot change a character directly:

text = "Python"
text[0] = "J" # Error

Correct way:

text = "Python"
text = "J" + text[1:]
print(text) # Jython

#Important String Methods


#upper() – Converts all characters of a string to uppercase.

print("python".upper())
#lower() – Converts all characters of a string to lowercase.

print("python".lower())

#title() – Converts the first letter of each word to uppercase.

print("python is funny language".title())

#capitalize() – Capitalizes only the first character of the string.

print("python is funny language".capitalize())

#strip() – Removes spaces (or specified characters) from both sides.

print(" python ".strip())

#lstrip() – Removes spaces from the left side.

print(" python".lstrip())

#rstrip() – Removes spaces from the right side.

print("python ".rstrip())

#replace(old, new) – Replaces a substring with another substring.

print("I like Java".replace("Java","Pyhton"))

#find(sub) – Returns the index of first occurrence of substring (or -1 if not found).

print("I like Java".find("kite"))


#index(sub) – Returns the index of substring (gives error if not found).

print("I like Java".index("Java"))

#count(sub) – Counts how many times a substring appears.

print("Python is Python lang".count("Python"))

#split() – Splits string into a list using a separator.

print("Python is Python lang".split(" "))

#join(iterable) – Joins elements of a list/tuple into a string.

name=["japan","london","englang"]

print("-".join(name))

#startswith(prefix) – Checks if string starts with given text.

print("Python is Python lang".startswith("P"))

#endswith(suffix) – Checks if string ends with given text.

print("Python is Python lang".endswith("n"))

#isalpha() – Returns True if all characters are letters.

print("Python".isalpha())

#isdigit() – Returns True if all characters are digits.


print("1234".isdigit())

#isalnum() – Returns True if all characters are letters or digits.

print("0127EC081923".isalnum())

#isspace() – Returns True if all characters are whitespace.

print(" ".isspace())

#islower() – Returns True if all characters are lowercase.

print("python".islower())

#isupper() – Returns True if all characters are uppercase.

print("python".isupper())

#swapcase() – Converts uppercase to lowercase and vice versa.

print("pyThoN".swapcase())

#center(width) – Centers the string within given width.

print("python".center(50))

#ljust(width) – Left-aligns the string.

print("python".ljust(50))
#rjust(width) – Right-aligns the string.

print("python".rjust(50))

#zfill(width) – Adds zeros at the beginning of string.

print("python".zfill(50))

#partition(sep) – Splits string into 3 parts using separator.

print("Pyhton is-very-funny-language".partition("-"))

#format() – Formats values inside a string.

name="tousheef"

print("Name is{}".format(name))

print(f"Name is{name}")

Functions of String:

#len(string)

print(len("python"))

#sorted()

print(sorted("python"))

#max()

print(max("python"))

#min()

print(min("python"))
#ord()

print(ord('A'))

#chr()

print(chr(65))

You might also like