Python 2
Python 2
Lecture 1
Introduction
Why Should You Use Python?
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.
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:
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:
>>> 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: ")
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.
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.
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
>>> # 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:
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:
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.
>>> 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:
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:
>>> 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:
>>> 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:
>>> [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:
>>> 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:
Dictionaries
[Link]
>>> john = {"name": "John Doe", "age": 25, "job": "Python Developer"}
>>> john
{'name': 'John Doe', 'age': 25, 'job': 'Python Developer'}
>>> 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:
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:
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:
>>> # 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:
>>> [Link](11)
>>> primes
{2, 3, 5, 7, 11}
The .remove() method takes an object and removes it from the set:
>>> [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 a quick example of a for loop that allows you to iterate over a tuple of numbers:
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:
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.
>>> 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")
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:
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:
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.
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:
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:
print("Invalid input")
This prevents the program from crashing when the user enters invalid data.
• [Link]
Python Assignment (Part 1 & Part 2)
Total: 10 Marks (5 + 5)
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()
Student Name
Midterm Score
Assignment Score
Final Project Score
Grade Classification:
A → 90–100
B → 80–89
C → 70–79
D → 60–69
F → Below 60
Use a menu interface:
Submission \