Python Programming- Module 1
Definition:
Python is a high level, dynamically type, platform independent, object oriented and
interpretable programming language.
Importance/Features of python Programming:
Python's most important features are as follows:
• Easy to Learn
• Dynamically Typed
• Interpreter Based
• Multi-paradigm
• Standard Library
• Open Source and Cross Platform
• Database Connectivity
• Extensible
o Easy to Learn
This is one of the most important reasons for the popularity of Python.
Python has a limited set of keywords. Its features such as simple syntax,
usage of indentation to avoid clutter of curly brackets.
o Dynamically Typed
Python is a dynamically typed programming language. In Python, you don't
need to specify the variable time at the time of the variable declaration. The
types are specified at the runtime based on the assigned value due to its
dynamically typed feature.
o Interpreter Based
Python is an interpreter-based language. The interpreter takes one instruction
from the source code at a time, translates it into machine code and executes it.
Instructions before the first occurrence of error are executed. With this feature,
it is easier to debug the program and thus proves useful for the beginner level
programmer to gain confidence gradually.
o Multi-paradigm
Python is a completely object-oriented language. Everything in a Python
program is an object. However, Python conveniently encapsulates its object
orientation to be used as an imperative or procedural language – such as C.
Python also provides certain functionality that resembles functional
programming.
o Standard Library
Python software is distributed with a standard library made of large number of
modules and packages.
Some of the Python's popular modules are:
• NumPy
• Pandas
• Matplotlib
• Math
o Open Source and Cross Platform
Python's standard distribution can be downloaded
from https://www.python.org/downloads/ without any restrictions. You can
download pre-compiled binaries for various operating system platforms. In
addition, the source code is also freely available, which is why it comes under
open source category.
o Database Connectivity
Almost any type of database can be used as a backend with the Python
application.
o Extensible
The term extensibility implies the ability to add new features or modify existing
features.
Applications of python programming:
Python is a general-purpose programming language known for its readability. It is
widely applied in various fields.
• In Data Science, Python libraries like Numpy, Pandas, and Matplotlib are
used for data analysis and visualization.
• Python frameworks like Django, and Pyramid, make the development and
deployment of Web Applications easy.
• This programming language also extends its applications to computer
vision and image processing.
• It is also favoured in many tasks like Automation, Job Scheduling, GUI
development, etc.
Methods to Run Python:
1. Interactive Mode: Python's interactive shell (REPL - Read-
Evaluate-Print Loop) allows users to execute Python commands
one by one. It is ideal for testing small snippets of code or learning
purposes. Example:
2. Script Mode: In this mode, Python code is written in a file (with a
.py extension) and executed as a whole. This method is used for
larger programs. To run a script, the command python filename.py
is used.
3. IDLE: Python's Integrated Development and Learning
Environment (IDLE) is a simple IDE that comes bundled with
Python. It has an interactive shell, an editor, and debugging tools.
4. Jupyter Notebooks: Popular in data science, Jupyter Notebooks
allow you to run Python code in an interactive notebook interface
where code, results, and annotations are combined.
5. Python IDEs: Integrated Development Environments (IDEs)
such as PyCharm, Visual Studio Code, and Spyder provide
enhanced features like auto-completion, debugging, and project
management.
What is IDLE?
IDLE (Integrated Development and Learning Environment) is a simple and user-
friendly IDE (Integrated Development Environment) that comes packaged with
Python. It is specifically designed to provide a basic development environment for
Python programming, particularly for beginners or those who need a lightweight
environment for quick testing and learning.
Comments, Indentation, Identifiers, Keywords,
Variables
Comments:
• Comments are non-executable lines that provide explanations or notes for
programmers. They improve the readability and maintainability of code.
Python supports single-line and multi-line comments.
• Single-line comment: Begins with #.
• Multi-line comment: Can be written using triple single or double quotes ('''
or """), though these are technically treated as string literals.
Indentation:
• Python uses indentation (whitespace) to define the structure of code blocks,
such as loops, conditionals, and functions. Unlike many other programming
languages that use braces ({}), Python relies on indentation to signify block
levels. This enforces clean and readable code.
Example:
if x > 0:
print("Positive")
else:
print("Negative")
Identifiers:
• Identifiers are the names used to identify variables, functions, classes,
modules, etc. They must follow certain rules:
o Can start with a letter (A-Z or a-z) or an underscore (_), but not a
number.
o Cannot contain spaces or special characters (except _).
o Python is case-sensitive, meaning variable and Variable are distinct.
Example: my_var = 10
Keywords:
• Keywords are reserved words that have predefined meanings in Python.
They cannot be used as identifiers (variable names, function names). Python
has 35 keywords in version 3.x, such as if, else, while, for, True, False, def,
etc.
Example:
if x > 5:
print("x is greater than 5")
Variables:
• A variable is a storage location paired with an associated symbolic name
(identifier), which contains some known or unknown quantity of information
referred to as a value.
• In Python, variables are dynamically typed, meaning their type is assigned
based on the value they hold. Variables do not need explicit declaration,
making Python more flexible.
Example:
name = "John" # String variable
age = 25 # Integer variable
Python Data Types
o Data types are used to define the type of a variable. It represents the type of
data we are going to store in a variable and determines what operations can
be done on it.
o Since Python is dynamically typed, the data type of a variable is determined
at runtime based on the assigned value.
Types of Data Types in Python
Getting the Data Type:
o You can get the data type of any object by using the type() function:
x=5
print(type(x))
Output:
<class 'int'>
Setting the Data Type:
o In Python, the data type is set when you assign a value to a variable:
Input/Output Functions, Import Functions, Range Function
Input Functions:
• Python provides the input() function to take user input from the console. The
input is returned as a string, which can be cast to other types (e.g., int, float)
if needed.
• Example:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
Output Functions:
• The print() function is used to output data to the console. It can take multiple
arguments, separated by commas, and outputs them on the same line.
Example:
print("Hello", name)
Import Functions:
• Python allows the inclusion of external modules using the import statement.
Standard libraries like math, os, and random provide additional
functionality.
• Example:
import math
print(math.sqrt(16)) # Outputs: 4.0
Range Function:
• The range() function generates a sequence of numbers, often used in loops.
It can take one, two, or three arguments (start, stop, and step).
• Example:
for i in range(5):
print(i) # Outputs: 0, 1, 2, 3, 4
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
1. Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:
2. Python Assignment Operators
Assignment operators are used to assign values to variables:
3. Python Comparison Operators
Comparison operators are used to compare two values:
4. Python Logical Operators
Logical operators are used to combine conditional statements:
5. Python Identity Operators
identity operators are used to compare the objects, not if they are equal, but if they
are actually the same object, with the same memory location:
6. Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
7. Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Precedence and Associativity in Python
o Precedence of Python Operators
This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.
10 + 20 * 30 is calculated as 10 + (20 * 30)
and not as (10 + 20) * 30
o Precedence of Logical Operators in Python
In the given code, the ‘if‘ block is executed even if the age is 0. Because the
precedence of logical ‘and‘ is greater than the logical ‘or‘.
# Precedence of 'or' & 'and'
name = "Alex"
age = 0
if name == "Alex" or name == "John" and age >= 2:
print("Hello! Welcome.")
else:
print("Good Bye!!")
Output:
Hello! Welcome.
Associativity of Python Operators
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.
# Left-right associativity
# 100 / 10 * 10 is calculated as
# (100 / 10) * 10 and not
# as 100 / (10 * 10)
print(100 / 10 * 10)
# Left-right associativity
# 5 - 2 + 3 is calculated as
# (5 - 2) + 3 and not
# as 5 - (2 + 3)
print(5 - 2 + 3)
# left-right associativity
print(5 - (2 + 3))
# right-left associativity
# 2 ** 3 ** 2 is calculated as
# 2 ** (3 ** 2) and not
# as (2 ** 3) ** 2
print(2 ** 3 ** 2)
Output:
100
6
0
512
eval() Function
The eval() function in Python takes a string as input and evaluates it as a Python
expression. It interprets the string as code, executes it, and returns the result.
expression = "2 + 3 * 5"
result = eval(expression)
print(result) # Output: 17
Type Conversion, Multiple Assignment
Type Conversion:
• Python allows for explicit type conversion using built-in functions such as
int(), float(), and str(). This is useful when converting between types to
perform certain operations.
• Example:
num_str = "25"
num_int = int(num_str) # Converts string "25" to integer 25
Implicit type conversion (type coercion) happens automatically in Python
during operations. For example, adding an integer and a float results in a
float.
Example:
result = 5 + 3.0 # result = 8.0 (implicit conversion to float)
Multiple Assignment:
• Python supports assigning multiple variables in a single line using a comma-
separated list of variables and values. This enhances code readability and
conciseness.
• Example:
x, y, z = 10, 20, 30 # Assigns 10 to x, 20 to y, and 30 to z
Expressions and Boolean Expressions
Expressions:
• An expression is a combination of values, variables, operators, and function
calls that evaluates to a single result. Python supports a wide range of
expressions, including arithmetic, logical, and comparison expressions.
Example:
result = (3 + 5) * 2 # result = 16
Python follows the standard precedence and associativity rules for
evaluating expressions. Parentheses can be used to explicitly specify the
order of evaluation.
Boolean Expressions:
• A Boolean expression evaluates to either True or False. Boolean expressions
are commonly used in conditional statements, loops, and logical operations.
Example:
is_valid = (x > 5) and (y < 10) # Evaluates to True if both conditions are
met
• Logical Operators (and, or, not) are used to combine multiple conditions in a
Boolean expression.
Example:
if x > 0 and y > 0:
print("Both are positive")
The print() Function
o Python's print() function is a built-in function. It is the most frequently used
function, that displays value of Python expression given in parenthesis, on
Python's console.
print ("Hello World ")
Decision Making in Python
1. If Statement
The if statement is used to test a condition. If the condition evaluates to True, the
block of code within the if statement is executed.
Syntax:
if condition:
# code block to be executed if condition is True
Example:
num = 15
if num > 10:
print("The number is greater than 10")
2. If…Else Statement
The if...else statement provides a secondary path of execution if the condition in
the if statement evaluates to False.
Syntax:
if condition:
# code block if condition is True
else:
# code block if condition is False
Example:
num = 4
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
3. If…Elif…Else Statement
If you have multiple conditions to check, the elif statement can be used to chain
multiple if statements together.
Syntax:
if condition1:
# code block if condition1 is True
elif condition2:
# code block if condition2 is True
else:
# code block if neither condition is True
Example:
num = 15
if num > 20:
print("The number is greater than 20")
elif num > 10:
print("The number is greater than 10 but less than or equal to 20")
else:
print("The number is less than or equal to 10")
4. Nested If Statements
Python allows the nesting of if statements, meaning that you can place an if
statement inside another if statement.
Example:
age = 18
if age >= 10:
if age < 18:
print("Teenager")
else:
print("Adult")
Loops in Python
1. For Loop
A for loop is used for iterating over a sequence (e.g., list, tuple, string, or range).
Syntax:
for variable in sequence:
# code block
Example:
for i in range(5):
print(i)
2. For Loop with Else
An else block can be attached to a for loop. The else block is executed when the
loop terminates normally, without encountering a break.
Example:
for i in range(5):
print(i)
else:
print("Loop completed")
3. While Loop
A while loop continues to execute a block of code as long as the condition is True.
Syntax:
while condition:
# code block
Example:
i=1
while i <= 5:
print(i)
i += 1
4. While Loop with Else
Just like the for loop, a while loop can have an else block. The else block will be
executed when the loop terminates normally.
Example:
i=1
while i <= 5:
print(i)
i += 1
else:
print("Loop completed")
5. Nested Loops
You can nest a loop within another loop. For each iteration of the outer loop, the
inner loop will be executed completely.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(f"i = {i}, j = {j}")
Control Statements in Python
1. Break Statement
The break statement is used to exit the loop prematurely, i.e., before the loop
condition becomes False.
Example:
for i in range(10):
if i == 5:
break
print(i)
2. Continue Statement
The continue statement skips the current iteration of the loop and moves to the next
iteration.
Example:
for i in range(10):
if i % 2 == 0:
continue
print(i)
3. Pass Statement
The pass statement is a null operation; nothing happens when it is executed. It is
used as a placeholder when a statement is syntactically required but you don't want
to write any code yet.
Example:
if True:
pass # Do nothing here
else:
print("This won't execute")
Common Questions from the Topics:
Checking if a Number is Greater than 10:
num = int(input("Enter a number: "))
if num > 10:
print("The number is greater than 10")
else:
print("The number is not greater than 10")
Checking if a Number is Odd or Even:
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Checking Multiple Conditions with Logical Operators:
num = int(input("Enter a number: "))
if num > 10 and num < 20:
print("The number is between 10 and 20")
elif num > 20 or num < 5:
print("The number is either greater than 20 or less than 5")
Checking if a Number is Divisible by Both 2 and 3:
num = int(input("Enter a number: "))
if num % 2 == 0 and num % 3 == 0:
print("The number is divisible by both 2 and 3")
else:
print("The number is not divisible by both 2 and 3")
What Happens if There is No Else Block and Condition is False?
If there is no else block and the condition in the if statement is False, the program
will simply not execute any code inside the if block, and it will move on to the next
part of the program.
Using Break to Exit a Loop:
for i in range(10):
if i == 5:
break
print(i)
Using Continue to Skip Iterations (Print Even Numbers):
for i in range(1, 11):
if i % 2 != 0:
continue
print(i)
Using Both Break and Continue in a Single Loop:
for i in range(10):
if i == 2:
continue # Skip when i is 2
if i == 7:
break # Stop when i is 7
print(i)
Skipping Negative Numbers in a List:
numbers = [-3, 2, -1, 4, 5]
for num in numbers:
if num < 0:
continue
print(num)
For Loop Condition Always True or Never True:
If the condition in a for loop is always True, the loop runs indefinitely. For
example, looping over an infinite iterator would cause this.
If the condition is never True, the loop will not execute even once.