Python Programming Unit i
Python Programming Unit i
UNIT-1
INTRODUCTION TO PYTHON
Key Concepts
Interpreted Language: Python code runs on an interpreter system, allowing for quick
prototyping and immediate execution.
Dynamic Typing: You don't need to declare variable types explicitly; Python tracks the
types of values at runtime.
Extensive Libraries: Python has a vast standard library and a large ecosystem of third-
party packages (available through the Python Package Index (PyPI)) for a wide range of
applications.
Control Flow:
o Conditional Statements: Use if , elif (else if), and else to make decisions in your
code based on whether a condition is true or false.
o Loops: Use for and while loops to repeat a block of code multiple times.
Functions: Reusable blocks of code that perform a specific task, defined using
the def keyword. They help organize code and improve efficiency.
Data Structures: Python offers built-in data structures for grouping related values:
You can run Python code using the command line/terminal, an Integrated
Development Environment (IDE), or an online environment.
3. Navigate to your file's directory: Use the cd (change directory) command to go to the
folder where you saved your Python file (e.g., cd Documents/pyscripts ).
4. Run the script: Type the appropriate command followed by your filename:
1. Install Python: As above, you must have the Python interpreter installed on your
system.
3. Install the Python Extension: In editors like VS Code, install the official Python
extension from the marketplace.
1. Most IDEs have a "Run" button (often a green play icon ▶) in the top bar
or a "Run Module" option in the menus (like pressing F5 in IDLE or Visual
Studio).
2. Alternatively, you can right-click in the editor window and select Run
Python File in Terminal.
Click the "Run" button to execute your code and see the output immediately in the
console area.
IDENTIFIERS:
DEF:
In Python, an identifier is a user-defined name used to identify a variable, function, class, module, or
other object. Identifiers are essential for writing readable and maintainable code, as they allow
you to refer to specific entities within a program.
Cannot Start with a Digit: An identifier must begin with a letter or an underscore. For
example, total_marks is valid, but 1st_place is not.
Length: There is no length limit imposed by the language itself; however, following
the PEP 8 style guide suggests keeping lines (and names) to a reasonable length for
readability.
Objects: s1 = Student()
Example:
import keyword
print("student_name".isidentifier()) # True
else - Used in conditional and loop statements to define a block of code to run when
conditions are not met
finally - Defines a block of code that will be executed no matter what in exception
handling
is - Identity operator, checks if two variables are the same object in memory
or - Logical operator
Key Characteristics
Case Sensitivity: Python keywords are case-sensitive. For example, False is a
keyword, but false is not.
Cannot be Identifiers: You will get a SyntaxError if you try to use a keyword as a
variable or function name.
Built-in Functions: Words like list , dict , and print are built-in functions, not
keywords, but you should still avoid using them as variable names to prevent issues
(known as "shadowing").
You can view a list of all keywords in your current Python environment by using
the keyword module in the console:
python
import keyword
print([Link])
VARIABLES:
DEFINITION:
In Python, a variable is a symbolic name (or label) that acts as a reference to an object or value stored
in memory. Unlike some other programming languages, Python is dynamically typed, meaning
you do not need to explicitly declare the variable's data type; it is automatically determined by
the value you assign to it.
Key Concepts
Assignment: Variables are created using the assignment operator ( = ). The value on
the right is assigned to the variable name on the left.
python
# Examples of variable assignment
name = "Alice" # A string variable
age = 30 # An integer variable
height = 5.9 # A float variable
is_student = True # A boolean variable
Dynamic Typing: A variable's type can change after it has been set by simply
assigning a new value of a different type.
python
data = 100 # data is now an integer
data = "hello" # data is now a string
Object References: Variables in Python hold references to objects, not the objects
themselves. Assigning one variable to another makes both variables refer to the same
object in memory.
Case Sensitivity: Variable names are case-sensitive. age and Age are two different
variables.
Names can only contain alphanumeric characters and underscores ( A-z , 0-9 , and _ ).
Best Practice (PEP 8 convention): Use snake_case (all lowercase words separated
by underscores) for variable names to improve code readability.
Multiple Assignment
Python allows you to assign values to multiple variables in a single line:
Multiple values to multiple variables:
python
x, y, z = "Orange", "Banana", "Cherry"
One value to multiple variables:
python
x = y = z = "Orange”
COMMENTS IN PYTHON:
DEFINITION:
In Python, comments are used to explain code and are ignored by the interpreter during
execution. There are two primary ways to create comments:
Single-line comments: Start with a hash symbol ( # ). Anything after the # on the same
line is considered a comment.
python
# This is a single-line comment
x = 10 # This is an inline comment
Multi-line comments: Python does not have a dedicated syntax for multi-line
comments like other languages (e.g., /* */ in C). The recommended way to create
block comments is by placing a hash symbol at the beginning of each line.
python
# This is the first line of a multi-line comment
# This is the second line
# And so on
Alternatively, unassigned triple-quoted strings ( """ or ''' ) can serve a similar purpose
because they are ignored by the interpreter if not assigned to a variable.
python
"""
This string literal is not assigned to a variable,
so it functions as a multi-line comment.
"""
Best Practices
Explain "Why," Not "What": Good comments explain the reasoning or intent behind a
piece of code, rather than simply restating what the code does.
Keep them updated: Outdated comments can be worse than no comments, leading to
confusion.
Use Sparingly: Strive to write self-explanatory code and use comments only when the
logic is complex or non-obvious.
Use Shortcuts: Most IDEs and editors offer keyboard shortcuts (commonly Ctrl
+ / or Cmd + / ) to quickly comment out or uncomment blocks of code.
INDENTATION IN PYTHON:
DEFINITION:
In Python, indentation is mandatory and defines code blocks, unlike most other languages
where it is merely a matter of style for readability. The Python interpreter uses the
amount of leading whitespace to determine the grouping and hierarchy of statements
within structures like loops, conditionals, functions, and classes.
Consistency: All statements within the same block must have the same level of
indentation.
Spaces over Tabs: The Python community prefers spaces over tabs. Mixing tabs and
spaces in the same file can cause errors.
Start at Zero: The first line of Python code should not be indented.
Example
The following example demonstrates how indentation defines the scope of
the if and else blocks:
python
age = 18
if age >= 18:
print("You are an adult.") # Indented, part of the if block
else:
print("You are a minor.") # Indented, part of the else block
print("Done.") # Not indented, outside both blocks
MULTI LINE COMMENTS:
DEFINITION:
Multi-line comments are used to add explanatory text or temporarily disable large blocks of
code across multiple lines. The syntax for these comments varies depending on the
programming language.
Common Multi-Line Comment Syntaxes
Language Syntax Source(s)
Go /* ... */
SQL /* ... */
Debugging: They are useful for temporarily disabling sections of code during testing
and debugging.
IDE Support: Most modern Integrated Development Environments (IDEs) and text
editors provide a keyboard shortcut (commonly Ctrl + / or Cmd + / ) to automatically
comment out or uncomment a selected block of code, which often uses the single-line
comment syntax for each line.
Clarity: Use comments to explain complex logic or the "why" behind your code, rather
than simply restating the "what".
For example, a def function definition requires a suite to define its body:
python
def my_function():
print("Hello") # Suite starts
return True
QUOTES IN PYTHON:
DEFINITION
In Python, strings can be enclosed using single quotes ( ' ' ), double quotes ( " " ),
or triple quotes ( ''' ''' or """ """ ). All three types function identically for defining a string
and are primarily a matter of style and convenience.
Standard Quotes (Single and Double)
Single and double quotes can be used interchangeably to define standard, single-line
strings.
The primary reason for having both is to easily include one type of quote within a string
without using escape characters.
python
python
python
Multi-line strings:
python
paragraph = """
This is a multi-line string.
It spans across several lines
and retains its formatting."""
print(paragraph)
Docstrings: Triple quotes are the standard and recommended way for writing
documentation strings (docstrings) for modules, classes, methods, and functions, as
specified in PEP 257. The convention is to use triple double quotes ( """ """) for
docstrings.
INPUT IN PYTHON
In Python, the built-in input() function is used to take user input from the keyboard. This
function pauses the program's execution and waits for the user to type something and
press Enter.
Basic Usage
The most straightforward way to use input() is by assigning the result to a variable:
python
user_response = input("Enter your name: ")
print("Hello,", user_response)
"Enter your name: " : This is an optional prompt message displayed to the user to guide
them on what to enter.
user_response : The value the user enters (e.g., "John") is stored in this variable.
Handling Different Data Types
By default, the input() function always returns the input as a string ( str ). To use the input
as a number (for calculations, for example), you must convert it using type
casting functions like int() or float() :
Integer Input:
python
python
python
# For string inputsfirst_name, last_name = input("Enter your first and last
name: ").split()
print("First name:", first_name)
print("Last name:", last_name)
# For integer inputs, use `map()` with `split()`x, y = map(int, input("Enter
two numbers (separated by a space): ").split())
print("The sum is:", x + y)
The map() function applies the int() conversion to each item in the split list.
OUTPUT IN PYTHON
DEFINITION:
In Python, the primary way to produce output is using the built-in print() function. This
function displays text, variables, and expressions to the console (standard output).
python
python
name = "Alice"age = 30
print("Name:", name, "Age:", age)# Output: Name: Alice Age: 30
By default, multiple items separated by commas within the print() function are
automatically separated by a single space in the output.
Printing numbers and expressions:
python
The print() function allows for custom formatting using specific arguments:
Formatted string literals (f-strings) provide a concise way to embed expressions inside
string literals for output.
IMPORT FUNCTIONS:
In Python, importing functions allows you to reuse code from other files
(modules) or built-in libraries.
import math
result = [Link](16)
print(result)
result = sqrt(16)
print(result)
✔ No need to write math. before the function.
print(sqrt(25))
print(pow(2, 3))
⚠ This can cause naming conflicts and makes code harder to read.
Module Alias:
import math as m
print([Link](36))
Function Alias:
print(square_root(49))
[Link]
def greet(name):
return f"Hello {name}"
print(greet("Alice"))
Both files must be in the same folder (or properly structured package).
import numpy as np
Quick Summary
Syntax Meaning
import module Import whole module
from module import function Import specific function
import module as alias Import with nickname
from module import * Import everything (avoid)
OPERATORS IN PYTHON
In Python programming, Operators in general are used to perform operations on
values and variables.
Operators: Special symbols like -, + , * , /, etc.
Operands: Value on which the operator is applied.
Types of Operators in Python
Arithmetic Operator:
An arithmetic operator is a symbol used to perform mathematical calculations on numbers.
Operat
Name Definition
or
EXAMPLE:
+ (Addition)
Definition: Adds two values.
Example: 5 + 3 → 8
- (Subtraction)
* (Multiplication)
/ (Division)
// (Floor Division)
% (Modulus)
** (Exponent)
equal
Greater than or
>= True if left is greater or equal
equal
== (Equal to)
Bitwise Operators
Python Bitwise operators act on bits and perform bit-by-bit operations. These are
used to operate on binary numbers.
Bitwise Operators in Python are as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
EXAMPLE:
a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)
Output
0
14
-11
14
2
40
Assignment Operators
Python Assignment operators are used to assign values to the variables. This
operator is used to assign the value of the right side of the expression to the left
side operand.
Example
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
Output
10
20
10
100
102400
Identity Operators
In Python, is and is not are the identity operators both are used to check if two
values are located on the same part of the memory. Two variables that are equal do
not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
EXAMPLE:
a = 10
b = 20
c=a
print(a is not b)
print(a is c)
Output
True
True
Membership Operators
In Python, in and not in are the membership operators that are used to test whether
a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
EXAMPLE:
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Output
x is NOT present in given list
y is present in given list
Ternary Operator
in Python, Ternary operators also known as conditional expressions are operators
that evaluate something based on a condition being true or false. It was added to
Python in version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-else,
making the code compact.
Syntax : [on_true] if [expression] else [on_false]
EXAMPLE:
a, b = 10, 20
min = a if a < b else b
print(min)
Output
10
Operator Precedence
This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.
EXAMPLE:
expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0
if name == "Alex" or name == "John" and age >= 2:
print("Hello! Welcome.")
else:
print("Good Bye!!")
Output
610
Hello! Welcome.
Operator Associativity
If an expression contains two or more operators with the same precedence then
Operator Associativity is used to determine. It can either be Left to Right or from
Right to Left.
EXAMPLE:
print(100 / 10 * 10)
print(5 - 2 + 3)
print(5 - (2 + 3))
print(2 ** 3 ** 2)
Output
100.0
6
0
512
1️⃣Integer (int)
Definition:
An integer is a whole number (positive, negative, or zero) without decimals.
Example:
x = 10
y = -5
print(type(x)) # <class 'int'>
OPERATIONS:
print(x + y) # Addition → 13
print(x - y) # Subtraction → 7
print(x * y) # Multiplication → 30
print(x / y) # Division → 3.3333
print(x // y) # Floor division → 3
print(x % y) # Modulus → 1
print(x ** y) # Exponent → 1000
2️⃣Float (float)
Definition:
A float is a number with a decimal point.
Example:
pi = 3.14
price = 99.99
print(type(pi)) # <class 'float'>
OPERATIONS:
print(a + b) # 7.5
print(a - b) # 3.5
print(a * b) # 11.0
print(a / b) # 2.75
3️⃣Complex (complex)
Definition:
A complex number has a real part and an imaginary part (written with j).
Example:
z = 2 + 3j
print(type(z)) # <class 'complex'>
OPERATIONS:
4️⃣String (str)
Definition:
A string is a sequence of characters enclosed in quotes.
Example:
name = "Python"
message = 'Hello'
print(type(name)) # <class 'str'>
OPERATIONS:
print([Link]()) # "PYTHON"
print([Link]()) # "python"
print(name[0]) # 'P' (indexing)
print(name[0:4]) # 'Pyth' (slicing)
print(name + "3") # "Python3" (concatenation)
print(name * 2) # "PythonPython" (repetition)
5️⃣List (list)
Definition:
A list is an ordered and changeable collection of elements.
Example:
numbers = [1, 2, 3, 4]
[Link](5)
print(numbers) # [1, 2, 3, 4, 5]
OPERATIONS:
[Link](5) # [1, 2, 3, 4, 5]
[Link](2) # [1, 3, 4, 5]
print(numbers[0]) #1
print(numbers[1:3]) # [3, 4]
len(numbers) #4
6️⃣Tuple (tuple)
Definition:
A tuple is an ordered but unchangeable collection of elements.
Example:
OPERATIONS:
print(point[0]) # 10
print(point[1:3]) # (20, 30)
len(point) #3
# Cannot add or remove elements (immutable)
7️⃣Dictionary (dict)
Definition:
A dictionary stores data in key–value pairs.
Example:
OPERATIONS:
print(student["name"]) # John
student["age"] = 21 # Update value
student["grade"] = "A" # Add key
print([Link]()) # dict_keys(['name','age','grade'])
print([Link]()) # dict_values(['John',21,'A'])
8️⃣Set (set)
Definition:
A set is an unordered collection of unique elements.
Example:
s = {1, 2, 3, 3}
OPERATIONS:
print(s) # {1, 2, 3}
[Link](4) # {1,2,3,4}
[Link](2) # {1,3,4}
print([Link]({5,6})) # {1,3,4,5,6}
print([Link]({3,4,7})) # {3,4}
9️⃣Boolean (bool)
Definition:
A boolean represents one of two values: True or False.
Example:
is_valid = True
print(type(is_valid)) # <class 'bool'>
OPERATIONS:
Then we added these two variables and stored the result in new_number .
EXAMPLE:
integer_number = 123
float_number = 1.23
print("Value:",new_number)
print("Data Type:",type(new_number))
OUTPUT:
Value: 124.23
Then we added these two variables and stored the result in new_number .
Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to
required data type.
We use the built-in functions like int(), float(), str(), etc to perform explicit type
conversion.
This type of conversion is also called typecasting because the user casts
(changes) the data type of the objects.
num_integer = 23
num_string = int(num_string)
print("Sum:",num_sum)
Sum: 35
If Conditional Statement
Eligible to vote.
If Else allows us to specify a block of code that will execute if the condition(s)
associated with an if or elif statement evaluates to False. Else block provides a
way to handle all other cases that don't meet the specified conditions.
Example:
age = 10
if age <= 12:
else:
Output
Travel for free.
elif Statement
elif statement in Python stands for "else if." It allows us to check multiple
conditions, providing a way to execute different blocks of code based on which
condition is true. Using elif statements makes our code more readable and
efficient by eliminating the need for multiple nested if statements.
Example:
age = 25
if age <= 12:
print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")
Output
Young adult.
The code checks the value of age using if-elif-else. Since age is 25, it skips the
first two conditions (age <= 12 and age <= 19), and the third condition (age <=
35) is True, so it prints "Young adult.".
Nested if..else means an if-else statement inside another if statement. We can use
nested if statements to check conditions within conditions.
Example:
age = 70
is_member = True
if age >= 60:
if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")
Output
Output
Adult
Here:
If age >= 18 is True, status is assigned "Adult".
Otherwise, status is assigned "Minor".
Match-Case Statement
match-case statement is Python's version of a switch-case found in other
languages. It allows us to match a variable's value against a set of patterns.
Example:
number = 2
match number:
case 1:
print("One")
case 2 | 3:
print("Two or Three")
case _:
print("Other number")
Output:
Two or Three
Loops in Python
Loops in Python are used to repeat actions efficiently. The main types are For loops
(counting through items) and While loops (based on conditions).
For Loop
For loops is used to iterate over a sequence such as a list, tuple, string or range. It
allow to execute a block of code repeatedly, once for each item in the sequenc e
Example:
n = 4
print(i)
Output
0
1
2
3
Explanation: This code prints the numbers from 0 to 3 (inclusive) using a for
loop that iterates over a range from 0 to n-1 (where n = 4).
Example:
li = ["geeks", "for", "geeks"]
for x in li:
print(x)
tup = ("geeks", "for", "geeks")
for x in tup:
print(x)
s = "abc"
for x in s:
print(x)
d = dict({'x':123, 'y':354})
for x in d:
print("%s %d" % (x, d[x]))
Iterating by Index of Sequences
We can also use the index of elements in the sequence to iterate. The key idea is
to first calculate the length of the list and then iterate over the sequence within the
range of this length.
li = ["geeks", "for", "geeks"]
for index in range(len(li)):
print(li[index])
Output
geeks
for
geeks
Explanation: This code iterates through each element of the list using its index
and prints each element one by one. The range(len(list)) generates indices from 0
to the length of the list minus 1.
While Loop
In Python, a while loop is used to execute a block of statements repeatedly until a
given condition is satisfied. When the condition becomes false, the line
immediately after the loop in the program is executed.
In below code, loop runs as long as the condition cnt < 3 is true. It increments the
counter by 1 on each iteration and prints "Hello Geek" three times.
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Geek")
Output
Hello Geek
Hello Geek
Hello Geek
set1 = {10, 30, 20}
for x in set1:
print(x),
Output:
geeks
for
geeks
geeks
for
geeks
a
b
c
x 123
y 354
10
20
30
Nested Loops
Python programming language allows to use one loop inside another loop which
is called nested loop. Following example illustrates the concept.
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output
1
22
333
4444
Explanation: In the above code we use nested loops to print the value of i
multiple times in each row, where the number of times it prints i increases with
each iteration of the outer loop. The print() function prints the value of i and
moves to the next line after each row.
A final note on loop nesting is that we can put any type of loop inside of any
other type of loops in Python. For example, a for loop can be inside a while loop
or vice versa.
Continue Statement
The continue statement in Python returns the control to the beginning of the loop.
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
Output
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Explanation: The continue statement is used to skip the current iteration of a
loop and move to the next iteration. It is useful when we want to bypass certain
conditions without terminating the loop.
Break Statement
The break statement in Python brings control out of the loop.
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
break
Output
Current Letter : e
Explanation: break statement is used to exit the loop prematurely when a
specified condition is met. In this example, the loop breaks when the letter is
either 'e' or 's', stopping further iteration.
Pass Statement
We use pass statement in Python to write empty loops. Pass is also used for
empty control statements, functions and classes.
for letter in 'geeksforgeeks':
pass
print('Last Letter :', letter)
Output
Last Letter : s
Explanation: In this example, the loop iterates over each letter in 'geeksforgeeks'
but doesn't perform any operation, and after the loop finishes, the last letter ('s') is
printed.