0% found this document useful (0 votes)
0 views76 pages

Unit 1 Python Programming

The document provides a comprehensive overview of the Python programming language, including its history, key features, and fundamental concepts such as identifiers, keywords, data types, control flow statements, and operators. It emphasizes Python's versatility in various fields like web development and machine learning, as well as its dynamic typing and object-oriented nature. Additionally, it covers practical aspects like variable declaration, input/output functions, and operator precedence.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views76 pages

Unit 1 Python Programming

The document provides a comprehensive overview of the Python programming language, including its history, key features, and fundamental concepts such as identifiers, keywords, data types, control flow statements, and operators. It emphasizes Python's versatility in various fields like web development and machine learning, as well as its dynamic typing and object-oriented nature. Additionally, it covers practical aspects like variable declaration, input/output functions, and operator precedence.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 76

UNTI-I: History of Python Programming Language,

Thrust Areas of Python, Installing Anaconda Python


Distribution, Installing and Using Jupiter Notebook.
Parts of Python Programming Language:
Identifiers, Keywords, Statements and Expressions,
Variables, Operators, Precedence and Associativity,
Data Types, Indentation, Comments, Reading Input,
Print Output, Type Conversions, the type () Function
and Is Operator, Dynamic and Strongly Typed
Language.
Control Flow Statements: if statement, if-else
statement, if...elif…else, Nested if statement, while
Loop, for Loop, continue and break Statements,
Catching Exceptions Using try and except
Statement.

History of Python Programming Language:


Python is a widely used general-purpose, high-level
programming language. It was initially designed
by Guido van Rossum in 1991 and developed by Python
Software Foundation. It was mainly developed for
emphasis on code readability, and its syntax allows
programmers to express concepts in fewer lines of code.
Why the Name Python?
There is a fact behind choosing the
name Python. Guido van Rossum was reading the
script of a popular BBC comedy series "Monty
Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique,
sort, and little-bit mysterious. So he decided to select
naming Python after the "Monty Python's Flying
Circus" for their newly created programming
language.
 Python is also versatile and widely used in every
technical field, such as Machine Learning, Artificial
Intelligence, Web Development, Mobile
Application, Desktop Application, Scientific
Calculation, etc.
 Thrust Areas of Python
 Web Development. The programming language is
used in back-end logic of web applications. ...
 Artificial intelligence and machine learning. ...
 Embedded applications. ...
 Game development. Python is open
source: The Python implementation is under an
open source license that makes it freely usable
and distributable, even for commercial use.
 Python is interpreted: Python is a high level
language which is interpreted by a Python
interpreter.
 Python is cross platform compatible: Python
can be executed on all major platforms
like Windows, Linux/Unix, OS/2, Mac and
others.
 Python is Object-Oriented: In Python, we
encapsulate data within the objects as it supports
the object-oriented style of programming.
 Database connectivity: Python provides
interfaces required to connect to all major
databases like Oracle, MySQL, PostgreSQL and
others.
Identifiers:

In Python, variables, functions, classes, modules


and objects are identified using a name
known as an identifier. An identifier can start
with an uppercase or lowercase character or an
underscore (_) followed by any number of
underscores, letters and digits. All identifiers in
Python are case sensitive.
Example: weight=10
In the above example, weight is an identifier.
Keywords:
Keywords are the reserved words in
Python. So keywords cannot be used as identifiers
or to name variables and functions. Few of the
keywords are listed below.
Example: if, else, elif, for, where, break, continue
Declaring a variable:
Syntax: var_name = literal_value
where var_name is the name given to the container
holding the value specified as literal_value in the
syntax above.
Example: weight=10
In the above example, weight is the container
holding the value 10 which can change during the
execution of the program.
Python may have data belonging to different types.
Common data types used in programming are listed
below:
Category Datatype Example
int 123
Numeric
long 1237126381763817
Numeric with decimal float 123.45
point double 123123.32345324
char A
Alphanumeric
string Hello
Boolean boolean True, False

Python is a dynamically typed language!


In the above example, no datatype was mentioned
at the time of declaring variable. In Python, the
datatype of a variable is decided automatically at
the time of execution based on the value assigned
to it. This is called as dynamic typing.
Syntax
Var_name=65
Var="A"
Note: To check the datatype of the variable we can
use type(var_name) which in turn returns
the datatype of the variable.
Example:

1.num=65
2.print(num,type(num))
3.num="A"
4.print(num,type(num))))

Output:
65<class'int'>
A <class 'str'>
The input() function:
Python provides the input() built-in function to read
an input from the user using the standard input
device (i.e. keyboard). The input() function always
returns string data irrespective of the type of
data entered through the keyboard.
Syntax: var_name = input([“interactive statement”])
where,
var_name is the variable assigned with the string
value which is read using input method.
Interactive statement is the statement displayed to
the user expecting the response from them.
Example:

1.input_var=input("please enter the value")


2.print(input_var)

sample output:
please enter the value100
100
The print() function:
Python provides the print() built-in function to
display the output onto the standard output device
(i.e. Monitor)
Syntax: print(var_name1, var_name2)
where,
var_name1, var_name2 are the variable names or
the literals you want to print or output
Statements and Expressions:
Statements
A statement is an instruction that the Python
interpreter can execute. There are various types of
statements in Python, including:
1.Assignment Statement:
Example: x = 5 name = "Alice"
2. Control Flow Statements:
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
Loops:
 For Loop:
for i in range(5):
print(i)

While Loop:
while x > 0:
print(x)
x -= 1
 Function Definition:
def greet(name):
return f"Hello, {name}"
 Class Definition:
class Dog:
def __init__(self, name):
self.name = name

def bark(self):
return "Woof!"
 Import Statement:
import math
from datetime import datetime
 Exception Handling:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Expressions
An expression is a combination of values,
variables, operators, and calls to functions that the
interpreter evaluates and produces another value.
Expressions can be used wherever Python expects
a value
1.Arithmetic Expressions:
2+3*4-5 #
Results in 9
2.Boolean Expressions:
5 > 3 # True
x == 10 # Evaluates to True or False depending
on the value of x

3.String Expressions:

"Hello, " + "world!" # Results in "Hello,


world!"
4.Function Calls:
len("Python") # Results in 6
5.List Comprehensions:
[x * 2 for x in range(5)] # Results in [0, 2, 4, 6,
8]
6.Lambda Expressions:
(lambda x: x + 1)(5) # Results in 6
Combining Statements and Expressions
Statements can contain expressions, and expressions
can appear within statements.
For example:
x = 10 Assignment statement
y = x * 2 Assignment statement with an expression

if y > 15: Conditional statement with an expression


print("y is greater than 15") # Print statement
Understanding the difference between statements
and expressions is crucial for writing efficient and
readable Python code. Statements control the flow of
the program, while expressions compute values
Variables:
In Python, variables are used to store data values. A
variable is essentially a name that refers to a value.
Python is dynamically typed, which means that you
don't have to declare the type of a variable when you
create one. The type of the variable is determined by
the value assigned to it. Here's a detailed overview
of variables in Python:
Creating and Assigning Variables
To create a variable, you simply assign a value to a
name using the = operator.
Example:
x=5
name = "Alice"
is_active = True
Naming Rules and Conventions
1.Names can contain letters, digits, and
underscores (_).
user_name = "Alice"
user1 = "Bob"
2.Names must start with a letter or an
underscore.
_private_variable = "secret"
3.Names cannot start with a digit.
1user = "Alice" # This will cause a syntax error
4.Names are case-sensitive.
name = "Alice"
Name = "Bob"
5.Avoid using Python reserved keywords as
variable names.
for = 5 # This will cause a syntax error
Types of Variables
Python variables can hold different types of values,
and the type is determined at runtime. Here are some
common types:
1.Integer:
age = 30
2.Float:
price = 19.99
3.String:
name = "Alice"
4.Boolean:
is_active = True
5.List:
colors = ["red", "green", "blue"]
6.Tuple:
point = (10, 20)
7.Dictionary:
person = {"name": "Alice", "age": 30}
8.Set:
unique_numbers = {1, 2, 3, 4, 5}
Variable Scope
The scope of a variable determines where in the
code a variable can be accessed.
1.Local Scope: Variables created inside a function
belong to the local scope of that function and
can only be used inside that function.
def my_function():
x = 10 # Local scope
print(x)

my_function()
print(x) # This will cause an error because x
is not defined outside the function
2.Global Scope: Variables created outside of all
functions are in the global scope and can be used
anywhere in the code.
y = 20 # Global scope

def my_function():
print(y)

my_function()
print(y)
3.Global Keyword: To modify a global variable
inside a function, you can use the global
keyword.
z = 30

def my_function():
global z
z = 40

my_function()
print(z) # This will print 40
Variable Type Casting
Sometimes, you may need to convert a variable from
one type to another.
1.Integer to String:

x = 10
y = str(x) # y is now "10"
2.String to Integer:
a = "5"
b = int(a) # b is now 5
3.String to Float:
c = "3.14"
d = float(c) # d is now 3.14
4.Integer to Float:
e=7
f = float(e) # f is now 7.0
Understanding variables and how to use them
effectively is fundamental to programming in
Python. They allow you to store, manipulate, and
retrieve data in your programs.
Operators:
In Python, operators are special symbols or
keywords that are used to perform operations on
variables and values. Python provides a variety of
operators that can be categorized into several groups
based on their functionality:
1. Arithmetic Operators
These operators are used to perform mathematical
operations.
 Addition (+)
x=5
y=3
print(x + y) # Output: 8
 Subtraction (-)
print(x - y) # Output: 2
 Multiplication (*)
print(x * y) # Output: 15
 Division (/)
print(x / y) # Output: 1.6666666666666667
 Floor Division (//)
print(x // y) # Output: 1
 Modulus (%)
print(x % y) # Output: 2
 Exponentiation (**)
print(x ** y) # Output: 125
2. Comparison Operators
These operators are used to compare two values and
return a Boolean result (True or False).
 Equal to (==)
print(x == y) # Output: False
 Not equal to (!=)
print(x != y) # Output: True
 Greater than (>)
print(x > y) # Output: True
 Less than (<)
print(x < y) # Output: False
 Greater than or equal to (>=)
print(x >= y) # Output: True
 Less than or equal to (<=)
print(x <= y) # Output: False
3. Logical Operators
These operators are used to combine conditional
statements.
 AND (and)
print(x > 0 and y > 0) # Output: True
 OR (or)
print(x > 0 or y < 0) # Output: True
 NOT (not)
print(not(x > 0)) # Output: False
4. Assignment Operators
These operators are used to assign values to
variables.
 Assignment (=)
z = 10
 Add and assign (+=)
z += 5 # z is now 15
 Subtract and assign (-=)
z -= 3 # z is now 12
 Multiply and assign (*=)
z *= 2 # z is now 24
 Divide and assign (/=)
z /= 4 # z is now 6.0
 Floor divide and assign (//=)
z //= 2 # z is now 3.0
 Modulus and assign (%=)
z %= 2 # z is now 1.0
 Exponent and assign (**=)
z **= 3 # z is now 1.0
5. Bitwise Operators
These operators are used to perform operations on
binary numbers.
 AND (&)
print(5 & 3) # Output: 1 (binary: 101 & 011 =
001)
 OR (|)
print(5 | 3) # Output: 7 (binary: 101 | 011 = 111)
 XOR (^)
print(5 ^ 3) # Output: 6 (binary: 101 ^ 011 =
110)
 NOT (~)
print(~5) # Output: -6 (binary: ~101 = -110)
 Left Shift (<<)
print(5 << 1) # Output: 10 (binary: 101 << 1 =
1010)
 Right Shift (>>)
print(5 >> 1) # Output: 2 (binary: 101 >> 1 =
10)
6. Membership Operators
These operators are used to test if a sequence is
present in an object.
 IN (in)
list = [1, 2, 3, 4, 5]
print(3 in list) # Output: True
 NOT IN (not in)
print(6 not in list) # Output: True
7. Identity Operators
These operators are used to compare the memory
locations of two objects.
 IS (is)
a = [1, 2, 3]
b=a
print(a is b) # Output: True
 IS NOT (is not)
c = [1, 2, 3]
print(a is not c) # Output: True
Understanding and using these operators effectively
is crucial for performing various operations and
manipulating data in Python.
Precedence and Associativity:
In Python, operator precedence and associativity
determine the order in which operators are evaluated
in expressions.
Precedence
Operator precedence determines which operator is
evaluated first in an expression with multiple
operators. Operators with higher precedence are
evaluated before operators with lower precedence.
Here's a list of Python operators, grouped by
precedence from highest to lowest:
1.Exponentiation: **
2.Unary plus, unary minus, and bitwise NOT:
+, -, ~
3.Multiplication, division, floor division, and
modulus: *, /, //, %
4.Addition and subtraction: +, -
5.Bitwise shift operators: <<, >>
6.Bitwise AND: &
7.Bitwise XOR: ^
8.Bitwise OR: |
9.Comparisons, including membership and
identity tests: ==, !=, >, <, >=, <=, is, is not, in,
not in
10. Boolean NOT: not
11. Boolean AND: and
12. Boolean OR: or
Associativity
Associativity determines the order in which
operators of the same precedence are evaluated.
Most operators in Python are left-associative,
meaning they are evaluated from left to right. The
exponentiation operator (**) is right-associative,
meaning it is evaluated from right to left.
Left-Associative Operators (evaluated from left
to right)
 Multiplication, division, floor division, and
modulus (*, /, //, %)
 Addition and subtraction (+, -)
 Bitwise shift operators (<<, >>)
 Bitwise AND (&)
 Bitwise XOR (^)
 Bitwise OR (|)
 Comparisons (==, !=, >, <, >=, <=, is, is not, in,
not in)
 Boolean AND (and)
 Boolean OR (or)
Right-Associative Operators (evaluated from
right to left)
 Exponentiation (**)
 Unary plus, unary minus, and bitwise NOT (+, -,
~)
 Boolean NOT (not)
Examples
Example 1: Operator Precedence
x=2+3*4
print(x) ‘P # Output: 14
In this example, multiplication (*) has higher
precedence than addition (+), so 3 * 4 is evaluated
first, resulting in 12, and then 2 + 12 gives 14.
Example 2: Using Parentheses to Override
Precedence
x = (2 + 3) * 4
print(x) # Output: 20
Parentheses have the highest precedence, so 2 + 3 is
evaluated first, resulting in 5, and then 5 * 4 gives
20.
Example 3: Associativity
x = 2 ** 3 ** 2
print(x) # Output: 512
Exponentiation is right-associative, so 3 ** 2 is
evaluated first, resulting in 9, and then 2 ** 9 gives
512.
Example 4: Mixed Associativity
x=5-3+2
print(x) # Output: 4
Both subtraction and addition are left-associative
and have the same precedence. So, 5 - 3 is evaluated
first, resulting in 2, and then 2 + 2 gives 4.
Understanding operator precedence and associativity
is crucial for writing clear and correct Python code,
especially in complex expressions. When in doubt,
using parentheses to explicitly define the evaluation
order can help ensure your code behaves as
expected.
In Python, data types specify the type of value a
variable holds. Python has several built-in data types
that are used to handle different kinds of data. Here's
a comprehensive overview of the most common data
types in Python:
Basic Data Types
1.Integer (int):
o Whole numbers, positive or negative,

without decimals.
o Example:

python
Copy code
x = 10
y = -5
2.Float (float):
o Numbers, positive or negative, containing

one or more decimals.


o Example:

python
Copy code
pi = 3.14
gravity = 9.81
3.String (str):
o Sequence of characters enclosed in single,

double, or triple quotes.


o Example:

python
Copy code
name = "Alice"
greeting = 'Hello, world!'
paragraph = """This is a paragraph
that spans multiple lines."""
4.Boolean (bool):
o Represents one of two values: True or False.

o Example:
python
Copy code
is_active = True
has_passed = False
Collection Data Types
1.List (list):
o Ordered collection of items which can be of

different types. Lists are mutable.


o Example:

fruits = ["apple", "banana", "cherry"]


numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "apple", 3.14, True]
2.Tuple (tuple):
o Ordered collection of items which can be of

different types. Tuples are immutable.


o Example:

point = (10, 20)


colors = ("red", "green", "blue")
3.Set (set):
o Unordered collection of unique items.

o Example:
unique_numbers = {1, 2, 3, 4, 5}
letters = {"a", "b", "c"}
4.Dictionary (dict):
o Unordered collection of key-value pairs.

o Example:

person = {"name": "Alice", "age": 30,


"city": "New York"}
scores = {"math": 95, "science": 90}
Special Data Types
1.NoneType (None):
o Represents the absence of a value or a null

value.
o Example:

x = None
2.Range (range):
o Represents an immutable sequence of

numbers, commonly used for looping a


specific number of times in for loops.
o Example:

numbers = range(10) # Creates a range


object from 0 to 9
Type Conversion
Python allows you to convert values from one data
type to another using type conversion functions.
1.Integer to String:
x = 10
y = str(x) # y is now "10"
2.String to Integer:
a = "5"
b = int(a) # b is now 5
3.String to Float:
c = "3.14"
d = float(c) # d is now 3.14
4.Float to Integer:
e = 7.89
f = int(e) # f is now 7
5.List to Tuple:
list_example = [1, 2, 3]
tuple_example = tuple(list_example) #
tuple_example is now (1, 2, 3)
6.Tuple to List:
tuple_example = (1, 2, 3)
list_example = list(tuple_example) #
list_example is now [1, 2, 3]
7.List to Set:
list_example = [1, 2, 2, 3]
set_example = set(list_example) # set_example
is now {1, 2, 3}
Understanding and effectively using these data types
is fundamental to programming in Python. Each data
type has its own properties and is suited for different
kinds of tasks.
Indentation: Indentation refers to the spaces or tabs
used at the beginning of a line of code to indicate
that it is a part of a block of code. It is a crucial
aspect of programming, especially in languages like
Python where indentation is used to define the
structure and flow of the program.
Importance of Indentation
1.Readability: Proper indentation makes code
easier to read and understand.
2.Structure: In languages like Python, indentation
defines blocks of code such as loops,
conditionals, and functions.
3.Debugging: Well-indented code is easier to
debug and maintain.
Comments: In Python, comments are used to explain
code and make it more readable. They are ignored
by the Python interpreter and do not affect the
execution of the program. There are two main types
of comments in Python: single-line comments and
multi-line comments.
Single-Line Comments
Single-line comments start with the hash character
(#) and extend to the end of the line.
This is a single-line comment
print("Hello, World!")
# This comment is at the end of a line of code
Multi-Line Comments
While Python does not have a specific syntax for
multi-line comments, you can use multiple single-
line comments or triple-quoted strings (which are
generally used for docstrings) to achieve the same
effect.
Multi-Line Comments
While Python does not have a specific syntax for
multi-line comments, you can use multiple single-
line comments or triple-quoted strings (which are
generally used for docstrings) to achieve the same
effect.
Example using multiple single-line comments:
# This is a multi-line comment
# that spans multiple lines
print("Hello, World!")
Example using triple-quoted strings:
"""
This is a multi-line comment
using triple-quoted strings.
It can span multiple lines.
"""
print("Hello, World!")
Docstrings
Docstrings are a special type of comment used to
document modules, classes, functions, and methods.
They are written using triple quotes and are the first
statement in the object being documented.
def greet(name):
""" This function greets a person with the given
name.
Parameters:.
name (str): The name of the person to greet.
Returns:
None
"""
print(f"Hello, {name}!")
greet("Alice")
READING INPUT
Reading input in Python can be done using the built-
in input() function. This function reads a line from
the standard input (usually from the keyboard) and
returns it as a string.
Basic Usage
The input() function can be used to prompt the user
for input.
Example:
name = input("Enter your name: ")
print(f"Hello, {name}!")

Print Output
In Python, you can display output using the print()
function. Here are some examples:
1.Printing a String:
print("Hello, World!")
Output:
Hello, World!
2.Printing Variables:
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 30
3.Printing Numbers:
num1 = 10
num2 = 20
print("Sum:", num1 + num2)
Output:
Sum: 30
4.Formatted Output using f-strings (Python
3.6+):
product = "Computer"
price = 1200.50
print(f"Product: {product}, Price: ${price}")
Output:
Product: Computer, Price: $1200.50
5.Printing Multiple Lines:
print("First line")
print("Second line")
Output:
First line
Second line
6.Printing with Special Characters:
print("This\tis\ta\ttabbed\tline")
Output:
This is a tabbed line
7.Printing with End Parameter (Python 3.x):
print("Hello", end="")
print(", World!")
Output:
Hello, World!
These are basic examples of how you can use the
print() function to display output in Python. It's a
versatile function that allows you to output strings,
numbers, variables, and formatted text to the console
or other output streams.
Type Conversions:
Type conversion in Python refers to the process of
converting one data type into another. This is useful
when you need to perform operations that involve
different types of data or when you want to represent
data in a different format. Here are some common
type conversions in Python:
1. Implicit Type Conversion (Coercion)
Python automatically converts data types in certain
situations, such as:
 Integers to Floats: Conversion occurs when
performing operations that involve both integers
and floats.
num_int = 10
num_float = 5.5
result = num_int + num_float # num_int is
implicitly converted to float
print(result) # Output: 15.5
 Floats to Integers: Conversion occurs when
assigning a float to an integer variable.
num_float = 15.8
num_int = int(num_float) # num_float is
explicitly converted to int
print(num_int) # Output: 15
2. Explicit Type Conversion (Type Casting)
You can explicitly convert data from one type to
another using built-in functions. Here are some
examples:
 Integer to Float:
num_int = 10
num_float = float(num_int)
print(num_float) # Output: 10.0
 Float to Integer:
num_float = 5.6
num_int = int(num_float)
print(num_int) # Output: 5
 String to Integer or Float:
num_str = "123"
num_int = int(num_str)
print(num_int) # Output: 123

num_str = "456.78"
num_float = float(num_str)
print(num_float) # Output: 456.78
 Integer or Float to String:
num_int = 100
num_str = str(num_int)
print(num_str) # Output: "100"

num_float = 3.14
num_str = str(num_float)
print(num_str) # Output: "3.14"

the type () Function and Is Operator


In Python, the type() function and the is operator are
useful tools for working with data types and object
identity. Let's explore each of them:
1. type() Function
The type() function in Python is used to get the type
of an object. It returns the data type of the object
passed to it as an argument.
Syntax:
type(object)
Examples:
 Checking the type of variables:
num = 10
print(type(num)) # Output: <class 'int'>

num_float = 5.5
print(type(num_float)) # Output: <class 'float'>

name = "Alice"
print(type(name)) # Output: <class 'str'>
 Checking the type of more complex objects:
my_list = [1, 2, 3]
print(type(my_list)) # Output: <class 'list'>

my_dict = {'a': 1, 'b': 2}


print(type(my_dict)) # Output: <class 'dict'>
 Using type() with functions:

def greet():
print("Hello!")

print(type(greet)) # Output: <class 'function'>


2. is Operator
The is operator in Python checks if two variables
refer to the same object in memory, not just if they
are equal.
Syntax:
x is y
Examples:
 Checking identity with simple types:
a = 10
b = 10
print(a is b) # Output: True (since integers in
this range are cached in Python)

c = 1000
d = 1000
print(c is d) # Output: False (different objects
are created for large integers)
 Checking identity with lists:
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 is list2) # Output: False (different
objects in memory)

list3 = list1
print(list1 is list3) # Output: True (both
variables refer to the same list object)
 Checking identity with functions:
def foo():
return

def bar():
return

print(foo is bar) # Output: False (different


function objects)
Key Differences between type() and is:
 Functionality:
o type() checks the data type of an object.

o is checks if two variables point to the same

object in memory.
 Usage:
o Use type() to determine the type of an object

for type checking or debugging.


oUse is to check object identity, which is
particularly useful when dealing with
mutable objects or functions.
 Output:
o type() returns the class/type of an object

(e.g., <class 'int'>, <class 'list'>).


o is returns a boolean (True or False)

indicating whether two variables refer to the


same object.
Understanding how to use type() and is effectively
can help you debug code, manage memory
efficiently, and write more robust Python programs.
Dynamic and Strongly Typed Language:
n the realm of programming languages, terms like
"dynamic" and "strongly typed" describe key
characteristics that influence how code is written,
executed, and managed. Let's explore each of these
concepts:
Dynamic Typing
Dynamic typing refers to the ability of a
programming language to automatically determine
the data type of a variable at runtime. In dynamically
typed languages, you do not need to explicitly
declare the type of a variable when you define it.
Instead, the type is inferred based on the value
assigned to it.
Characteristics of Dynamic Typing:
 Implicit Declaration: Variables are declared
without specifying a type.
 Type Checking at Runtime: Type
compatibility is checked during program
execution rather than at compile-time.
 Flexibility: Variables can change type during
the execution of the program.
Examples of Dynamically Typed Languages:
 Python: Variables are dynamically typed; their
types are determined based on the assigned
values.
 JavaScript: Another example where variables
are dynamically typed, allowing for flexibility in
data manipulation and function invocation.
Example in Python:
# Dynamic typing in Python
x = 10 # x is an integer
print(type(x)) # Output: <class 'int'>

x = "Hello" # Now x is a string


print(type(x)) # Output: <class 'str'>
Strongly Typed
Strongly typed languages enforce strict type
constraints and do not perform implicit type
conversion. This means that operations between
different data types are not automatically allowed
and must be explicitly converted if necessary.
Characteristics of Strongly Typed Languages:
 Explicit Type Conversion: Conversion
between types must be explicitly performed by
the programmer.
 Type Safety: Types are strictly enforced to
prevent unintended operations or errors.
 Less Implicit Conversion: Operations between
different types generally require explicit casting
or conversion.
Examples of Strongly Typed Languages:
 Python: Despite being dynamically typed,
Python is also considered strongly typed because
it enforces strict type rules.
 Java: Variables in Java must be declared with a
specific type, and operations between
incompatible types are not allowed without
explicit conversion.
Example of Strongly Typed Behavior:
# Strongly typed behavior in Python
x = 10
y = "20"

# This would raise a TypeError because you cannot


add an integer and a string directly
# Uncommenting this line would result in a
TypeError:
# print(x + y)

# Explicit conversion needed


print(x + int(y)) # Output: 30
Key Differences
 Dynamic vs. Static Typing: Dynamic typing
refers to type determination at runtime (e.g.,
Python), while static typing involves type
checking at compile-time (e.g., Java).
 Strong vs. Weak Typing: Strongly typed
languages enforce strict type rules and do not
automatically convert types (e.g., Python, Java),
whereas weakly typed languages may perform
implicit type conversions (e.g., JavaScript).
Understanding these concepts helps in choosing the
right language for a particular programming task and
in writing robust, maintainable code. Python, for
example, combines dynamic typing with strong type
enforcement, offering flexibility without sacrificing
safety and clarity.
Control Flow Statements if statement, if-else
statement, if...elif…else, Nested if statement, while
Loop, for Loop, continue and break Statements,
Catching Exceptions Using try and except
Statement.
if statement:
In Python, the if statement is used for conditional
execution. It allows you to execute a certain block of
code only if a specified condition is true. Here's the
basic syntax of an if statement in Python:
if condition:
# Code to be executed if the condition is true
statement1
statement2
# and so on
Here, condition is an expression that evaluates to
either True or False. If condition is True, then the
indented block of code following the if statement
(denoted by spaces or tabs) will be executed. If
condition is False, then the block of code is skipped.
Example:
x = 10

if x > 5:
print("x is greater than 5")
print("This statement is also executed because x >
5")
In this example, since x is indeed greater than 5,
both print statements inside the if block will be
executed.
Using else and elif:
You can also extend the if statement with else and
elif (short for else if) clauses to handle alternative
conditions:
 else: Executes a block of code if the if condition
is False.
 elif: Stands for "else if". It allows you to check
multiple conditions sequentially.
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition1 is false and
condition2 is true
else:
# Code to execute if both condition1 and
condition2 are false
Example with elif and else:
grade = 85

if grade >= 90:


print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("F")
In this example, based on the value of grade, a
corresponding grade letter is printed depending on
which condition (if, elif, or else) is satisfied first.
Notes:
 Python uses indentation (typically 4 spaces) to
define blocks of code. This is different from
languages like C or Java, which use curly braces
{}.
 The elif and else parts are optional. An if
statement can stand alone without them.
Understanding if statements are fundamental to
controlling the flow of your Python programs based
on different conditions.
Nested if:
Nested if statements in Python refer to placing one if
statement inside another if or else block. This allows
for more complex conditional logic where certain
conditions need to be checked only if another
condition is true. Here's how you can use nested if
statements in Python:
x = 10
y=5

if x > 5:
print("x is greater than 5")
if y > 2:
print("y is also greater than 2")
else:
print("y is not greater than 2")
else:
print("x is not greater than 5")
In this example:
 The outer if statement checks if x is greater than
5.
 If x is greater than 5 (True), it prints "x is greater
than 5".
 Inside the outer if block, there is a nested if
statement that checks if y is greater than 2.
 Depending on the value of y, it will print either
"y is also greater than 2" or "y is not greater than
2".
 If x is not greater than 5 (False), it executes the
else block of the outer if statement and prints "x
is not greater than 5".

Nested if with elif:


You can also nest if, elif, and else statements to
handle multiple conditions in a more structured way:
x = 10
y=5

if x > 5:
if y > 2:
print("x is greater than 5 and y is greater than
2")
elif y == 2:
print("x is greater than 5 and y is exactly 2")
else:
print("x is greater than 5 but y is less than 2")
else:
print("x is not greater than 5")
In this example:
 The outer if statement checks if x is greater than
5.
 If x is greater than 5 (True), it then checks the
value of y using nested if, elif, and else
statements:
o If y is greater than 2, it prints "x is greater

than 5 and y is greater than 2".


o If y is exactly 2, it prints "x is greater than 5

and y is exactly 2".


o If y is less than 2, it prints "x is greater than

5 but y is less than 2".


 If x is not greater than 5 (False), it executes the
else block of the outer if statement and prints "x
is not greater than 5".
Important Notes:
 Proper indentation is crucial in Python to
indicate nested blocks of code.
 Nesting if statements should be done carefully to
maintain code readability. Excessive nesting can
make code harder to understand and debug.
 Nested if statements allow you to handle more
complex conditional logic based on multiple
conditions and their combinations.
Understanding how to use nested if statements
effectively can help you write more flexible and
expressive code in Python, especially when dealing
with complex conditions and decision-making
processes.
Certainly! Let's explore the while loop, for loop,
continue, and break statements in Python. These are
fundamental control flow statements that allow you
to iterate through sequences, skip certain iterations,
and break out of loops based on conditions.
while Loop:
The while loop in Python repeatedly executes a
block of statements as long as a specified condition
is true.
Syntax:
while condition:
# Code block to be executed while the condition is
true
statement1
statement2
# and so on
Example:
count = 0

while count < 5:


print(f"Current count: {count}")
count += 1
In this example:
 count starts at 0.
 The while loop continues executing as long as
count < 5.
 Each iteration, it prints the current value of
count and increments count by 1 (count += 1).
 The loop terminates when count reaches 5
because count < 5 becomes False.
for Loop:
The for loop in Python iterates over a sequence
(such as a list, tuple, string, or range) and executes a
block of code for each element in the sequence.
Syntax:
for item in sequence:
# Code block to be executed for each item in
sequence
statement1
statement2
# and so on
Example:
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(f"Current fruit: {fruit}")
In this example:
 fruits is a list containing three strings.
 The for loop iterates over each element (fruit) in
the fruits list.
 For each iteration, it prints "Current fruit: "
followed by the value of fruit.
continue Statement:
The continue statement in Python is used to skip the
rest of the code inside a loop for the current iteration
and proceed to the next iteration.
Example (with while loop):
count = 0

while count < 5:


count += 1
if count == 3:
continue
print(f"Current count: {count}")
In this example:
 The while loop increments count from 1 to 5.
 When count equals 3, the continue statement is
encountered.
 The continue statement skips the remaining code
in the loop for that iteration.
 Therefore, "Current count: 3" is not printed, but
the loop continues with other iterations.
break Statement:
The break statement in Python terminates the current
loop and resumes execution at the next statement
after the loop.
Example (with for loop):
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(f"Current fruit: {fruit}")
if fruit == "banana":
break
In this example:
 The for loop iterates over the fruits list.
 For each iteration, it prints "Current fruit: "
followed by the value of fruit.
 When fruit is "banana", the if condition is true.
 The break statement terminates the loop
immediately after "banana" is printed.
 Therefore, only "apple" and "banana" are
printed, and "cherry" is not processed.
Summary:
 while Loop: Executes a block of code
repeatedly while a condition is true.
 for Loop: Iterates over a sequence (list, tuple,
string, etc.) and executes a block of code for
each element.
 continue Statement: Skips the rest of the code
inside a loop for the current iteration and moves
to the next iteration.
 break Statement: Terminates the loop it is in
and resumes execution at the next statement
after the loop.
These statements are essential for controlling the
flow of execution in Python programs, especially
when dealing with repetitive tasks or iterating over
data structures
Catching Exceptions Using try and except
Statement.
In Python, the try and except statements are used for
exception handling, which allows you to catch and
handle exceptions (errors) gracefully during program
execution. This mechanism helps in preventing your
program from crashing unexpectedly when errors
occur. Here's how try and except statements work:
Syntax:
try:
# Code block where exceptions may occur
statement1
statement2
# and so on
except ExceptionName as exception_variable:
# Code to handle the exception
statement3
statement4
# and so on
Example:
try:
x = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError as e:
print("Error: Division by zero!")
print(f"Exception details: {e}")
In this example:
 The try block contains code that might raise an
exception (in this case, dividing by zero).
 The except block catches the specific
ZeroDivisionError exception.
 If a ZeroDivisionError occurs during the
execution of the try block, the code inside the
except block will execute.
 The as e part captures the exception object
(ZeroDivisionError in this case) into the variable
e, allowing you to access details about the
exception.
Multiple except Blocks:
You can have multiple except blocks to handle
different types of exceptions separately.
try:
x = int(input("Enter a number: "))
result = 10 / x # This may raise
ZeroDivisionError or ValueError
except ZeroDivisionError:
print("Error: Division by zero!")
except ValueError:
print("Error: Invalid input. Please enter a valid
number.")
In this example:
 The try block attempts to get an integer input
from the user and perform a division operation.
 There are two separate except blocks:
o ZeroDivisionError catches division by zero

errors.
o ValueError catches errors when the input

cannot be converted to an integer.


Generic except Block:
You can also use a generic except block to catch any
type of exception that is not explicitly handled by
previous except blocks. However, it is generally
recommended to specify the specific exceptions you
expect to handle whenever possible.
try:
# Some code that may raise exceptions
except ZeroDivisionError:
# Handle ZeroDivisionError
except Exception as e:
# Handle all other exceptions
print(f"An error occurred: {e}")
finally Block:
Optionally, you can use a finally block to execute
cleanup code that should always be run, regardless
of whether an exception was raised or not.
try:
# Some code that may raise exceptions
except SomeException:
# Handle SomeException
finally:
# This block is always executed, whether there
was an exception or not
cleanup_code()
Summary:
 try: Contains code that may raise exceptions.
 except: Handles specific exceptions that occur
within the try block.
 as exception_variable: Optionally captures the
exception object for further processing.
 Multiple except blocks: Allows handling
different types of exceptions separately.
 finally: Optional block for cleanup code that is
always executed, regardless of exceptions.
Using try and except statements effectively helps in
writing robust Python code that can gracefully
handle errors and exceptions during execution,
improving the reliability and stability of your
programs.
Program 01: Write a program to find the largest
element among three Numbers
Source Code:
num1 = 10
 num2 = 14
 num3 = 12

 #num1 = float(input("Enter first number: "))


 #num2 = float(input("Enter second number: "))
 #num3 = float(input("Enter third number: "))

 if (num1 >= num2) and (num1 >= num3):


 largest = num1
 elif (num2 >= num1) and (num2 >= num3):
 largest = num2
 else:
 largest = num3

 print("The largest number is", largest)


 Output:
The Largest number is 14
Program 2: Write a Program to display all prime
numbers within an interval
Source code:
lower = 900
upper = 1000
print("Prime numbers between", lower, "and", upper,
"are:")
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Output:
Prime numbers between 900 and 1000 are:
907
911
919
929
937
941
947
953
967
971
977
983
991
997
Program 03
Write a program to swap two numbers without
using a temporary variable.
Source code:
x=5
y = 10

# To take inputs from the user


#x = input('Enter value of x: ')
#y = input('Enter value of y: ')

# create a temporary variable and swap the values


temp = x
x=y
y = temp

print('The value of x after swapping: {}'.format(x))


print('The value of y after swapping: {}'.format(y))

Output:
The value of x after swapping: 10
The value of y after swapping: 5
Program 04
Demonstrate the following Operators in Python
with suitable examples. i) Arithmetic
Operators
ii) Relational Operators iii) Assignment
Operators
Source code:
i) Arithmetic Operators
a = 21
b = 10
# Addition
print ("a + b : ", a + b)
# Subtraction
print ("a - b : ", a - b)
# Multiplication
print ("a * b : ", a * b)
# Division
print ("a / b : ", a / b)
# Modulus
print ("a % b : ", a % b)

# Exponent
print ("a ** b : ", a ** b)
# Floor Division
print ("a // b : ", a // b)

Output
a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b: 1
a ** b : 16679880978201
a // b : 2
Relational Operators:
Source code:
a=4
b=5
# Equal
print ("a == b : ", a == b)
# Not Equal
print ("a != b : ", a != b)
# Greater Than
print ("a > b : ", a > b)
# Less Than
print ("a < b : ", a < b)
# Greater Than or Equal to
print ("a >= b : ", a >= b)
# Less Than or Equal to
print ("a <= b : ", a <= b)
Output:
a == b : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True
iii)Assignment Operators
# Assignment Operator
a = 10
# Addition Assignment
a += 5
print ("a += 5 : ", a)
# Subtraction Assignment
a -= 5
print ("a -= 5 : ", a)
# Multiplication Assignment
a *= 5
print ("a *= 5 : ", a)
# Division Assignment
a /= 5
print ("a /= 5 : ",a)
# Remainder Assignment
a %= 3
print ("a %= 3 : ", a)
# Exponent Assignment
a **= 2
print ("a **= 2 : ", a)
# Floor Division Assignment
a //= 3
print ("a //= 3 : ", a)
Output:

a += 5 : 15
a -= 5 : 10
a *= 5 : 50
a /= 5 : 10.0
a %= 3 : 1.0
a **= 2 : 1.0
a //= 3 : 0.0

Program 5:

Write a program to add and multiply complex


numbers
Source Code:
print("Addition of two complex numbers : ",(4+3j)
+(3-7j))
print("Subtraction of two complex numbers : ",
(4+3j)-(3-7j))
print("Multiplication of two complex numbers : ",
(4+3j)*(3-7j))
print("Division of two complex numbers:",(4+3j)/(3-
7j))
Output:
Addition of two complex numbers : (7-4j)
Subtraction of two complex numbers : (1+10j)
Multiplication of two complex numbers : (33-19j)
Division of two complex numbers : (-
0.15517241379310348+0.6379310344827587j)

Program 06:
Write a program to print multiplication table of a
given number.

# Multiplication table (from 1 to 10) in Python

num = 9

# To take input from the user


# num = int(input("Display multiplication table of?
"))

# Iterate 10 times from i = 1 to 10


for i in range(1, 10):
print(num, 'x', i, '=', num*i)

Output:
9x1=9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90

You might also like