0% found this document useful (0 votes)
4 views55 pages

Python 2

Python is a versatile, high-level programming language known for its readability and ease of use, making it an excellent choice for beginners. It supports multiple programming paradigms and is widely used in various applications, including web development and data analysis. The document provides an overview of Python's features, installation instructions, basic syntax, and essential programming concepts such as variables, data types, and user input.

Uploaded by

alfrjbas016
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)
4 views55 pages

Python 2

Python is a versatile, high-level programming language known for its readability and ease of use, making it an excellent choice for beginners. It supports multiple programming paradigms and is widely used in various applications, including web development and data analysis. The document provides an overview of Python's features, installation instructions, basic syntax, and essential programming concepts such as variables, data types, and user input.

Uploaded by

alfrjbas016
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

Python

Lecture 1
Introduction
Why Should You Use Python?

Python is a high-level, interpreted, interactive, and object-orientedprogramming


language that’s a great choice as a rst language because its code reads like English.
It’s exible, powerful, and allows you to do many things, both big and small.

With Python, you can write basic programs and scripts, as well as create complex and
large-scale enterprise solutions. Here’s a sampling of its uses:
fl
fi

Building desktop applications, including GUI applications, CLI tools, and even
games
• Doing mathematical and scienti c data analysis
• Building web applications
• Administering computer systems and automating tasks
• Performing DevOps tasks
You’ll nd Python across many high-traf c websites. For example, Reddit is written in
Python. Dropbox’s earliest prototypes were in Python, and it remains central there.
YouTube uses Python among its back-end languages. Meanwhile, Instagram runs on
Django, and Pinterest has historically used Python with a modi ed Django stack.
Python offers many features that make it attractive as your rst programming
language:
Compared to other programming languages, Python offers several key features:

Interpreted: It’s portable and quicker to experiment with than compiled languages. •
Multiparadigm: It lets you write code in different styles, including object-oriented, •
imperative, and functional.
Dynamically typed: It checks variable types at runtime, so you don’t need to •
declare them explicitly.
fi
fi
fi
fi
fi
Strongly typed: It won’t let unsafe operations on incompatible types go unnoticed. •

Note \
Python can be installed on Windows, macOS, and Linux.
Students may download it from the official website if they wish to run Python locally on their
own devices.
However, for this course we will use Replit for all practical work.

How to Use Python on Replit


1. Go to the website
Visit: [Link]
2. Sign up or log in
Create a free account using Google or GitHub.
3. Click on “Create Repl”
Start a new project.
4. Select Python
Choose Python as the programming language.
5. Start coding
Write and run your Python code directly in the editor.
Important Note
Replit automatically installs Python libraries.
When you use import, the required library is installed automatically—no manual
installation needed.
You can also work directly through this link:
[Link]

How to Use Python: What’s the Basic Syntax?


The Python syntax is clear, concise, and focused on readability. Readability is
arguably one of the most appealing features of the language itself. It makes Python
ideal for those learning to program. In this section, you’ll learn about several key
components of Python syntax:
• Comments
• Variables
• Keywords
• Built-in data types
• Conditional statements
• Loops
• Functions
• Classes
• Imports
In the following sections, you’ll learn the essentials of Python’s syntax. With this
knowledge, you’ll understand the basics of how to use Python to write real programs.

Comments
[Link]
Comments are pieces of text that live in your code but are ignored by the Python
interpreter as it executes the code. You can use comments to quickly document
certain parts of your code so that other developers can understand what the code
does or why it’s written a certain way.

To write a comment in Python, just add a hash mark (#) before your comment text:
# This is a comment on its own line
The Python interpreter ignores the text after the hash mark up to the end of the line.
You can also add inline comments to your code. In other words, you can combine a
Python expressionor statement with a comment in a single line, given that the
comment is at the end of the line:

greeting = "Hello, World!" # This is an inline comment


You should use inline comments sparingly to clear up pieces of code that aren’t
obvious on their own.

Variables
In Python, variables are names attached to a particular object. They hold a reference,
or pointer, to the memory address at which an object is stored. Once you assign an
object to a variable, you can access the object using that variable name.

To use a Python variable in your code, you need to de ne it in advance. Here’s the
syntax:

variable_name = variable_value
fi
You should use a naming scheme that makes your variables intuitive and readable.
The variable name should provide some indication as to what the values assigned to it
are.
Here are some examples of valid and invalid variable names in Python:

>>> numbers = [1, 2, 3, 4, 5]


>>> numbers
[1, 2, 3, 4, 5]

>>> first_num = 1
>>> first_num
1

>>> π = 3.141592653589793
>>> π
3.141592653589793

>>> 1rst_num = 1
File "<python-input-6>", line 1
1rst_num = 1
^
SyntaxError: invalid decimal literal
Your variable names can be any length and can consist of uppercase and lowercase
letters (A-Z, a-z), digits (0-9), and the underscore character (_). In summary, variable
names should be alphanumeric, but note that even though variable names can contain
digits, their rst character can’t be a digit.

User Input
Python allows the user to enter data using the input() function.
name = input("Enter your name: ")

The value entered by the user is stored as text (string).

Keywords
[Link]

Like any other programming language, Python has a set of special words that are part of its
syntax. These words are known as keywords.

Here is a list of the Python keywords. Enter any keyword to get more help.
fi
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
Each of these keywords plays a role in Python syntax. They have specific meanings and
purposes in the language, so you shouldn’t use them for anything but those specific
purposes. For example, you shouldn’t use them as variable names in your code. In fact,
Python will prevent this by raising a syntax error if you try.

Built-in Data Types


[Link]

Python has a handful of built-in data types, such as numbers (integers, oats, and
complex numbers), Booleans, strings, bytes, lists, tuples, dictionaries, and sets.
You can manipulate the built-in data types using different tools. Here are some of
them:

fl
• Operators
• Built-in functions
• Methods
In the following sections, you’ll learn how to use Python’s built-in data types, including
numbers, Booleans, strings, bytes, lists, tuples, dictionaries, and sets, with quick
practical examples.

Numbers
[Link]

Python provides integers, oating-point numbers, and complex numbers. Integers and
oating-point numbers are the most commonly used numeric types in day-to-day
programming, while complex numbers have speci c use cases in math and science.

Here’s a summary of their more relevant features:


fl
fl
fi
Integer Whole numbers 1, 2, 42, 476, -99999 int

Floating- Numbers with 1.0, 2.2, 42.09, 476.1, -99999.9 float


point decimal points
Complex Numbers with a complex(1, 2), complex(-1, 7), complex
realpart and an complex("1+2j")
imaginarypart

When you combine math operators with numbers, you form expressions that Python
can evaluate. Arithmetic operators represent common operations such as addition,
subtraction, multiplication, division, and so on:

>>> # Addition
>>> 5 + 3
8

>>> # Subtraction
>>> 5 - 3
2

>>> # Multiplication
>>> 5 * 3
15

>>> # True division


>>> 5 / 3
1.6666666666666667

>>> # Floor division


>>> 5 // 3
1

>>> # Modulus (returns the remainder from division)


>>> 5 % 3
2

>>> # Power
>>> 5 ** 3
125
These operators work with two operands. The operands can be numbers or variables
that point to numbers.
Besides operators, Python provides built-in functions that allow you to manipulate
numbers. These functions are always available to you. In other words, you don’t have
Consider the float() function. Given an integer number or a string representing a
number, float()returns a oating-point number:

>>> # Integer numbers


>>> float(9)
9.0
>>> float(-99999)
-99999.0

>>> # Strings representing numbers


>>> float("2")
2.0
>>> float("-200")
-200.0
>>> float("2.25")
2.25

Similarly, int() returns an integer when you call it with a oating-point number or a
string as an argument. This function doesn’t round a oat input up to the nearest
integer. Instead, it truncates the input, throwing out anything after the decimal point,
and returns the resulting integer. For example, an input of 10.6 returns 10 instead of
11. Likewise, 3.25returns 3:

>>> # Floating-point numbers


>>> int(10.6)
fl
fl
fl
10
>>> int(3.25)
3

>>> # Strings representing numbers


>>> int("2")
2
>>> int("2.3")
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: '2.3'

Using Input with Number Conversion

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

price = float(input("Enter the price: "))

Use int() or float() to convert user input into numbers before calculations.

Booleans

[Link]
In Python, Booleans have two possible values: True or False. Note that these values
must start with a capital letter.
You use Boolean values to express the truth value of an expression or object.
Booleans are handy when you’re writing predicate functions or using comparison
operators, such as greater than (>), less than (<), equal to (==), and so on:

>>> 2 < 5
True
>>> 4 > 10
False
>>> 4 <= 3
False
>>> 3 >= 3
True
>>> 5 == 6
False
>>> 6 != 9
True
Comparison expressions like these evaluate to the Boolean values True or False.

Python provides a built-in function called bool()that’s closely related to Boolean


values. Here’s how it works:
>>> bool(0)
False
>>> bool(1)
True

>>> bool("")
False
>>> bool("a")
True

>>> bool([])
False
>>> bool([1, 2, 3])
True
The bool() function takes an object as an argument and returns True or False
according to the object’s truth value.

Strings
[Link]
Strings are pieces of text or sequences of characters that you can de ne using single,
double, or triple quotes:

>>> # Use single quotes


>>> 'Hello there!'
'Hello there!'

>>> # Use double quotes


>>> "Welcome to Real Python!"
'Welcome to Real Python!'

>>> # Use triple quotes


>>> """Thanks for joining us!"""
'Thanks for joining us!'

>>> # Escape characters


>>> 'can\'t'
"can't"
>>> "can't"
"can't"
You can use different types of quotes to create string objects in Python. You can also
use a backslash (\) to escape characters with special meaning, such as the quotes
themselves.
You can use the plus operator (+) to concatenatemultiple strings in a new string:

fi
>>> "Happy" + " " + "pythoning!"
'Happy pythoning!'
When used with strings, the plus operator (+) concatenates them into a single string.
Note that you need to include a space (" ") between words to have proper spacing in
your resulting string.
Python comes with many useful built-in functions and methods for string
manipulation. For example, if you pass a string as an argument to len(), then you’ll
get the string’s length, or the number of characters it contains:

>>> len("Happy pythoning!")


16
When you call len() using a string as an argument, you get the total number of
characters, including any whitespace, in the input string.
For example, [Link]() takes an iterable of strings and combines them into a new
string. The string on which you call the method plays the role of a separator:

>>> " ".join(["Happy", "pythoning!"])


'Happy pythoning!'
The .upper() method returns a copy of the underlying string with all the letters
converted to uppercase:
>>> "Happy pythoning!".upper()
'HAPPY PYTHONING!'
The .lower() method returns a copy of the underlying string with all the letters
converted to lowercase:

>>> "HAPPY PYTHONING!".lower()


'happy pythoning!'
The .format() method performs a string formattingoperation. This method provides a
lot of exibility for string formatting and interpolation:

>>> name = "John Doe"


>>> age = 25
>>> "My name is {0} and I'm {1} years old".format(name, age)
"My name is John Doe and I'm 25 years old"
You can also use an f-string to format your strings without using .format():

>>> name = "John Doe"


>>> age = 25
>>> f"My name is {name} and I'm {age} years old"
"My name is John Doe and I'm 25 years old"
Python’s f-strings are an improved string formatting syntax. They’re string literals with
an f at the beginning, outside the quotes. Expressions that appear in embedded curly
braces ({}) are replaced with their values in the formatted string.
fl
Strings are sequences of characters. As with other sequences, you can retrieve
individual characters from a string using their index. An index is a zero-based integer
associated with the position of a value in a sequence:

>>> welcome = "Welcome to Real Python!"


>>> welcome[0]
'W'
>>> welcome[11]
'R'
>>> welcome[-1]
'!'
This syntax runs an indexing operation that retrieves the character at the position
indicated by the target index. Note that a negative index retrieves the element in
reverse order, with -1 being the index of the last character in the string.

You can also retrieve a part of a string by slicing it:


[Link]

>>> welcome[0:7]
'Welcome'
>>> welcome[11:22]
'Real Python'
Slicing operations follow the syntax [start:end:step]. Here, start is the index of the
rst value to include in the slice, and end is the index of the last value, which isn’t
included in the returned slice.
Finally, step is an optional integer representing the number of values to jump over
while extracting the values from the original string. A step of 2, for example, will return
every other element between start and stop.

Lists
[Link]
fi
In Python, lists are mutable sequences that group various objects together. To create
a list, you use a sequence of comma-separated objects in square brackets ([]), as
shown below:

>>> # Define an empty list


>>> empty = []
>>> empty
[]

>>> # Define a list of numbers


>>> numbers = [1, 2, 3, 100]
>>> numbers
[1, 2, 3, 100]

>>> # Modify the list in place


>>> numbers[3] = 200
>>> numbers
[1, 2, 3, 200]

>>> # Define a list of strings


>>> ["batman", "superman", "spiderman"]
['batman', 'superman', 'spiderman']

>>> # Define a list of objects with different data types


>>> ["Hello World", [4, 5, 6], False]
['Hello World', [4, 5, 6], False]
They can be empty, as you saw in the rst example. Because lists are mutable
sequences, you can modify them in place using index notation and an assignment
operation. Lists can also contain objects of different data types, including other lists.
Lists are sequences like strings, so you can access their individual items using zero-
based integer indices:

>>> numbers = [1, 2, 3, 4]


>>> numbers[0]
1
>>> numbers[1]
2

>>> superheroes = ["batman", "superman", "spiderman"]


>>> superheroes[-1]
"spiderman"
>>> superheroes[-2]
"superman"
Indexing operations also work with Python lists, so you can retrieve any item in a list
by using its positional index. Negative indices retrieve items in reverse order, starting
from the last item at index -1.
You can also slice lists:

>>> numbers = [1, 2, 3, 4]


fi
>>> new_list = numbers[0:3]
>>> new_list
[1, 2, 3]
If you nest a list, a string, or any other sequence within a list, then you can access the
inner items using multiple indices in a row:

>>> mixed_types = ["Hello World", [4, 5, 6], False]


>>> mixed_types[0][6]
'W'

>>> mixed_types[1][2]
6
In these examples, the rst index gets the item from the container list, mixed_types,
and the second index retrieves an item from the nested sequence.
You can also concatenate lists using the plus (+) operator:

>>> fruits = ["apples", "grapes", "oranges"]


>>> veggies = ["corn", "kale", "spinach"]

>>> fruits + veggies


['apples', 'grapes', 'oranges', 'corn', 'kale', 'spinach']
This list concatenation returns a new list object containing all the items from the
original lists.
fi
You can also use len() with lists. Given a list as an argument, len() returns the list’s
length, or the number of objects it contains:

>>> numbers = [1, 2, 3, 4]


>>> len(numbers)
4
Lists provide a rich set of methods that allow you to manipulate them. Below are some
of the most commonly used methods.
The .append() method takes an object as an argument and adds it to the end of the
underlying list:

>>> fruits = ["apples", "grapes", "oranges"]


>>> [Link]("blueberries")
>>> fruits
['apples', 'grapes', 'oranges', 'blueberries']
The .sort() method sorts the underlying list in place:

>>> [Link]()
>>> fruits
['apples', 'blueberries', 'grapes', 'oranges']
The .pop() method takes an integer index as an argument, then removes and returns
the item at that index in the underlying list:
>>> numbers = [1, 2, 3, 4]
>>> [Link](2)
3
>>> numbers
[1, 2, 4]

Tuples
[Link]

Tuples are similar to lists, but they’re immutable sequences. This means that you can’t
change their content after creation:

>>> employee = ("Jane", "Doe", 31, "Software Developer")

>>> employee[0] = "John"


Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
If you try to change a tuple in place, then you get a TypeError exception, which
indicates that tuples don’t support in-place modi cations.
fi
Note that to create a tuple object, you only need a series of comma-separated values.
You don’t need to include parentheses. However, using the parentheses to delimit a
tuple makes your code more readable and explicit.
An edge case would be when you need to create a single-element tuple. In this
situation, you need to add a comma after the value. Otherwise, you won’t be creating a
tuple:

>>> type((1))
<class 'int'>

>>> type((1,))
<class 'tuple'>
In this example, you use the built-in type() function to demonstrate that the
parentheses don’t de ne the tuple—the comma does.

Just like lists, you can also do indexing and slicing with tuples:

>>> employee = ("Jane", "Doe", 31, "Software Developer")


>>> employee[0]
'Jane'
>>> employee[1:3]
('Doe', 31)
fi
You can use indices to retrieve speci c items in the tuples. Note that you can also
retrieve slices from a tuple with a slicing operation.

Dictionaries
[Link]

Python dictionaries are associative arrayscontaining a collection of key-value pairs.


There are several ways to create a dictionary in Python. The most common one is to
use a literal. However, you can also use the dict() constructor:

>>> john = {"name": "John Doe", "age": 25, "job": "Python Developer"}
>>> john
{'name': 'John Doe', 'age': 25, 'job': 'Python Developer'}

>>> jane = dict(name="Jane Doe", age=24, job="Web Developer")


>>> jane
{'name': 'Jane Doe', 'age': 24, 'job': 'Web Developer'}
The rst approach involves using a pair of curly braces, in which you add a comma-
separated series of key-value pairs, using a colon (:) to separate the keys from the
values. The second approach uses dict(), which can take keyword arguments and
fi
fi
turn them into a dictionary. In this case, the keywords work as the keys and the
arguments as the values.
You can retrieve the value associated with a given key using the following syntax:

>>> john["name"]
'John Doe'

>>> john["age"]
25
This is quite similar to an indexing operation, but this time, you use a descriptive key
instead of an index.
You can also retrieve the keys, values, and key-value pairs in a dictionary using
the .keys(), .values(), and .items() methods, respectively:

>>> # Retrieve all the keys


>>> [Link]()
dict_keys(['name', 'age', 'job'])

>>> # Retrieve all the values


>>> [Link]()
dict_values(['John Doe', 25, 'Python Developer'])

>>> # Retrieve all the key-value pairs


>>> [Link]()
dict_items([('name', 'John Doe'), ('age', 25), ('job', 'Python Developer')])

Sets
[Link]

Python also provides a built-in set data type. Sets are unordered and mutable
collections of unique objects.
You can create sets in several ways. Here are a few examples:

>>> {"John", "Jane", "Linda"}


{'John', 'Linda', 'Jane'}

>>> set(["David", "Mark", "Marie"])


{'Mark', 'David', 'Marie'}

>>> empty = set()


>>> empty
set()
In the rst example, you use a set literal consisting of curly braces and a series of
comma-separated objects.
fi
When you use set(), you need to provide an iterablewith the objects you want to
include in the set. Finally, if you want to create an empty set, then you need to use
set() without arguments. Using an empty pair of curly braces creates an empty
dictionary instead of a set.
One of the most common use cases for sets is removing duplicate items from an
iterable:

>>> set([1, 2, 2, 3, 4, 5, 3])


{1, 2, 3, 4, 5}
Because sets are collections of unique objects, when you create a set using set() with
an iterable as an argument, the class constructor removes any duplicate objects and
keeps only one instance of each in the resulting set.

You can use some built-in functions with sets like you’ve done with other built-in data
types. For example, if you pass a set as an argument to len(), then you get the
number of items in the set:

>>> employees = {"John", "Jane", "Linda"}


>>> len(employees)
3
You can also use operators to manage sets in Python. In this case, most operators
represent typical set operations like union (|), intersection (&), difference(-), and so
on:

>>> primes = {2, 3, 5, 7}


>>> evens = {2, 4, 6, 8}

>>> # Union
>>> primes | evens
{2, 3, 4, 5, 6, 7, 8}

>>> # Intersection
>>> primes & evens
{2}

>>> # Difference
>>> primes - evens
{3, 5, 7}
Sets provide a variety of methods, including those that perform set operations like in
the example above. They also provide methods to modify or update the underlying set.
For example, [Link]()takes an object and adds it to the set:

>>> primes = {2, 3, 5, 7}

>>> [Link](11)
>>> primes
{2, 3, 5, 7, 11}
The .remove() method takes an object and removes it from the set:

>>> primes = {2, 3, 5, 7, 11}

>>> [Link](11)
>>> primes
{2, 3, 5, 7}

Conditionals

[Link]

Sometimes, you need to run a given code block depending on whether certain
conditions are met. In this situation, conditional statements are your allies. They’re
control ow statements that manage the execution of a code block based on the truth
value of a condition.
fl
You can create a conditional statement in Python with the if, elif, and else keywords.
Here’s the general syntax:

if condition_0:
# Run if condition_0 is true
<block>
elif condition_1:
# Run if condition_1 is true
<block>
elif condition_2:
# Run if condition_2 is true
<block>
...
else:
# Run if all expressions are false
<block>
The code block under if only runs if the condition is true. The elif and else clauses
are optional. The rst elif clause evaluates condition_1 only if condition_0 is false. If
condition_0 is false and condition_1 is true, then only the code block associated with
condition_1 will run, and so on.

The else clause will run only if all the previous conditions are false, providing a default
code block. You can have as many elif clauses as you need, including none at all, but
you can only have one elseclause.
fi
Here are some examples of how this works:

>>> age = 21
>>> if age >= 18:
... print("You're a legal adult")
...
You're a legal adult

>>> age = 16
>>> if age >= 18:
... print("You're a legal adult")
... else:
... print("You're NOT an adult")
...
You're NOT an adult

>>> age = 18
>>> if age > 18:
... print("You're over 18 years old")
... elif age == 18:
... print("You're exactly 18 years old")
...
You're exactly 18 years old
Loops
[Link]

[Link]

[Link]

Sometimes, you need to traverse an iterable of data or repeat a piece of code several
times. In this scenario, you can use a loop. Python provides two types of loops:
1. for loops
2. while loops
Python’s for loops are designed to iterate over the items in a collection, such as lists,
tuples, strings, and dictionaries. In contrast, while loops are useful when you need to
execute a block of code repeatedly as long as a given condition remains true.

Here’s the general syntax for creating a for loop:

for loop_var in iterable:


# Repeat this code block until iterable is exhausted
# Do something with loop_var...
if break_condition:
break # Leave the loop
if continue_condition:
continue # Resume the loop without running the remaining code
# Remaining code...
else:
# Run this code block if no break statement is run
This type of loop normally performs as many iterations as items in the target iterable.
You commonly use each iteration to perform a given operation on or with the value of
loop_var. The elseclause is optional and runs when the loop nishes. The break and
continue statements are also optional.

Here’s a quick example of a for loop that allows you to iterate over a tuple of numbers:

>>> for i in (1, 2, 3, 4, 5):


... print(i)
... else:
... print("The loop wasn't interrupted")
...
1
2
3
4
5
The loop wasn't interrupted
When the loop processes the last number in the tuple, the ow of execution jumps to
the else clause and prints The loop wasn't interrupted on your screen. That’s
because your loop wasn’t interrupted by a break statement.
fl
fi
You commonly use an else clause in loops that include at least one break statement in
their code block. Otherwise, there’s no need for it.

If the loop nds a break_condition, then the breakstatement interrupts the loop’s
execution and jumps to the next statement below the loop, without consuming the rest
of the items in iterable:

>>> for i in (1, 2, 3, 4, 5):


... if i == 3:
... print("Number found:", i)
... break
... else:
... print("Number not found")
...
Number found: 3
When i == 3 is true, the loop prints Number found: 3 on your screen and then hits the
break statement. This interrupts the loop, and the execution jumps to the line below
the loop without running the elseclause. If you change the condition to i == 6 or any
other number that’s not in the tuple, then the loop doesn’t hit the break statement and
prints Number not found.
If the continue_condition is true, then the continue statement resumes the loop without
running the remaining statements in the loop’s code block:
fi
>>> for i in (1, 2, 3, 4, 5):
... if i == 3:
... continue
... print(i)
...
1
2
4
5
This time, the continue statement restarts the loop when i == 3. That’s why you don’t
see the number 3in the output.
Both break and continue should be wrapped in a conditional. Otherwise, the loop will
always break when it hits break, and continue when it hits continue.

You typically use a while loop when you don’t know beforehand how many iterations
you need to complete a given operation. Here’s the general syntax for a while loop in
Python:

while condition:
# Repeat this code block as long as the condition is true
# Do something...
if break_condition:
break # Leave the loop
if continue_condition:
continue # Resume the loop without running the remaining code
# Remaining code...
else:
# Run this code block if no break statement is run
This loop works similarly to a for loop, but it’ll keep iterating until condition becomes
false. A common problem with this type of loop comes when you provide a condition
that never evaluates to False. In such cases, you’ll have a potentially in nite loop.

Here’s an example of how the while loop works:

>>> count = 1
>>> while count < 5:
... print(count)
... count += 1
... else:
... print("The loop wasn't interrupted")
...
1
2
3
4
The loop wasn't interrupted
Again, the else clause is optional, and you’ll commonly use it with a break statement in
the loop’s code block. The break and continue statements work the same way in a for
loop.

fi
Practical Example: Menu Loop

while True:
print("1. Analyze Student")
print("2. Exit")

choice = input("Enter choice: ")


if choice == "1":
print("Analyzing Student...")
elif choice == "2":
break
else:
print("Invalid choice")
Functions
[Link]

In Python, a function is a named code block that performs actions and optionally
computes the result, which can be returned to the calling code.
You can use the following syntax to de ne a function:

def function_name(arg1, arg2, ..., argN):


# Do something with arg1, arg2, ..., argN here...
return return_value
The def keyword starts the function header. Then you need the function’s name and a
list of arguments in parentheses. Note that the list of arguments is optional, but the
parentheses are syntactically required.

Next, you can de ne the function’s code block, which will begin one level of
indentation to the right. The return statement is also optional and is the statement you
use if you need to send a return_value back to the caller code.
fi
fi
To use a function, you need to call it with the appropriate arguments if needed. A
function call consists of the function’s name, followed by the function’s arguments in
parentheses:

function_name(arg1, arg2, ..., argN)


You can have functions that don’t require arguments when called, but parentheses are
always needed. If you forget them, then you won’t be calling the function but
referencing it as a function object.

Classes
[Link]

Classes let you bundle data (attributes) and behavior (methods) into reusable
blueprints for objects. They’re a core part of object-oriented programming in Python
and help you model concepts from your problem domain.

Here’s a quick example of how to create a class and instantiate it:

>>> class Dog:


... def __init__(self, name, age):
... [Link] = name
... [Link] = age
...
... def bark(self):
... return "Woof! Woof!"
...

>>> fido = Dog("Fido", 3)


>>> [Link], [Link]
('Fido', 3)
>>> [Link]()
"Woof! Woof!"

Calculator Class Example


class Calculator:
def add(self, a, b):
return a + b

calc = Calculator()
print([Link](5, 3))

The class keyword allows you to de ne the class. Then, you have the .__init__(),
which runs when you create a new object and initializes its attributes.
fi
Once you’ve de ned a class, you can create instances using the class constructor
with appropriate arguments. Finally, you can access the attributes and methods on the
instance.

Imports
[Link]

Imports allow you to reuse code by bringing modules and packages into your main
program. They’re a critical tool for programs where you split the code into multiple .py
les.

Here are some quick examples of common syntax constructs that you’ll use to import
modules and objects in your Python code:

>>> import math


>>> [Link](16)
4.0

>>> from math import sqrt


>>> sqrt(25)
fi
fi
5.0

>>> from math import pi as PI


>>> PI
3.141592653589793
In these examples, you import math and use dot notation to call sqrt(). Then, you
import the sqrt()function directly into your current session and call it again. Finally,
you import pi as PI, which is an alias

How Do You Handle Errors in Python?


Errors can frustrate programmers at every level of experience, and identifying and handling
them is a core skill. In Python, there are two types of code-based errors—syntax errors and
exceptions

Syntax Errors
Syntax errors occur when the syntax of your code isn’t valid in Python. They automatically
stop the execution of your programs. For example, the ifstatement below is missing a
colon at the end of its header, and Python quickly points out the error:

>>> if x < 9
File "<python-input-0>", line 1
if x < 9
^
SyntaxError: expected ':'
The missing colon at the end of the if statement is invalid Python syntax. Python’s parser
catches the problem and immediately raises a SyntaxErrorexception. The ^
character indicates where the parser found the problem.

Exceptions
Exceptions are raised by syntactically correct code at runtime to signal a problem during
program execution. For example, consider the following math expression:

>>> 12 / 0
Traceback (most recent call last):
File "<python-input-0>", line 1, in <module>
12 / 0
~~~^~~
ZeroDivisionError: division by zero

This code is syntactically correct, but it raises an exception during execution because division by zero is not
allowed.
Handling Exceptions with try / except

try:

num = int(input("Enter number: "))


except ValueError:

print("Invalid input")

This prevents the program from crashing when the user enters invalid data.

To start a project in Python

• [Link]
Python Assignment (Part 1 & Part 2)

Total: 10 Marks (5 + 5)

Week 1: Task 1-3 Marks


Write and run the following Python programs exactly as required.

Important Instructions
Convert all inputs to numbers
Display results clearly
Write all programs in one file
Separate each program using comments
Program 1: Addition
Take two numbers from the user
Convert them to numbers
Store them in variables
Display the result as:
The result is: …
Program 2: Even or Odd
Take one number from the user
Convert it to a number
Use a conditional statement
Display whether the number is:
even or odd
Program 3: Multiplication Table
Take a number from the user
Convert it to a number
Use a loop
Display the multiplication table from 1 to 10
Program 4: Simple Calculator (Without Class)
Take two numbers from the user
Convert them to numbers
Ask the user to choose an operation:
addition, subtraction, multiplication, or division
Use conditional statements to perform the operation
Display the result clearly
Submission
Submit one Python file (.py)
Include all 4 programs
Use comments to separate them
Add simple comments explaining your code
Week 2: Task 2 (7 Marks)
Build a terminal-based Python program using Object-Oriented Programming (OOP) to analyze a
student’s academic performance.

Requirements
Create a class named AcademicAnalyzer
Add methods for:

calculate_total()
calculate_average()
determine_grade()
display_report()

Ask the user to enter:

Student Name
Midterm Score
Assignment Score
Final Project Score

Use the following formulas:

Total = Midterm + Assignment + Final Project


Average = Total / 3

Grade Classification:

A → 90–100
B → 80–89
C → 70–79
D → 60–69
F → Below 60
Use a menu interface:

Analyze Student Performance


Exit

Handle errors using try/except


Bonus (Optional):
Store multiple student records in a list.

Submission \

Submit one Python file (.py)


Code must be organized
Use clear comments

You might also like