Python Programming Module 1
Python Programming Module 1
Definition:
Python is a high level, dynamically type, platform independent, object oriented and
interpretable programming language.
• 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
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
o Standard Library
• NumPy
• Pandas
• Matplotlib
• Math
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.
• 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.
What is IDLE?
Comments:
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:
Keywords:
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:
o You can get the data type of any object by using the type() function:
x=5
print(type(x))
Output:
<class 'int'>
o In Python, the data type is set when you assign a value to a variable:
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:
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:
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
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:
This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.
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
Output:
Hello! Welcome.
# 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.
• 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
Example:
Multiple Assignment:
Boolean Expressions:
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:
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:
Example:
for i in range(5):
print(i)
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
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:
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")
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)
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)
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.