Unit 1 Python Programming
Unit 1 Python Programming
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:
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:
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
python
Copy code
pi = 3.14
gravity = 9.81
3.String (str):
o Sequence of characters enclosed in single,
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
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:
value.
o Example:
x = None
2.Range (range):
o Represents an immutable sequence of
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"
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'>
def greet():
print("Hello!")
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
object in memory.
Usage:
o Use type() to determine the type of an object
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 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".
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
errors.
o ValueError catches errors when the input
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:
Program 06:
Write a program to print multiplication table of a
given number.
num = 9
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