Python Unit 1 Notes by Dr. Yusuf Perwej
Python Unit 1 Notes by Dr. Yusuf Perwej
Installing Python-
Python is a free, open-source programming language that is available for
everyone to use. It also has a huge and growing ecosystem with a variety of open-
source packages and libraries. If you would like to download and install Python
on your computer you can do for free at python.org.
Python Installation on Windows
1. Step 1: Select Python Version. ...
2. Step 2: Download Python Executable Installer. ...
3. Step 3: Run Executable Installer. ...
4. Step 4: Add Python to PATH (Optional) ...
5. Step 5: Verify Python Is Installed on Windows. ...
6. Step 6: Verify pip is Installed on Windows. ...
7. Step 7: Install virtualenv (Optional)
Python IDE-
A Python IDE, or Integrated Development Environment, is a software application
that provides a comprehensive set of tools and features specifically designed to
streamline and enhance the process of developing software using the Python
programming language. The Python interpreter is the application network
engineers use to execute scripts when testing basic features. An IDE is all-in-one
software with advanced features that enable engineers to write code efficiently.
Introduction to Clean Code:
Clean Code is a term from software development and addresses the clear,
comprehensible, traceable, logical and disciplined implementation of code. The
goal is to produce software efficiently and effectively, and to design the code so
that it is easily readable, changeable, and expandable.
What is Bad Code? Bad code is code that is poorly written, difficult to understand,
and challenging to maintain. It can be more than just syntax errors or minor bugs
Some signs of bad code: Complex, Poorly structured, Lacking documentation,
Duplicative, Excessive dependencies, unnecessarily complex, Not scalable,
Inconsistent in naming, overly verbose, Untested, Hard to read, has non-intuitive
variable names.
Text Editors-
A text editor is a tool that is used to write and edit program. They are usually
lightweight and can be great for learning. However, once your program gets
larger, you need to test and debug your code, that's where IDEs come in.
Some text editors for Python:
IDLE, PyCharm, Sublime Text, Visual Studio Code, Jupyter
What is indentation?
In Python, indentation is the use of spaces or tabs at the beginning of a line of
code to group and organize code.
Indentation is a requirement in Python, not just a convention. It's a key part of
Python's syntax and is used to:
Define blocks of code: Indentation is used to define blocks of code, such
as loops or functions.
Determine code flow: Indentation determines the flow of code.
Improve readability: Indentation makes code more readable and easier
to understand.
Ensure code cleanliness: Consistent indentation keeps code clean and
organized.
Facilitate collaboration: Consistent indentation helps developers
collaborate seamlessly.
In other programming languages, like C, C++, and Java, curly braces are used to
define a block of code.
Debugging-
Debugging is the process of finding, isolating and resolving coding errors known
as bugs in software programs. Debugging helps uncover the cause of coding
errors, prevent software function issues and improve the overall performance of
software.
Different between Interpreter & Compiler-
Feature Interpreter Compiler
Translates and executes code Translates the entire program
Execution
line by line into machine code, then executes
Speed of Slower (because it checks Faster (machine code is already
Execution line by line) generated before execution)
Feature Interpreter Compiler
Error Shows errors immediately Shows all errors together after
Detection (after the line is executed) compilation
No separate file created; Produces an independent
Output
executes directly executable file (e.g., .exe)
Memory Uses more memory (stores object
Uses less memory
Usage code)
C, C++, Java (with bytecode +
Examples Python, JavaScript, Ruby
JVM compiler), Go
Experimental Debugging-
Debugging is also like an experimental science. Once you have an idea what is
going wrong, you modify your program and try again. If your hypothesis was
correct, then you can predict the result of the modification, and you take a step
closer to a working program.
Formal and Natural Languages-
Natural languages are the languages that people speak, such as English, Spanish,
and French. They were not designed by people (although people try to impose
some order on them); they evolved naturally.
Formal languages are languages that are designed by people for specific
applications.
The Difference between Brackets, Braces, and Parentheses in Python-
Symbol Purpose in Python
Function calls & definitions, grouping expressions, defining
Parentheses()
tuples, creating generators
Brackets [] Creating lists, indexing/slicing sequences, list comprehensions
Braces {} Defining dictionaries (key→value) and sets (unique, unordered)
Example:
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Output:
Enter your name: perwej
Hello, perwej ! Welcome!
Example:
color = input("What color is rose?: ")
print(color)
Output:
What color is rose?: Red
Red
Elements of Python
The basic elements of Python, essential for constructing programs and defining
logic, include:
Variables: Named storage locations used to hold data values.
Literals: Fixed values that appear directly in code, such as numbers
(e.g., 10, 3.14), strings (e.g., "hello"), booleans (e.g., True, False), and None.
Keywords: Reserved words with special meanings in Python,
like if, else, for, while, def, class, etc., which cannot be used as identifiers.
Identifiers: Names given to variables, functions, classes, and other program
entities, following specific naming rules.
Operators: Symbols that perform operations on values and variables, such as
arithmetic operators (+, -, *, /), comparison operators (==, !=, <, >), and logical
operators (and, or, not).
Data Types: Classifications of data that determine the operations that can be
performed on them. Common built-in data types include integers (int), floating-
point numbers (float), strings (str), booleans (bool), lists (list), tuples (tuple),
dictionaries (dict), and sets (set).
Control Flow Statements: Structures that dictate the order of execution in a
program. These include:
Conditionals: if, elif, else statements for executing code blocks based on
conditions.
Loops: for and while loops for repeatedly executing code blocks.
Functions: Reusable blocks of code designed to perform a specific task,
promoting modularity and code reuse.
Classes and Objects: Fundamental concepts of Object-Oriented Programming
(OOP) in Python, allowing the creation of custom data types and encapsulating
data and behavior.
Modules and Packages: Mechanisms for organizing and reusing Python code,
allowing for the import of pre-written functionalities.
Python Variables:
Variables are containers for storing data values. Variables are used as
placeholders for information that can be recalled later in the coding process.
Python has no command for declaring a variable. A variable is created the
moment you first assign a value to it.
Example: Output:
x=5 5
y = "John" John
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even
change type after they have been set.
Example: Output:
x=4 # x is of type int Sally
x = "Sally" # x is now of type str
print(x)
To define the values of various data types of Python and check their data types
we use the type() function.
Example-
a = []
a = [1, 2, 3]
print(a)
b = ["Geeks", "For", "Geeks", 4, 5]
print(b)
Output-
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]
Example-
a = ["Geeks", "For", "Geeks"]
print("Accessing element from the list")
print(a[0])
print(a[2])
print("Accessing element using negative indexing")
print(a[-1])
print(a[-3])
Output-
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Python Tuple – Just like a list, a tuple is also an ordered collection of Python
objects. The only difference between a tuple and a list is that tuples are
immutable. Tuples cannot be modified after it is created.
Creating a Tuple in Python- In Python Data Types, tuples are created by placing
a sequence of values separated by a ‘comma’ with or without the use of
parentheses for grouping the data sequence. Tuples can contain any number of
elements and of any datatype (like strings, integers, lists, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky.
Having one element in the parentheses is not sufficient, there must be a trailing
‘comma’ to make it a tuple.
Access Tuple Items In order to access the tuple items refer to the index number.
Use the index operator [ ] to access an item in a tuple.
Example-
tup1 = ('Geeks', 'For')
print("\nTuple with the use of String: ", tup1)
Output-
Tuple with the use of String: ('Geeks', 'For')
Example-
tup1 = tuple([1, 2, 3, 4, 5])
print(tup1[0])
print(tup1[-1])
print(tup1[-3])
Output-
1
5
3
Output-
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
The first two lines will print the type of the boolean values True and False, which
is <class 'bool'>. The third line will cause an error, because true is not a valid
keyword in Python. Python is case-sensitive, which means it distinguishes
between uppercase and lowercase letters.
Set Data Type in Python
In Python Data Types, Set is an unordered collection of data types that is iterable,
mutable, and has no duplicate elements. The order of elements in a set is
undefined though it may consist of various elements.
Create a Set in Python Sets can be created by using the built-in set() function
with an iterable object or a sequence by placing the sequence inside curly braces,
separated by a ‘comma’. The type of elements in a set need not be the same,
various mixed-up data type values can also be passed to the set.
Access Set Items Set items cannot be accessed by referring to an index, since
sets are unordered the items have no index. But we can loop through the set items
using a for loop, or ask if a specified value is present in a set, by using the in the
keyword.
To create an empty set, you must use set(), as {} creates an empty dictionary.
Common Uses of Sets:
Removing duplicates:
Easily convert a list or other iterable to a set to obtain only the unique
elements.
Fast membership testing:
Checking if an element exists in a set using the in keyword is highly efficient.
Mathematical set operations:
Sets support operations like union (| or union()), intersection
(& or intersection()), difference (- or difference()), and symmetric difference
(^ or symmetric_difference()).
Example-
s = {10, 50, 20}
print(s)
print(type(s))
Output-
{10, 50, 20}
<class 'set'>
Example-
s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)
s2 = set(["Geeks", "For", "Geeks"])
print("Set with the use of List: ", s2)
Output-
Set with the use of String: {'s', 'o', 'F', 'G', 'e', 'k', 'r'}
Set with the use of List: {'Geeks', 'For'}
Example-
set1 = set(["Geeks", "For", "Geeks"])
print(set1)
for i in set1:
print(i, end=" ")
print("Geeks" in set1)
Output-
{'Geeks', 'For'}
Geeks For True
Example-
# Create a set
fruits = {"apple", "banana", "cherry"}
# Add an element
fruits.add("orange")
print(fruits) # Output might be {'cherry', 'apple', 'orange', 'banana'} (order varies)
# Try to add a duplicate
fruits.add("apple")
print(fruits) # Output remains the same, 'apple' is not added again
# Check for membership
if "banana" in fruits:
print("Banana is in the set.")
# Remove an element
fruits.remove("cherry")
print(fruits)
# Perform set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # or set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
Example-
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d)
d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(d1)
Output-
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Example-
d = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print(d['name'])
print(d.get(3))
Output-
For
Geeks
Output-
15.5
<class 'float'>
Example-
num_str = "123"
num_int = int(num_str) # Explicitly convert string to integer
print(num_int)
print(type(num_int))
price_float = 25.99
price_int = int(price_float) # Explicitly convert float to integer (truncates decimal)
print(price_int)
print(type(price_int))
Output-
123
<class 'int'>
25
<class 'int'>
Data Loss: Explicit conversion, especially from a larger data type to a smaller
one (e.g., float to int), can lead to data loss.
Type Compatibility: Not all type conversions are possible (e.g., converting a
non-numeric string to an integer will raise a ValueError).
Error Handling: When performing explicit conversions, particularly with user
input, it is good practice to use try-except blocks to handle
potential ValueError exceptions.
Operators:
Operators are used to perform operations on variables and values.
For example- We use the + operator to add together two values-
Example-
print(10 + 5)
Output:
15
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators:
Arithmetic operators are used with numeric values to perform common
mathematical operations:
1. Addition +
x+y
Example:
x=5
y=3
print(x + y)
Output:
8
2. Subtraction –
x–y
Example:
x=5
y=3
print(x - y)
Output:
2
3. Multiplication *
x*y
Example:
x=5
y=3
print(x * y)
Output:
15
4. Division /
x/y
Example:
x = 12
y=3
print(x / y)
Output:
4
5. Modulus %
x%y
Example:
x=5
y=2
print(x % y)
Output:
1
6. Exponentiation **
x ** y
Example:
x=2
y=5
print(x ** y) #same as 2*2*2*2*2
Output:
32
7. Floor division //
x // y
Example:
x = 15
y=2
print(x // y) #the floor division rounds the result down to the nearest
whole number
Output:
7
Assignment operators:
Assignment operators are used to assign values to variables
1. Assign =
Example:
x=5
print(x)
Output:
5
Comparison operators:
Comparison operators are used to compare two values
1. Equal = =
Example:
x=5
y=3
print(x = = y)
# returns False because 5 is not equal to 3
Output
False
2. Not equal !=
Example:
x=5
y=3
print(x != y)
# returns True because 5 is not equal to 3
Output
True
Logical operators:
Logical operators are used to combine conditional statements
1. And
Returns True if both statements are true
Example:
x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10
Output
True
2. Or
Returns True if one of the statements is true
Example:
x=5
print(x > 3 or x < 4)
# returns True because one of the conditions are true (5 is greater than 3,
but 5 is not less than 4)
Output
True
3. Not
Reverse the result, returns False if the result is true
Example:
x=5
print(not(x > 3 and x < 10))
# returns False because not is used to reverse the result
Output
False
Identity operators:
1. Is
Returns True if both variables are the same object
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
# returns True because z is the same object as x
print(x is y)
# returns False because x is not the same object as y, even if they have the
same content
print(x = = y)
# to demonstrate the difference betweeen "is" and "= =": this comparison
returns True because x is equal to y
Output:
True
False
True
2. Is not
Returns True if both variables are not the same object
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is not z)
# returns False because z is the same object as x
print(x is not y)
# returns True because x is not the same object as y, even if they have the
same content
print(x != y)
# to demonstrate the difference betweeen "is not" and "!=": this
comparison returns False because x is equal to y
Output:
False
True
False
Membership operators:
1. In
Returns True if a sequence with the specified value is present in the object
Example:
x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list
Output:
True
2. Not in
Returns True if a sequence with the specified value is not present in the
object
Example:
x = ["apple", "banana"]
print("pineapple" not in x)
# returns True because a sequence with the value "pineapple" is not in the
list
Output:
True
Bitwise operators:
1. AND &
Sets each bit to 1 if both bits are 1
Example:
print(6 & 3)
# The & operator compares each bit and set it to 1 if both are 1, otherwise it
is set to 0:
6 = 0000000000000110
3 = 0000000000000011
2 = 0000000000000010
Output:
2
2. OR |
Sets each bit to 1 if one of two bits is 1
Example:
print(6 | 3)
# The | operator compares each bit and set it to 1 if one or both is 1,
otherwise it is set to 0:
6 = 0000000000000110
3 = 0000000000000011
7 = 0000000000000111
Output:
7
3. XOR ^
Sets each bit to 1 if only one of two bits is 1
Example:
print(6 ^ 3)
#The ^ operator compares each bit and set it to 1 if only one is 1, otherwise
(if both are 1 or both are 0) it is set to 0:
6 = 0000000000000110
3 = 0000000000000011
5 = 0000000000000101
Output:
5
4. NOT ~
Inverts all the bits
Example:
print(~3)
The ~ operator inverts each bit (0 becomes 1 and 1 becomes 0).
Inverted 3 becomes -4:
3 = 0000000000000011
-4 = 1111111111111100
Output:
-4
5. Zero fill left shift <<
Shift left by pushing zeros in from the right and let the leftmost bits fall off
Example:
print(3 << 2)
#The << operator inserts the specified number of 0's (in this case 2) from the
right and let the same amount of leftmost bits fall off:
If you push 00 in from the left:
3 = 0000000000000011
becomes
12 = 0000000000001100
Output:
12
Expressions in Python-
1. e = (a + b) * c / d
(a + b) = 30
30 * c = 30 * 15 = 450
450 / d = 450 / 5 = 90.0
e = 90.0
2. e = ((a + b) * c) / d
(a + b) = 30
30 * c = 450
450 / 5 = 90.0
e = 90.0
3. e = (a + b) * (c / d)
(a + b) = 30
(c / d) = 15 / 5 = 3.0
30 * 3.0 = 90.0
e = 90.0
4. e = a + (b * c) / d
(b * c) = 10 * 15 = 150
150 / d = 150 / 5 = 30.0
a + 30.0 = 20 + 30.0 = 50.0
e = 50.0
Statement in Python?
A statement in Python is a single line of code that instructs the Python
interpreter to perform an action.
Every line you write in Python (like assigning a value, printing, looping, etc.) is
considered a statement.
Types of Statements in Python with Examples
Assignment Statement- Assigns a value to a variable.
x = 10
name = "Alice"
Print Statement- Displays output.
print("Hello, World!")
Conditional Statement- Controls the flow of execution based on conditions.
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
Looping Statement- Executes a block of code repeatedly.
for i in range(3):
print("Iteration:", i)
Import Statement- Used to include external modules or libraries.
import math
print(math.sqrt(25))
Function Definition Statement- Defines a reusable block of code.
def greet():
print("Hello from function!")
greet()