From Complete Beginner to 2D Arrays
Table of Contents
- Python Basics
- Variables & Data Types
- Input & Output
- Decision Making (if-else)
- Loops
- Functions
- Lists (Arrays)
- Records/Dictionaries
- While Loops & Menu Systems
- Password Validation & Attempt Tracking
- Score Calculation & Game Logic
- Practical Applications
- 2D Arrays (Matrices)
- Quick Reference Card
Python Basics
What is Python?
Python is a programming language that is easy to read and write. It’s great for beginners!
Your First Program
# This is a comment - Python ignores this
print("Hello, World!")
Output:
Hello, World!
Key Points:
print()is used to display output- Text inside quotes
" "is called a string - Comments start with
#and are ignored by Python
Variables & Data Types
What are Variables?
Variables are containers for storing data values.
Basic Data Types
# Integer - whole numbers
age = 16
year = 2026
# Float - decimal numbers
price = 99.99
temperature = 36.5
# String - text (in quotes)
name = "Arj"
school = 'ABC School' # Single quotes also work
# Boolean - True or False
is_student = True
passed_exam = False
print(age)
print(name)
print(is_student)
Variable Naming Rules
- Can contain letters, numbers, and underscores
- Must start with a letter or underscore
- Cannot start with a number
- Case-sensitive (Age and age are different)
# Valid variable names
student_name = "Ali"
roll_number = 101
marks1 = 85
_total = 500
# Invalid variable names (will cause error)
# 1st_student = "Ali" # Cannot start with number
# my-name = "Ali" # Hyphen not allowed
# class = "10" # 'class' is a reserved word
Type Conversion
Converting between different data types:
# Converting string to integer
num_str = "123"
num_int = int(num_str)
print(num_int + 10) # 133
# Converting integer to string
age = 16
age_str = str(age)
print("I am " + age_str + " years old")
# Converting string to float
price_str = "99.99"
price_float = float(price_str)
print(price_float + 10) # 109.99
# Converting to boolean
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False
print(bool("Hi")) # True
Checking Data Types
x = 10
y = 3.14
z = "Hello"
print(type(x)) # <class 'int'>
print(type(y)) # <class 'float'>
print(type(z)) # <class 'str'>
Input & Output
Taking Input from User
# Taking input (always returns a string)
name = input("Enter your name: ")
print("Hello", name)
# Taking number input (need to convert)
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
marks = float(input("Enter your marks: "))
print("Your marks are", marks)
Multiple Inputs
# Taking multiple inputs
name = input("Enter name: ")
age = int(input("Enter age: "))
city = input("Enter city: ")
print("Name:", name)
print("Age:", age)
print("City:", city)
Formatted Output
# Simple output
name = "Ali"
marks = 85
print("Student", name, "got", marks, "marks")
# Using + for concatenation (joining strings)
print("Student " + name + " got " + str(marks) + " marks")
Decision Making (if-else)
if Statement
age = 18
if age >= 18:
print("You are an adult")
if-else Statement
marks = 75
if marks >= 40:
print("Pass")
else:
print("Fail")
if-elif-else Statement
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 80:
print("Grade B")
elif marks >= 70:
print("Grade C")
elif marks >= 60:
print("Grade D")
else:
print("Grade F")
Multiple Conditions (and, or)
# and - both conditions must be True
age = 20
has_id = True
if age >= 18 and has_id == True:
print("You can vote")
# or - at least one condition must be True
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's a holiday!")
Nested if Statements
num = 15
if num > 0:
print("Positive number")
if num % 2 == 0:
print("Even")
else:
print("Odd")
else:
print("Negative number")
Loops
for Loop
Used when you know how many times to repeat.
# Repeat 5 times
for i in range(5):
print("Hello", i)
# Output:
# Hello 0
# Hello 1
# Hello 2
# Hello 3
# Hello 4
range() Function
# range(stop) - from 0 to stop-1
for i in range(3):
print(i) # 0, 1, 2
# range(start, stop) - from start to stop-1
for i in range(2, 6):
print(i) # 2, 3, 4, 5
# range(start, stop, step) - with step value
for i in range(1, 10, 2):
print(i) # 1, 3, 5, 7, 9
while Loop
Used when you don’t know how many times to repeat.
# Count from 1 to 5
count = 1
while count <= 5:
print(count)
count = count + 1
# Output: 1 2 3 4 5
break Statement
Exit the loop immediately.
# Stop when user enters 0
while True:
num = int(input("Enter a number (0 to exit): "))
if num == 0:
break
print("You entered:", num)
continue Statement
Skip to the next iteration.
# Print only even numbers
for i in range(1, 11):
if i % 2 != 0: # if odd
continue
print(i) # 2, 4, 6, 8, 10
Functions
What are Functions?
Functions are reusable blocks of code that perform a specific task.
Defining and Calling Functions
# Defining a function
def greet():
print("Hello!")
print("Welcome to Python")
# Calling the function
greet()
greet() # Can call multiple times
Functions with Parameters
# Function with one parameter
def greet_person(name):
print("Hello", name)
greet_person("Ali")
greet_person("Sara")
# Function with multiple parameters
def add_numbers(a, b):
result = a + b
print("Sum is", result)
add_numbers(5, 3)
add_numbers(10, 20)
Functions with Return Values
# Function that returns a value
def add(a, b):
return a + b
result = add(5, 3)
print("Result:", result) # 8
# Function that returns multiple values
def get_min_max(numbers):
smallest = min(numbers)
largest = max(numbers)
return smallest, largest
nums = [10, 5, 8, 20, 3]
small, large = get_min_max(nums)
print("Smallest:", small)
print("Largest:", large)
Functions with Default Parameters
def greet(name, greeting="Hello"):
print(greeting, name)
greet("Ali") # Uses default "Hello"
greet("Sara", "Hi") # Uses provided "Hi"
Scope of Variables
# Global variable (outside function)
x = 10
def my_function():
# Local variable (inside function)
y = 5
print("Inside function - x:", x) # Can access global
print("Inside function - y:", y) # Can access local
my_function()
print("Outside - x:", x) # Works
# print("Outside - y:", y) # Error! y doesn't exist here
Function Examples
# Example 1: Calculate area of rectangle
def area_rectangle(length, width):
return length * width
area = area_rectangle(5, 3)
print("Area:", area)
# Example 2: Check if number is even
def is_even(num):
if num % 2 == 0:
return True
else:
return False
print(is_even(4)) # True
print(is_even(7)) # False
# Example 3: Convert temperature
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
temp = celsius_to_fahrenheit(30)
print("30°C =", temp, "°F")
Lists (Arrays)
Creating Lists
# Empty list
empty_list = []
# List with values
numbers = [1, 2, 3, 4, 5]
names = ["Ali", "Sara", "Ahmed"]
mixed = [10, "Hello", 3.14, True]
# Create list with repeated values
zeros = [0] * 5 # [0, 0, 0, 0, 0]
Accessing List Elements
fruits = ["apple", "banana", "orange", "mango"]
# Access by index (starts at 0)
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[3]) # mango
# Negative indexing (from end)
print(fruits[-1]) # mango (last item)
print(fruits[-2]) # orange
# Length of list
print(len(fruits)) # 4
Modifying Lists
fruits = ["apple", "banana", "orange"]
# Change an element
fruits[1] = "grapes"
print(fruits) # ["apple", "grapes", "orange"]
# Add elements
fruits.append("mango") # Add at end
fruits.insert(1, "kiwi") # Add at specific position
print(fruits)
# Remove elements
fruits.remove("apple") # Remove by value
fruits.pop() # Remove last element
fruits.pop(1) # Remove by index
print(fruits)
Looping Through Lists
fruits = ["apple", "banana", "orange"]
# Method 1: Direct iteration
for fruit in fruits:
print(fruit)
# Method 2: Using index
for i in range(len(fruits)):
print(fruits[i])
List Operations
numbers = [5, 2, 8, 1, 9]
# Sum of all elements
total = sum(numbers)
print("Sum:", total)
# Minimum and maximum
minimum = min(numbers)
maximum = max(numbers)
print("Min:", minimum, "Max:", maximum)
# Sort list
numbers.sort()
print("Sorted:", numbers)
# Reverse list
numbers.reverse()
print("Reversed:", numbers)
# Check if item exists
if 8 in numbers:
print("8 is in the list")
List Functions
def calculate_average(marks_list):
total = sum(marks_list)
count = len(marks_list)
return total / count
marks = [75, 80, 90, 65, 85]
avg = calculate_average(marks)
print("Average:", avg)
Records/Dictionaries
What are Dictionaries?
Dictionaries store data in key-value pairs, like a real dictionary where you look up a word (key) to find its meaning (value).
Creating Dictionaries
# Empty dictionary
student = {}
# Dictionary with data
student = {
"name": "Ali",
"age": 16,
"grade": "10th",
"marks": 85
}
print(student)
Accessing Dictionary Values
student = {
"name": "Ali",
"age": 16,
"city": "Karachi"
}
# Access by key
print(student["name"]) # Ali
print(student["age"]) # 16
# Using get() method (safer - no error if key doesn't exist)
print(student.get("city")) # Karachi
print(student.get("country")) # None (doesn't exist)
Modifying Dictionaries
student = {"name": "Ali", "age": 16}
# Add new key-value pair
student["city"] = "Karachi"
print(student) # {"name": "Ali", "age": 16, "city": "Karachi"}
# Modify existing value
student["age"] = 17
print(student) # {"name": "Ali", "age": 17, "city": "Karachi"}
# Remove a key-value pair
del student["city"]
print(student) # {"name": "Ali", "age": 17}
Looping Through Dictionaries
student = {
"name": "Ali",
"age": 16,
"city": "Karachi",
"grade": "10th"
}
# Loop through keys
for key in student:
print(key, ":", student[key])
# Loop through key-value pairs
for key, value in student.items():
print(key, "=", value)
# Get all keys
keys = student.keys()
print(keys)
# Get all values
values = student.values()
print(values)
List of Dictionaries (Records)
# Multiple student records
students = [
{"name": "Ali", "age": 16, "marks": 85},
{"name": "Sara", "age": 15, "marks": 92},
{"name": "Ahmed", "age": 17, "marks": 78}
]
# Access each student's data
for student in students:
print(student["name"], "got", student["marks"], "marks")
# Find student with highest marks
highest = students[0]
for student in students:
if student["marks"] > highest["marks"]:
highest = student
print("Top student:", highest["name"], "with", highest["marks"], "marks")
Dictionary Functions
def add_student(students_list, name, age, marks):
student = {
"name": name,
"age": age,
"marks": marks
}
students_list.append(student)
return students_list
def get_average_marks(students_list):
total = 0
for student in students_list:
total = total + student["marks"]
return total / len(students_list)
# Using the functions
my_students = []
my_students = add_student(my_students, "Ali", 16, 85)
my_students = add_student(my_students, "Sara", 15, 92)
avg = get_average_marks(my_students)
print("Average marks:", avg)
Student Record System Example
def display_menu():
print("\n--- Student Record System ---")
print("1. Add Student")
print("2. Display All Students")
print("3. Search Student")
print("4. Calculate Class Average")
print("5. Exit")
def add_student(students):
name = input("Enter student name: ")
age = int(input("Enter age: "))
marks = float(input("Enter marks: "))
student = {
"name": name,
"age": age,
"marks": marks
}
students.append(student)
print("Student added successfully!")
def display_all(students):
if len(students) == 0:
print("No students in record")
else:
print("\nAll Students:")
for i in range(len(students)):
s = students[i]
print(i+1, "-", s["name"], ", Age:", s["age"], ", Marks:", s["marks"])
def search_student(students):
name = input("Enter name to search: ")
found = False
for student in students:
if student["name"].lower() == name.lower():
print("Found:", student["name"], ", Age:", student["age"], ", Marks:", student["marks"])
found = True
if not found:
print("Student not found")
def calculate_average(students):
if len(students) == 0:
print("No students to calculate average")
else:
total = 0
for student in students:
total = total + student["marks"]
avg = total / len(students)
print("Class average:", avg)
# Main program
students = []
choice = 0
while choice != 5:
display_menu()
choice = int(input("Enter your choice: "))
if choice == 1:
add_student(students)
elif choice == 2:
display_all(students)
elif choice == 3:
search_student(students)
elif choice == 4:
calculate_average(students)
elif choice == 5:
print("Goodbye!")
else:
print("Invalid choice!")
While Loops & Menu Systems
Simple Menu System
A basic menu that continues until the user chooses to exit.
# Simple Menu System
def Display():
userInput = 0
while userInput != 3:
userInput = int(input("Enter a number: 1 for Hello, 2 for Goodbye and 3 for exit "))
if userInput == 1:
print("Hello")
elif userInput == 2:
print("Goodbye")
Display()
Key Points:
- While loop runs until condition becomes False
- User input controls which option runs
- Program ends when user enters 3
Password Validation & Attempt Tracking
Password Retry System
Allow limited attempts for password entry.
def password():
passwordS = "CS123"
tries = 3
access = False
while tries > 0 and not access:
password = input("Enter your password: ")
if password == passwordS:
print("Access granted")
access = True
else:
tries -= 1
print("Try Again.", tries, "left")
if not access:
print("Access denied")
password()
Key Points:
- Counter variable tries tracks remaining attempts
- Boolean flag access tracks if login successful
- Loop stops when either condition becomes False
Score Calculation & Game Logic
Game Score Tracker
Process scores with special rules.
def scoreCalculator():
sumAll = 0
for i in range(5):
scores = int(input("Enter your game score: "))
if scores < 0:
print("Invalid score.")
elif scores <= 50 and scores > 0:
sumAll += scores
elif scores > 50:
sumAll = sumAll + scores * 2
if sumAll > 200:
print("high score")
else:
print("try again")
scoreCalculator()
Key Points:
- For loop for fixed number of rounds
- Multiple conditions with if-elif
- Cumulative sum with += operator
Practical Applications
Coffee Shop Order Calculator
def Calcprices():
print("Coffee Prices:")
print("Small = Rs 100")
print("Medium = Rs 150")
print("Large = Rs 250")
print("Adding Cream = Rs 20")
Calcprices()
price = 0
total = 0
choice = ""
while choice != "done":
choice = input("Do you want S/M/L (enter done to exit): ").lower()
if choice == "done":
break
elif choice == "small":
total += 100
elif choice == "medium":
total += 150
elif choice == "large":
total += 250
cream = input("Do you want cream with your coffee (Y/N): ").lower()
if cream == "yes":
total += 20
print("your total is", total)
Parking Fee Calculator
def displayboard():
print("Parking Charges:")
print("0-1 hours = Rs 20")
print("1-3 hours = Rs 50")
print("5 hours = Rs 100 with extra Rs 20")
displayboard()
charges = 0
total = 0
exit = False
while exit != True:
hours = float(input("Enter the hours spent parking (enter 0 to exit): "))
if hours == 0:
exit = True
print("You have exited.")
elif hours > 0 and hours <= 1:
charges = 20
elif hours > 1 and hours <= 3:
charges = 50
elif hours > 3 and hours <= 5:
charges = 100
else:
charges = 120
total += charges
print("Your parking charges are", total)
Student Marks Analyzer
marks = []
grades = []
sum = 0
count = 0
Acount, Bcount, Ccount, Dcount, Fcount = 0, 0, 0, 0, 0
userInput = 0
while userInput != -1:
userInput = int(input("Enter student marks: "))
if userInput == -1:
break
else:
marks.append(userInput)
sum = sum + userInput
count = count + 1
if userInput >= 90:
grades.append('A')
Acount = Acount + 1
elif userInput >= 80:
grades.append('B')
Bcount = Bcount + 1
elif userInput >= 70:
grades.append('C')
Ccount = Ccount + 1
elif userInput >= 60:
grades.append('D')
Dcount = Dcount + 1
else:
grades.append('F')
Fcount = Fcount + 1
print("The average score is", sum / count)
print("Number of A's are", Acount)
print("Number of B's are", Bcount)
print("Number of C's are", Ccount)
print("Number of D's are", Dcount)
print("Number of F's are", Fcount)
print(marks)
print(grades)
Employee Salary Calculator
def display():
print("first 40 hours: Rs 500")
print("next 10 hours(41-50): Rs 600")
print("above 50 hours: Rs 700")
display()
highest = -999999
lowest = 999999
count = 0
pay = 0
total = 0
salarylist = []
hourslist = []
exit = False
while exit != True:
hours = float(input("Enter Employees' hours worked: "))
if hours == 0:
exit = True
elif hours <= 40:
count = count + 1
pay = 500
cost = pay * hours
salarylist.append(cost)
hourslist.append(hours)
elif hours >= 41 and hours <= 50:
count = count + 1
pay = 600
cost = pay * hours
salarylist.append(cost)
hourslist.append(hours)
else:
count = count + 1
pay = 700
cost = pay * hours
salarylist.append(cost)
hourslist.append(hours)
total = total + pay * hours
average = total / count
if cost > highest:
highest = cost
if cost < lowest:
lowest = cost
print("Hours List For Employees:")
print("[", end=" ")
for p in hourslist:
print(p, end=" ")
print("]")
print("Salary List For Employees:")
print("[", end=" ")
for x in salarylist:
print(x, end=" ")
print("]")
print("The total amount of salary given is", total)
print("The highest salary given is", highest)
print("The lowest salary given is", lowest)
print("The average salary given is", average)
Hotel Room Booking System
def extraRooms():
extra = input("Do you have extra people? ")
if extra == "yes":
return True
else:
return False
def amountOfNights():
nights = int(input("Enter the number of nights: "))
return nights
print("Single (1 person): Rs. 2000/night")
print("Double (2 people): Rs. 3000/night")
print("Family (4 people): Rs. 5000/night")
print("Extra person: +Rs. 500")
print()
priceslist = []
price = 0
totalCost = 0
exit = True
totalNights = 0
sCount, dCount, fCount = 0, 0, 0
while exit != False:
roomtype = input("(single/double/family) for extra (+500) and enter 'stop' to leave: ")
if roomtype == "stop":
exit = False
elif roomtype == "single":
price = 2000
extra = extraRooms()
if extra == True:
price = price + 500
nights = amountOfNights()
price = price * nights
priceslist.append(price)
totalCost = totalCost + price
sCount = sCount + 1
totalNights = totalNights + nights
elif roomtype == "double":
price = 3000
extra = extraRooms()
if extra == True:
price = price + 500
nights = amountOfNights()
price = price * nights
priceslist.append(price)
totalCost = totalCost + price
dCount = dCount + 1
totalNights = totalNights + nights
elif roomtype == "family":
price = 5000
extra = extraRooms()
if extra == True:
price = price + 500
nights = amountOfNights()
price = price * nights
priceslist.append(price)
totalCost = totalCost + price
fCount = fCount + 1
totalNights = totalNights + nights
else:
print("invalid room type, Enter Again.")
print(priceslist)
print("The total Cost of all rooms is:", totalCost)
if sCount > dCount and sCount > fCount:
print("Most Booked Room is Single Room")
elif dCount > sCount and dCount > fCount:
print("Most Booked Room is Double Room")
elif fCount > sCount and fCount > dCount:
print("Most Booked Room is Family Room")
else:
print("All Rooms had the same amount of bookings")
TotalCount = sCount + dCount + fCount
print("The average stay duration is:", totalNights / TotalCount)
2D Arrays (Matrices)
Creating 2D Arrays
# Method 1: Direct initialization
Matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Method 2: Using list comprehension
Data = [[0] * 3 for _ in range(3)]
print(Data)
# Method 3: Taking user input
rows = int(input("enter the number of rows: "))
cols = int(input("enter the number of columns: "))
matrix = [[0] * cols for i in range(rows)]
for i in range(rows):
for j in range(cols):
matrix[i][j] = int(input("Enter value: "))
# Displaying a 2D array
for i in range(rows):
print("[", end=" ")
for j in range(cols):
print(matrix[i][j], end=" ")
print("]")
Row & Column Sum
Data = [[0] * 3 for i in range(3)]
# Inputting data
for rows in range(3):
for cols in range(3):
Data[rows][cols] = int(input("Enter a number: "))
# Calculating row and column sums
for rows in range(3):
rowSum = 0
colSum = 0
for cols in range(3):
rowSum = rowSum + Data[rows][cols]
colSum = colSum + Data[cols][rows]
print("The sum of row", rows, "is", rowSum)
print("The sum of col", rows, "is", colSum)
Search Element
data = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
num = int(input("enter a number: "))
found = False
for i in range(3):
for j in range(3):
if data[i][j] == num:
found = True
if found:
print("The number you entered is in the list")
else:
print("The number you entered is not in the list")
Matrix Transpose
rows = int(input("enter the number of rows: "))
cols = int(input("enter the number of columns: "))
data = [[0] * cols for i in range(rows)]
for i in range(rows):
for j in range(cols):
data[i][j] = int(input("Enter the value: "))
print("Original Matrix:")
for i in range(rows):
print("[", end=" ")
for j in range(cols):
print(data[i][j], end=" ")
print("]")
newData = [[0] * rows for i in range(cols)]
for i in range(cols):
for j in range(rows):
newData[i][j] = data[j][i]
print("Transpose Matrix:")
for i in range(cols):
print("[", end=" ")
for j in range(rows):
print(newData[i][j], end=" ")
print("]")
Find Maximum Value
rows = int(input("enter the number of rows: "))
cols = int(input("enter the number of columns: "))
D_list = [[0] * cols for i in range(rows)]
for i in range(rows):
for j in range(cols):
D_list[i][j] = int(input("enter number: "))
# Display matrix
for i in range(rows):
print("[", end=" ")
for j in range(cols):
print(D_list[i][j], end=" ")
print("]")
# Find maximum
max = D_list[0][0]
for i in range(rows):
for j in range(cols):
if D_list[i][j] > max:
max = D_list[i][j]
print("The maximum value is: ", max)
Diagonal Sum
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
data = [[0] * cols for i in range(rows)]
for i in range(rows):
for j in range(cols):
data[i][j] = int(input("Enter a number: "))
# Calculating diagonal sums
dSum = 0
aSum = 0
for i in range(rows):
dSum = dSum + data[i][i]
aSum = aSum + data[rows - 1 - i][i]
print("The diagonal sum is ", dSum)
print("The anti diagonal sum is ", aSum)
Matrix Addition
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
A = [[0] * cols for i in range(rows)]
B = [[0] * cols for i in range(rows)]
print("Enter the values of A:")
for i in range(rows):
for j in range(cols):
A[i][j] = int(input("Enter the value: "))
print("Enter the values of B:")
for i in range(rows):
for j in range(cols):
B[i][j] = int(input("Enter the value: "))
C = [[0] * cols for i in range(rows)]
for i in range(rows):
for j in range(cols):
C[i][j] = A[i][j] + B[i][j]
print("The result of Matrix addition of A and B is:")
for i in range(rows):
print("[", end=" ")
for j in range(cols):
print(C[i][j], end=" ")
print("]")
Student Marks Analysis System
def averagemarks(total, count):
return total / count
total = 0
count = 3
rows = 5
cols = 3
highest = 0
D_list = [[0] * cols for i in range(rows)]
for r in range(rows):
total = 0
for c in range(cols):
marks = int(input("Enter your marks: "))
D_list[r][c] = marks
total = total + marks
avg = averagemarks(total, 3)
if avg < 50:
print("Fail")
else:
print("Pass")
if avg > highest:
highest = avg
print("The highest average marks is: ", highest)
Classroom Attendance System
def countattendance(student_record):
total = 0
for i in student_record:
total = total + i
return total
students = 4
days = 5
attendance = []
for i in range(students):
student_record = []
for j in range(days):
present = int(input("Mark attendance. 1 for present and 0 for absent: "))
student_record.append(present)
attendance.append(student_record)
total = countattendance(student_record)
if total < 3:
print("Low attendance")
print("Total attendance for student", i, ": ", total)
print("Attendance Data (Student x Days)")
print("M T W T F")
for i in range(students):
for j in range(days):
print(attendance[i][j], end=" ")
print()
Cinema Seat Booking System
def bookseat(seatstatus):
print("total 30 seats")
print("Seat availability")
print("0 = Available, 1 = Booked")
r = int(input("Enter the row you want to book (0-4): "))
c = int(input("Enter the column you want to book (0-5): "))
if seatstatus[r][c] == 0:
seatstatus[r][c] = 1
print("Booking Successful")
else:
print("The seat is already booked. Please choose another one")
return seatstatus
def display(seatstatus):
print("Available seats")
print("0 = Available, 1 = Booked")
for i in range(5):
print("[", end=" ")
for j in range(6):
print(seatstatus[i][j], end=" ")
print("]")
rows = 5
seats = 6
seatstatus = [[0] * seats for i in range(rows)]
userInput = ""
while userInput != "stop":
display(seatstatus)
seatstatus = bookseat(seatstatus)
userInput = input("Do you want to make more bookings? type 'stop' to exit: ")
Quick Reference Card
| Concept | Syntax | Example |
|---|---|---|
print() | print("Hello") | |
| Input | input() | name = input("Name: ") |
| Variable | name = value | age = 16 |
| If statement | if condition: | if age >= 18: |
| If-else | if: ... else: | if x>0: print("+") else: print("-") |
| For loop | for i in range(n): | for i in range(5): |
| While loop | while condition: | while x < 10: |
| Function | def name(): | def greet(): |
| Function with params | def name(p1, p2): | def add(a, b): |
| Return value | return value | return total |
| List creation | list = [] | marks = [85, 90, 78] |
| List append | list.append(item) | marks.append(95) |
| Dictionary | dict = {key:value} | student = {"name": "Ali"} |
| Access dict | dict[key] | student["name"] |
| 2D list | [[0]*cols for _ in range(rows)] | matrix = [[0]*3 for _ in range(3)] |
| Type conversion | int(), float(), str() | age = int(input()) |
| Length | len() | len(list) |
| Sum | sum() | total = sum(marks) |
Note: Practice each concept by writing your own programs. Start with simple examples and gradually build more complex programs. Happy coding! 🐍
