python notes unit 1 and 2
python notes unit 1 and 2
Guide
This guide covers the fundamentals of Python, including data structures, operations, conditional
statements, loops, and comprehensions.
1. Basics of Python
Python is a high-level, interpreted programming language used for software development, data
analysis, machine learning, and web development.
Example:
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
Example:
numbers = [1, 2, 3, 4, 5]
numbers.append(6) # Adds 6 to the list
numbers.sort() # Sorts the list
Example:
student = {"name": "Alice", "age": 20}
student["grade"] = "A" # Adding a new key-value pair
if checks a condition.
elif is used for multiple conditions.
else executes if none of the conditions are met.
Example:
age = 18
if age >= 18:
print("Eligible to vote")
elif age == 17:
print("Wait one more year")
else:
print("Not eligible")
A. for Loop
Used for iterating over sequences like lists and strings.
range(start, stop, step) is used for looping numbers.
Example:
B. while Loop
Runs until a condition becomes false.
Example:
x=1
while x <= 5:
print(x)
x += 1
Example:
Example:
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output:
Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display(self):
print(f"Car: {self.brand}, Model: {self.model}")
# Creating an object
my_car = Car("Toyota", "Corolla")
my_car.display()
Output:
Example:
class Vehicle:
def __init__(self, type):
self.type = type
2. Arrays in Python
2.1 What is an Array?
An array is a collection of items of the same data type stored in contiguous memory locations.
Output:
import numpy as np
arr = np.zeros(5, dtype=int) # Creates an array of size 5 with zeros
print(arr)
Output:
[0 0 0 0 0]
Output:
2D Array Example:
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)
Output:
[[1 2 3]
[4 5 6]]
import numpy as np
Output:
First element: 10
Last three elements: [13 14 15]
Array elements:
10
11
12
13
14
15