[go: up one dir, main page]

0% found this document useful (0 votes)
75 views19 pages

Lab 01 Introduction To Pyton (1) .Ipynb - Colab

Uploaded by

i222162
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)
75 views19 pages

Lab 01 Introduction To Pyton (1) .Ipynb - Colab

Uploaded by

i222162
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
You are on page 1/ 19

8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).

ipynb - Colab

keyboard_arrow_down AL-4003 Applied Machine Learning


Name: Asma khan

Reg No: 22i-2162

Lab# 01

Introduction to Python Programming Language

Learning Outcomes:

Understand and apply Python syntax


Declare and manipulate variables
Differentiate between and utilize various data types
Implement input and output operations
Apply control structures
Construct and control loops
Work with functions
Perform file handling operations
Apply object-oriented programming concepts

Python

Python is a high-level, interpreted, and general-purpose programming language widely used in software development, data science, artificial
intelligence, web development, automation, and scientific computing. It was created by Guido van Rossum and first released in 1991.

Python is known for its simplicity, readability, and versatility, making it an ideal choice for both beginners and professionals. Its clean syntax
resembles natural language, which reduces the learning curve compared to other programming languages like C or Java.

Key Features of Python:

Simple and Readable: Python code is easy to write and understand.


Interpreted Language: Code is executed line by line, making debugging easier.
Cross-platform: Runs on Windows, macOS, Linux, and other operating systems.
Extensive Libraries: Provides rich built-in libraries and third-party packages for tasks like machine learning, web development, and data
analysis.
Object-Oriented: Supports concepts like classes, objects, and inheritance.
Versatile Applications: Used in automation, artificial intelligence, data visualization, web applications, and more.

Syntax

Syntax refers to the set of rules that define how a Python program is written and interpreted. Python emphasizes readability and uses
indentation instead of braces {} or keywords (like in C/C++ or Java) to define code blocks.

keyboard_arrow_down Basic Rules


Case Sensitivity
Indentation
Comments
Statements
Identifiers
Quotations
Line Continuation

keyboard_arrow_down 1. Case Sensitivity

Python is case-sensitive.

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 1/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab

Name = "Ali"
name = "Ahmad"
print(Name)
print(name)

Ali
Ahmad

keyboard_arrow_down 2. Indentation

Indentation is mandatory in Python to define code blocks (instead of braces).

if True:
print("This is indented correctly") # valid

This is indented correctly

if True:
print("Error due to missing indentation")

keyboard_arrow_down 3. Comments

Comments are used to explain the code.

# This is a single-line comment


"""
This is a
multi-line comment
"""

keyboard_arrow_down 4. Statements

Each line in Python is a statement.

You can also write multiple statements in a single line using ;.

x = 5;
y = 10;
print(x + y)

15

keyboard_arrow_down 5. Identifiers

Names for variables, functions, and classes.

Must start with a letter or underscore _, followed by letters, digits, or underscores.

Cannot use keywords as identifiers.

my_var = 10 # valid
_count = 5 # valid
1name = "Ali" # ❌ invalid

keyboard_arrow_down 6. Quotations

Strings can be written in single ('), double (") or triple quotes (''' or """).

str1 = 'Hello'
str2 = "World"
str3 = '''This is
a multiline string'''

keyboard_arrow_down 7. Line Continuation

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 2/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
Long statements can be broken into multiple lines using \ or parentheses.

total = 1 + 2 + 3 + \
4 + 5 + 6

total = (1 + 2 + 3 +
4 + 5 + 6)
print(total)

21

keyboard_arrow_down Task# 1

Write a Python program that demonstrates proper syntax by printing your name, age, and a multi-line comment describing your career goals.

name = "Asma"
print(name)
age = 23
print (age)
''' i want to become a good human and want to do a job which serve people '''

Asma
23
' i want to become a good human and want to do a job which serve people '

keyboard_arrow_down Variables
A variable in Python is a name that refers to a value stored in memory. Unlike many programming languages, Python variables don't need to
be declared with a specific type - Python automatically determines the type based on the value assigned.

# Example
name = "Alice"
age = 25
height = 5.6
is_student = True

# Multiple assignment
x, y, z = 10, 20, 30

# Same value to multiple variables


a = b = c = 100

Understanding variables and data types is fundamental to Python programming. Learn:

Variables are names that reference values in memory


Python uses dynamic typing - variable types are determined at runtime
Choose the appropriate data type for your use case
Follow naming conventions for readable code
Handle type conversions safely with proper error checking

Mastering these concepts will provide a solid foundation for all your Python programming endeavors.

keyboard_arrow_down 1. Dynamic Typing


Python variables can change their data type during program execution:

x = 10 # x is integer
x = "Hello" # x is now string
x = [1, 2, 3] # x is now list

keyboard_arrow_down 2. Variable Naming Rules


Valid Variable Names

Must start with a letter (a-z, A-Z) or underscore (_) Can contain letters, digits, and underscores Case-sensitive Cannot be Python keywords

# Valid variable names


name = "John"
_private = 42
user_age = 25

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 3/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
firstName = "Alice"
score2 = 95

2name = "Invalid" # Cannot start with digit


first-name = "Bob" # Hyphen not allowed
class = "Math" # 'class' is a keyword

keyboard_arrow_down 3. Integer (int)


Whole numbers without decimal points. Python 3 integers have unlimited precision.

# Integer examples
positive_num = 42
negative_num = -17
zero = 0

# Different number systems


binary = 0b1010 # Binary (10 in decimal)
octal = 0o12 # Octal (10 in decimal)
hexadecimal = 0xA # Hexadecimal (10 in decimal)

print(f"Binary {binary}, Octal {octal}, Hex {hexadecimal}")


# Output: Binary 10, Octal 10, Hex 10

Binary 10, Octal 10, Hex 10

keyboard_arrow_down 4. Float (float)


Numbers with decimal points, following IEEE 754 double-precision standard.

# Float examples
pi = 3.14159
negative_float = -2.5
scientific = 1.5e2 # Scientific notation (150.0)
small_num = 1.5e-3 # 0.0015

keyboard_arrow_down 5. Complex (complex)


Numbers with real and imaginary parts.

# Complex numbers
z1 = 3 + 4j
z2 = complex(2, -1) # 2 - 1j
z3 = 5j # Pure imaginary

print(z1.real) # Output: 3.0


print(z1.imag) # Output: 4.0
print(abs(z1)) # Output: 5.0 (magnitude)

3.0
4.0
5.0

keyboard_arrow_down 6. Text Data Type (String)


Strings are sequences of characters enclosed in quotes.

# Different ways to create strings


single_quotes = 'Hello'
double_quotes = "World"
triple_quotes = """Multi-line
string example"""
raw_string = r"C:\Users\name" # Raw string (backslashes literal)

keyboard_arrow_down 7. String Operations


name = "Python"

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 4/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
# Length
print(len(name))

# Indexing (0-based)
print(name[0])
print(name[-1])

# Slicing
print(name[1:4])
print(name[:3])
print(name[2:])

# Common methods
print(name.upper())
print(name.lower())
print(name.replace('P', 'J'))

6
P
o
yth
Pyt
thon
PYTHON
python
Jython

keyboard_arrow_down 8. Boolean Data Type


Boolean values represent truth values: True or False.

# Boolean values
is_valid = True
is_empty = False

# Boolean operations
print(True and False) # Output: False
print(True or False) # Output: True
print(not True) # Output: False

# Truthy and Falsy values


print(bool(0)) # Output: False
print(bool("")) # Output: False
print(bool([])) # Output: False
print(bool(42)) # Output: True
print(bool("Hello")) # Output: True

False
True
False
False
False
False
True
True

keyboard_arrow_down 9. Type Checking and Conversion


Checking Types

x = 42
print(type(x))
print(isinstance(x, float))

<class 'int'>
False

# Implicit conversion
result = 10 + 3.14

# Explicit conversion
x = "123"
y = int(x)
z = float(y)
s = str(z)

# Conversion with error handling


user_input = "abc"

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 5/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
try:
number = int(user_input)
except ValueError:
print("Invalid input for integer conversion")

Invalid input for integer conversion

keyboard_arrow_down Input Output Operations


I/O operations are fundamental to most programs, allowing interaction with users. Python provides built-in functions and modules to handle
various I/O scenarios efficiently.

keyboard_arrow_down 1. The input() Function


The input() function reads a line from standard input (keyboard) and returns it as a string.

# Basic input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Input is always a string


age_str = input("Enter your age: ")
print(f"Type of age_str: {type(age_str)}")

Enter your name: asm a


Hello, asm a!
Enter your age: ten
Type of age_str: <class 'str'>

keyboard_arrow_down Converting Input to Other Data Types

# Converting to integer
try:
age = int(input("Enter your age: "))
print(f"Next year you'll be {age + 1}")
except ValueError:
print("Please enter a valid number")

# Converting to float
try:
height = float(input("Enter your height in meters: "))
print(f"Your height is {height} meters")
except ValueError:
print("Please enter a valid number")

# Multiple inputs on one line


numbers = input("Enter three numbers separated by spaces: ").split()
x, y, z = map(int, numbers)
print("Sum: ",x + y + z)

Enter your age: 12


Next year you'll be 13
Enter your height in meters: 12.3
Your height is 12.3 meters
Enter three numbers separated by spaces: 2 3 4
Sum: 9

Double-click (or enter) to edit

keyboard_arrow_down Reading Passwords Securely

import getpass

password = getpass.getpass("Enter password: ")


print("Password entered (hidden from display)")

Enter password: ··········


Password entered (hidden from display)

keyboard_arrow_down 2. The print() Function


https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 6/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
The print() function is the primary way to display output in Python.

# Basic printing
print("Hello, World!")
print(42)
print([1, 2, 3])

# Multiple arguments
print("Name:", "Ahmed", "\nAge:", 25)

# Print parameters
print("Hello", "World", sep="-")
print("Hello", "World", end="\n")
print("Next line")

# sep parameter - separator between arguments


print("apple", "banana", "cherry", sep=", ")

Hello, World!
42
[1, 2, 3]
Name: Ahmed
Age: 25
Hello-World
Hello World
Next line
apple, banana, cherry

keyboard_arrow_down Printf-style Formatting

name = "Ahmed"
age = 21
gpa = 3.87

# Basic formatting
print("Name: %s, Age: %d" % (name, age))

# Format specifiers
print("GPA: %.2f" % gpa) # 2 decimal places
print("Age: %03d" % age) # Zero-padded to 3 digits
print("Percentage: %d%%" % 85) # Literal % sign

Name: Ahmed, Age: 21


GPA: 3.87
Age: 021
Percentage: 85%

keyboard_arrow_down Control Structures


Control structures determine the flow of program execution based on conditions. They allow programs to make decisions, execute different
code paths, and respond dynamically to various situations.

Types of Control Structures in Python:

Sequential: Code executes line by line (default behavior)


Conditional: Code executes based on conditions (if, elif, else, match)
Iterative: Code repeats based on conditions (for, while loops)

keyboard_arrow_down 1. Basic if Statement


The if statement executes code only when a condition is true.

# Code to execute if condition is True


if condition:
statement1
statement2

# Example
age = 18
if age >= 18:
print("You are eligible to vote!")

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 7/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
# Multiple statements in if block
temperature = 35
if temperature > 30:
print("It's hot outside!")
print("Consider wearing light clothing.")
print("Stay hydrated.")

# Using variables in conditions


user_input = input("Enter your name: ")
if user_input: # Checks if string is not empty
print("Hello", user_input,"!")

# Checking multiple conditions with 'and'


score = 85
attendance = 90
if score >= 80 and attendance >= 85:
print("Congratulations! You passed with distinction.")

You are eligible to vote!


It's hot outside!
Consider wearing light clothing.
Stay hydrated.
Enter your name: Ahmed
Hello Ahmed !
Congratulations! You passed with distinction.

keyboard_arrow_down 2. if-else Statement


The if-else statement provides an alternative path when the condition is false.

Syntax

# Code to execute if condition is True


if condition:
statement1

# Code to execute if condition is False


else:
statement2

# Example 1: Basic if-else

age = int(input("Enter your age: "))


if age >= 18:
print("You can vote!")
else:
print("You cannot vote yet.")

# Even or odd checker


number = int(input("Enter a number: "))
if number % 2 == 0:
print(number, " is even")
else:
print(number, " is odd")

# Password validation
password = input("Enter password: ")
if len(password) >= 8:
print("Password is strong enough")
else:
print("Password too short. Must be at least 8 characters.")

# Grade classification
score = float(input("Enter your score: "))
if score >= 60:
print("You passed!")
else:
print("You failed. Better luck next time.")

Enter your age: 19


You can vote!
Enter a number: 21
21 is odd
Enter password: 12345678
Password is strong enough
Enter your score: 83
You passed!

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 8/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
# Example 2: Conditions with logical operators
username = input("Enter username: ")
password = input("Enter password: ")

if username == "admin" and password == "secret123":


print("Access granted!")
else:
print("Access denied!")

# Multiple conditions with 'or'


weather = input("What's the weather like? ").lower()
if weather == "rainy" or weather == "stormy":
print("Take an umbrella!")
else:
print("Enjoy your day!")

# Using 'not' operator


is_weekend = False
if not is_weekend:
print("It's a weekday - time to work!")
else:
print("It's weekend - time to relax!")

Enter username: admin


Enter password: secret123
Access granted!
What's the weather like? rainy
Take an umbrella!
It's a weekday - time to work!

Double-click (or enter) to edit

keyboard_arrow_down 3. if-elif-else Statement


The elif (else if) statement allows checking multiple conditions in sequence.

Syntax

pythonif condition1:
# Execute if condition1 is True
statement1

elif condition2:
# Execute if condition1 is False and condition2 is True
statement2

elif condition3:
# Execute if condition1 and condition2 are False and condition3 is True
statement3

else:
# Execute if all conditions are False
statement4

# Example 1: Take temperature input from user


temp = int(input("Enter the temperature in °C: "))

if temp < 0:
description = "Freezing"
elif temp < 10:
description = "Very Cold"
elif temp < 20:
description = "Cold"
elif temp < 25:
description = "Cool"
elif temp < 30:
description = "Warm"
elif temp < 35:
description = "Hot"
else:
description = "Very Hot"

print(temp, "°C: ", description) # Press ALT and type 0176 to write °

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 9/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab

Enter the temperature in °C: 26


26°C: Warm

# Example 2: Take score input from user


score = float(input("Enter your score: "))

if score >= 90:


grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"

print(f"Your grade is: {grade}")

Enter your score: 89


Your grade is: B

keyboard_arrow_down 3. Nested if Statements


Nested if statements are if statements inside other if statements, allowing for more complex decision-making.

Basic Nested Structure

# Simple nested if
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")

has_license = input("Do you have a driver's license? (yes/no): ").lower()


if has_license == "yes":
print("You can drive!")
else:
print("You need to get a driver's license first.")
else:
print("You are a minor.")
if age >= 16:
print("You can get a learner's permit.")
else:
print("You need to wait to drive.")

Enter your age: 19


You are an adult.
Do you have a driver's license? (yes/no): no
You need to get a driver's license first.

keyboard_arrow_down 4. Match-Case Statement


The match-case statement, introduced in Python 3.10, provides powerful pattern matching capabilities similar to switch statements in other
languages.

Basic Match-Case Syntax

match value:
case pattern1:
# Code for pattern1
case pattern2:
# Code for pattern2
case _: # Default case (optional)
# Code for default case

# Take day input from user


day = input("Enter a day: ")

match day:
case "monday":
category = "Weekday"
case "tuesday":
category = "Weekday"

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 10/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
case "wednesday":
category = "Weekday"
case "thursday":
category = "Weekday"
case "friday":
category = "Weekday"
case "saturday":
category = "Weekend"
case "sunday":
category = "Weekend"
case _:
category = "Invalid day"

print("day:", category)

Enter a day: friday


day: Weekday

# Example
x = int(input("Enter a number: "))

match x:
case n if n < 0:
category = "Negative number"
case 0:
category = "Zero"
case n if n > 0 and n <= 10:
category = "Small positive number (1-10)"
case n if n > 10 and n <= 100:
category = "Medium positive number (11-100)"
case n if n > 100:
category = "Large positive number (>100)"
case _:
category = "Not a number"

print("x:", category)

Enter a number: 85
x: Medium positive number (11-100)

keyboard_arrow_down Example: Calculator with Match-Case

# Take input from user


a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
op = input("Enter operation (+, -, *, /, **, %): ")

# Match-case for operations


match op:
case "+":
result = a + b
case "-":
result = a - b
case "*":
result = a * b
case "/":
result = a / b
case "**":
result = a ** b
case "%":
result = a % b
case _:
result = "Error: Unknown operation"

print(a, op, b, " = ", result)

Enter first number: 15


Enter second number: 19
Enter operation (+, -, *, /, **, %): /
15.0 / 19.0 = 0.7894736842105263

keyboard_arrow_down LOOPS
https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 11/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
Loops are fundamental control structures in Python that allow you to execute a block of code repeatedly. They help automate repetitive tasks
and process collections of data efficiently. Python provides two main types of loops: for loops and while loops.

keyboard_arrow_down 1. For Loops


The for loop is used to iterate over a sequence (like a list, tuple, string, or range) or any iterable object.

Basic Syntax

for variable in iterable:


# code block to execute

range() Function in Python

The range() function in Python is used to generate a sequence of numbers. It is commonly used in for loops when we want to repeat
something a fixed number of times or iterate over a sequence of numbers.

Syntax

range(start, stop, step)

Where:

start (optional): The starting value of the sequence (default is 0).


stop (required): The value at which the sequence stops (not included).
step (optional): The increment between each number (default is 1).

# Using only stop


for i in range(5):
print(i)

0
1
2
3
4

# Using start and stop


for i in range(2, 7):
print(i)

2
3
4
5
6

# Using start, stop, and step


for i in range(1, 10, 2):
print(i)

1
3
5
7
9

# Negative Step (Counting Down)


for i in range(10, 0, -2):
print(i)

10
8
6
4
2

keyboard_arrow_down 2. While Loops


The while loop continues executing as long as a specified condition is True. ** Syntax**

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 12/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab

while condition:
# code block to execute

# Basic While Loop


count = 0
while count < 5:
print("Count: ", count)
count += 1

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

password = ""
while password != "secret":
password = input("Enter password: ")
if password != "secret":
print("Incorrect password. Try again.")
print("Access granted!")

Enter password: 12345678


Incorrect password. Try again.
Enter password: Secret
Incorrect password. Try again.
Enter password: secret
Access granted!

keyboard_arrow_down 3. Break Statement


The break statement terminates the loop prematurely.

# Finding the first even number


numbers = [1, 3, 7, 8, 9, 12]
for num in numbers:
if num % 2 == 0:
print("First even number: ", num)
break

First even number: 8

keyboard_arrow_down 4. Continue Statement


The continue statement skips the rest of the current iteration and moves to the next one.

# Print only positive numbers


numbers = [0, 1, 2, 3, -4, -5, -6, 7, 8]
for num in numbers:
if num <= 0:
continue
print(num)

1
2
3
7
8

keyboard_arrow_down Functions
Functions are reusable blocks of code that perform specific tasks. They are fundamental building blocks in Python programming that help
organize code, avoid repetition, and make programs more modular and maintainable. Functions take inputs (called parameters), process
them, and optionally return outputs.

Function Syntax

Defining a function:

def function_name(parameters):
# Function body
return value # Optional

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 13/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab

# Function with no parameters


def greet():
print("Hello, World!")

# Function with parameters


def greet_person(name):
print("Hello", name)

# Function with return value


def add_numbers(a, b):
return a + b

# Calling functions
greet()
greet_person("Ahmad Ali")
result = add_numbers(5, 3)

Hello, World!
Hello Ahmad Ali

# Example
def introduce(name, age, city):
print(f"My name is", name, "I'm", age, "years old, and I live in", city)

introduce("Ahmad Ali", 21, "Islamabad")

My name is Ahmad Ali I'm 21 years old, and I live in Islamabad

def calculate_area(length, width):


area = length * width
return area

# Take input from user


length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))

# Call function
result = calculate_area(length, width)

# Print result
print("The area of the rectangle is:",result)

Enter the length of the rectangle: 13


Enter the width of the rectangle: 15
The area of the rectangle is: 195.0

keyboard_arrow_down Classes & Objects


Classes and objects are fundamental concepts in object-oriented programming (OOP). A class is a blueprint or template that defines the
structure and behavior of objects, while an object is an instance of a class. Python's class system provides powerful features for creating
reusable, maintainable code that models real-world entities and relationships.

keyboard_arrow_down Class Definition and Object Creation


Python is an object-oriented programming (OOP) language. OOP allows us to structure programs by bundling data (attributes) and
functionality (methods) together.

A class is a blueprint or template for creating objects.

It defines the properties (attributes/variables) and behaviors (methods/functions) that the objects created from the class will have.

Syntax:

class ClassName:
# attributes
# methods

What is an object?

An object is an instance of a class.


When a class is defined, no memory is allocated until an object is created.
You can create multiple objects from the same class.

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 14/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
Syntax:

object_name = ClassName()

# Defining a class
class Car:
# Attribute (class variable)
wheels = 4

# Constructor method
def __init__(self, brand, model):
self.brand = brand # instance attribute
self.model = model # instance attribute

# Method
def display_info(self):
print("Car:", self.brand, self.model, "Wheels:", Car.wheels)

# Creating objects (instances of Car class)


car1 = Car("Toyota", "Corolla")
car2 = Car("Honda", "Civic")

# Accessing attributes and methods


car1.display_info()
car2.display_info()

Car: Toyota Corolla Wheels: 4


Car: Honda Civic Wheels: 4

keyboard_arrow_down Lab Tasks


keyboard_arrow_down Task# 2

(a) Write a program that prints your name, university, and department.

(b) Explain the difference between IndentationError and SyntaxError in Python. Give an example of each.

# Write task 2a here 👇


name = "asma"
university ='fast'
department = 'EE'
print(name,university,department,sep=",")

asma,fast,EE

# Write examples of task 2b here 👇


'''syntax error occur when code does not follow python syntax eg print("name"
while indentation error occur when Python expects a certain indentation level, but it’s missing eg
if True:
print("This will cause an IndentationError")'''

keyboard_arrow_down Task# 3

(a) Declare variables for name, age, and GPA. Print them in a sentence.

(b) Swap two numbers without using a third variable.

(c) Update a variable’s value(e.g., bank balance after deposit/withdrawal).

# Write task 3a here 👇


name = "asma"
age= 23
gpa = 3.5
print('my name is',name,'my age is',age,'my gpa is',gpa)

my name is asma my age is 23 my gpa is 3.5

# Write task 3b here 👇


x=12
y=33
def swap(x,y):

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 15/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
x,y=y,x
return x,y
print(swap(x,y))

(33, 12)

# Write task 3c here 👇


amount = 1200
withdraw = 300
deposit = 200
balance = amount - withdraw
print(balance)
balance = amount + deposit
print(balance)

900
1400

keyboard_arrow_down Task# 4

(a) Ask the user for radius and calculate the area of a circle.

(b) Take marks of five subjects from students and compute average, highest, lowest and percentage, also print them all.

(c) Implement a grading system (A, B, C, D, F) based on marks input.

# Write task 4a here 👇


radius = input('enter radius')
radius = float(radius)
area = 3.142*radius*2
print(area)

enter radius12
75.408

# Write task 4b here 👇


s1= int(input('enter marks'))
s2= int(input('enter marks'))
s3= int(input('enter marks'))
s4= int(input('enter marks'))
s5= int(input('enter marks'))
students=[s1,s2,s3,s4,s5]
avg=sum(students)/5
print(avg)
print(max(students))
print(min(students))
print((sum(students)/500)*100)

enter marks67
enter marks89
enter marks90
enter marks56
enter marks100
80.4
100
56
80.4

x = int(input("Enter marks: "))

match x:
case n if n >= 80:
category = "A"
case n if n >= 70:
category = "B"
case n if n >= 60:
category = "C"
case n if n >= 50:
category = "D"
case _:
category = "F"

print("Grade:", category)

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 16/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab

Enter marks: 70
Grade: B

keyboard_arrow_down Task# 5

In this task, you are required to design and implement a menu-driven calculator program in Python. The calculator should be able to perform
basic arithmetic operations such as addition, subtraction, multiplication, division, exponentiation, and floor division.

You must implement the solution using:

Functions: Each operation (e.g., addition, subtraction) should be written as a separate user-defined function.

Control Structures (if-elif-else or match-case): To control the program’s flow, use decision-making statements that allow the user to
select the desired operation.

Input/Output Handling: Take two numbers and the operation choice as input from the user and display the calculated result clearly.

Error Handling: Include basic error handling for division by zero and invalid operation choices.

The calculator should continue to run in a loop until the user decides to exit.

# Write task # 5 code here 👇

def add(a, b):


return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def exponent(a, b):


return a ** b

def divide(a, b):


if b == 0:
return "Error: dividing by zero"
return a / b

def floordiv(a, b):


return a // b

while True:
print("1 Addition")
print("2 Subtraction")
print("3 Multiplication")
print("4 Division")
print("5 Exponentiation")
print("6 Floor Division")
print("7 Exit")

choice = input("Enter your choice: ")

if choice == "7":
print("exit")
break

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))

if choice == "1":
print("result:", add(a, b))
elif choice == "2":
print("result:", subtract(a, b))
elif choice == "3":
print("result:", multiply(a, b))
elif choice == "4":
print("result:", divide(a, b))
elif choice == "5":
print("result:", exponent(a, b))
elif choice == "6":
print("result:", floordiv(a, b))
else:
print("invalid")

1 Addition
2 Subtraction

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 17/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
3 Multiplication
4 Division
5 Exponentiation
6 Floor Division
7 Exit
Enter your choice: 1
Enter first number: 2
Enter second number: 3
result: 5
1 Addition
2 Subtraction
3 Multiplication
4 Division
5 Exponentiation
6 Floor Division
7 Exit
Enter your choice: 7
exit

keyboard_arrow_down Task# 6

Create a user-defined data type in Python using a class named Biodata. The class should store your personal details such as name, age,
gender, address, and contact number. Implement a constructor (init) to initialize these attributes, and provide methods to:

display the biodata


update any detail

Create object of the class and demonstrate how they can be used to store and manage biodata of different people.

# Write task # 6 code here 👇


class biodata:
def __init__(self, name, age, gender, address, contact):
self.name = name
self.age = age
self.gender = gender
self.address = address
self.contact = contact
def display(self):
print("name:", self.name)
print("age:", self.age)
print("gender:", self.gender)
print("address:", self.address)
print("contact:", self.contact)

def update(self, field, value):


if field == "name":
self.name = value
elif field == "age":
self.age = value
elif field == "gender":
self.gender = value
elif field == "address":
self.address = value
elif field == "contact":
self.contact = value
else:
print("invalid")
return
print(f"{field} updated successfully!")

person1 = biodata("bilal", 22, "male", "islamabad", "03004567897")


person2 = biodata("ali", 20, "memale", "lahore", "03034567821")
person1.display()
person2.display()
person1.update("address", "karachi")
person1.display()

name: bilal
age: 22
gender: male
address: islamabad
contact: 03004567897
name: ali
age: 20
gender: memale
address: lahore
contact: 03034567821
address updated successfully!

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 18/19
8/22/25, 10:44 PM Lab_01_Introduction_to_Pyton (1).ipynb - Colab
name: bilal
age: 22
gender: male
address: karachi
contact: 03004567897

https://colab.research.google.com/drive/16KZeOwQjzX7KqK2muuZD2SPTiSKDArOr#scrollTo=AzugRc72FD7Y&printMode=true 19/19

You might also like