Lab 01 Introduction To Pyton (1) .Ipynb - Colab
Lab 01 Introduction To Pyton (1) .Ipynb - Colab
ipynb - Colab
Lab# 01
Learning Outcomes:
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.
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.
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
if True:
print("This is indented correctly") # valid
if True:
print("Error due to missing indentation")
keyboard_arrow_down 3. Comments
keyboard_arrow_down 4. Statements
x = 5;
y = 10;
print(x + y)
15
keyboard_arrow_down 5. 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'''
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
Mastering these concepts will provide a solid foundation for all your Python programming endeavors.
x = 10 # x is integer
x = "Hello" # x is now string
x = [1, 2, 3] # x is now list
Must start with a letter (a-z, A-Z) or underscore (_) Can contain letters, digits, and underscores Case-sensitive Cannot be Python keywords
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
# Integer examples
positive_num = 42
negative_num = -17
zero = 0
# Float examples
pi = 3.14159
negative_float = -2.5
scientific = 1.5e2 # Scientific notation (150.0)
small_num = 1.5e-3 # 0.0015
# Complex numbers
z1 = 3 + 4j
z2 = complex(2, -1) # 2 - 1j
z3 = 5j # Pure imaginary
3.0
4.0
5.0
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
# 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
False
True
False
False
False
False
True
True
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)
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")
# Basic input
name = input("Enter your name: ")
print(f"Hello, {name}!")
# 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")
import getpass
# 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")
Hello, World!
42
[1, 2, 3]
Name: Ahmed
Age: 25
Hello-World
Hello World
Next line
apple, banana, cherry
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
# 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.")
Syntax
# 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.")
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: ")
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
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
# Simple nested if
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
match value:
case pattern1:
# Code for pattern1
case pattern2:
# Code for pattern2
case _: # Default case (optional)
# Code for default case
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)
# 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 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.
Basic Syntax
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
Where:
0
1
2
3
4
2
3
4
5
6
1
3
5
7
9
10
8
6
4
2
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
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!")
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
# 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)
# Call function
result = calculate_area(length, width)
# Print result
print("The area of the rectangle is:",result)
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?
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)
(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.
asma,fast,EE
keyboard_arrow_down Task# 3
(a) Declare variables for name, age, and GPA. Print them in a sentence.
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)
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.
enter radius12
75.408
enter marks67
enter marks89
enter marks90
enter marks56
enter marks100
80.4
100
56
80.4
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.
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.
while True:
print("1 Addition")
print("2 Subtraction")
print("3 Multiplication")
print("4 Division")
print("5 Exponentiation")
print("6 Floor Division")
print("7 Exit")
if choice == "7":
print("exit")
break
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:
Create object of the class and demonstrate how they can be used to store and manage biodata of different people.
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