class 15
class 15
For Variables and Functions: Use lowercase letters with words separated
by underscores (e.g., user_name, calculate_total).
Avoid Reserved Keywords: Python has reserved keywords like if, else,
class, etc., which cannot be used as identifiers.
Python: Syntax
Python syntax is designed to be clear and easy to read.
Some key syntax rules are:
1. Statements: Each line of code is typically one statement.
2. Use a newline to indicate the end of a statement.
3. Use a semicolon (;) to combine multiple statements on one line (not
common).
Example:
a = 10; b = 20; print(a + b) # Outputs: 30
Python: Comments
Use # for single-line comments.
Use triple quotes (""" or ''') for multi-line comments.
Example:
# This is a single-line comment
"""
This is a multi-line
comment
"""
Python: Operators
Operators in Python are special symbols or keywords used to perform
operations on variables and values.
Types of operators in Python:
Python: Logical Operators
x=5
y = 10
print(x > 3 and y < 15) # True
print(x > 6 or y < 15) # True
print(not(x > 6)) # True
Python: Relational Operators
x=5
y = 10
print(x == y) # False
print(x != y) # True
print(x > y) # False
Python: Assignment Operators
x=5
x += 3 # x = 8
x *= 2 # x = 16
Python: Bitwise Operators
x = 5 # Binary: 0101
y = 3 # Binary: 0011
print(x & y) # 1 (Binary: 0001)
Python: Membership Operators
text = "Python"
print("P" in text) # True
print("z" not in text) # True
Python: Identity Operators
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # False (different objects)
print(x == y) # True (same content)
Python: Special Operators
8. Special Operators:
Ternary Operator: A shorthand for if-else.
result = "Positive" if x > 0 else "Non-Positive"
Python: Variables
Variables are created by assignment.
They do not require type declarations.
Example:
x = 10 # Integer
y = "Hello" # String
Python: Dynamic Typing
Python uses dynamic typing, meaning variables do not require a
specified type when they are declared.
For instance, a variable can hold an integer initially,
Then be reassigned to a string without type declarations.
Example:
x = 10 # x is an integer
x = "Hello" # x is now a string
Python: Numeric & String Data Types
Python supports several numeric data types:
Integer (int): Whole numbers, positive or negative (e.g., 5, -10).
Float (float): Numbers with a decimal point (e.g., 3.14, -2.5).
Complex (complex): Numbers with a real and imaginary part (e.g., 3
+ 2j).
String Values and Operations: Strings in Python are sequences of
characters enclosed in single, double, or triple quotes:
name = "Python"
sentence = 'Hello, World!'
paragraph = """This is a
multi-line string."""
Python: String
String Operations:
Concatenation: Joining strings using +.
Repetition: Repeating strings with *.
Length: Finding the length of a string using len().
String Operators:
Concatenation (+): Combines two strings into one.
Repetition (*): Repeats a string a specified number of times.
Membership (in): Checks if a substring is present in the string.
text = "Python"
print(text + " Programming") # Concatenation
print(text * 3) # Repetition
print("Py" in text) # Membership
Python: String Slices
Slicing allows extraction of a portion of a string by specifying a range.
Syntax:
string[start:end:step]
Example:
text = "Python"
print(text[1:4]) # 'yth'
print(text[:3]) # 'Pyt'
print(text[::2]) # 'Pto'
Python: Different Data Structures
Different data structures in Python to manage data effectively are:
Python: Mutable/Immutable Data Structures
Difference:
Python: Ordered/Unordered Data Structures
Differences:
Python: Non-Primitive Data Structures - Lists
A list is an ordered, mutable collection of items.
Lists are versatile and allow for mixed data types.
Features:
Allows duplicates.
Can store mixed data types.
Example:
# Declaration
fruits = ["apple", "banana", "cherry"]
# Removing an element
# Accessing elements fruits.remove("banana")
print(fruits[1]) # Output: banana
# Iterating through a list
# Adding an element for fruit in fruits:
fruits.append("orange") print(fruit)
Python: Non-Primitive Data Structures - Lists
Example:
# Using square brackets #Removing elements
my_list = [1, 2, 3, 4] my_list.remove(3) #Removes the first
occurrence of 3
# Using the list() constructor my_list.pop() #Removes the last element
my_list = list((1, 2, 3, 4)) del my_list[1] #Deletes element at index 1
#Accessing elements #List slicing
print(my_list[0]) # Output: 1 sub_list = my_list[1:3] # Gets elements from
#Adding elements index 1 to 2
my_list.append(5) # Adds to the end #List comprehension
my_list.insert(2, 6) # Inserts 6 at index 2 squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Python: Non-Primitive Data Structures - Tuples
A tuple is an ordered, immutable collection of items.
Once a tuple is created, its elements cannot be modified.
Tuples are often used to group related data.
Features:
Allows duplicates.
Cannot be modified after creation.
Example: # Declaration
coordinates = (10, 20, 30)
# Accessing elements
print(coordinates[0]) # Output: 10
# Unpacking
x, y, z = coordinates
print(x, y, z) # Output: 10 20 30
Python: Non-Primitive Data Structures - Tuples
Example:
# Declaration # Accessing elements
# Using parentheses print(my_tuple[1]) # Output: 2
my_tuple = (1, 2, 3, 4)
# Unpacking tuples
# Using the tuple() constructor a, b, c = (1, 2, 3)
my_tuple = tuple([1, 2, 3, 4]) print(a, b, c) # Output: 1 2 3
x, y = get_coordinates()
print(x, y) # Output: 10 20
Python: Non-Primitive Data Structures - Sets
A set is an unordered collection of unique and immutable elements.
It is commonly used for membership testing, removing duplicates, and
mathematical set operations like union, intersection, etc.
Features:
No duplicate elements.
Used for mathematical set operations.
Python: Non-Primitive Data Structures - Sets
Declaration Removing elements
# Using curly braces my_set.remove(3) # Raises KeyError if the element is
not found
my_set = {1, 2, 3, 4}
my_set.discard(6) # Does not raise an error if the
# Using the set() constructor element is not found
# Duplicates are removed automatically
#Adding elements Set operations
my_set = set([1, 2, 3, 3, 4]) set1 = {1, 2, 3}
my_set.add(5) set2 = {3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # Output: {3}
print(set1.difference(set2)) # Output: {1, 2}
Python: Non-Primitive Data Structures - Dictionaries
A dictionary is an unordered collection of key-value pairs.
It is mutable, which means one can modify, add, or remove items.
The keys in a dictionary are unique
While the values can be duplicated.
Features:
Keys are unique and immutable.
Values can be mutable and duplicated.
Python: Non-Primitive Data Structures - Dictionaries
Example:
# Declaration
student = {"name": "Alice", "age": 25, "grade": "A"}
# Accessing values
print(student["name"]) # Output: Alice