0% found this document useful (0 votes)
5 views

Python UNIT.1

The document provides an overview of Python programming, highlighting its features such as being an interpreted, object-oriented, and free language. It discusses the origins of Python, its applications in various fields like AI, web development, and finance, as well as the different versions of Python. Additionally, it covers basic programming concepts including variables, operators, and the structure of Python programs.

Uploaded by

appachud
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python UNIT.1

The document provides an overview of Python programming, highlighting its features such as being an interpreted, object-oriented, and free language. It discusses the origins of Python, its applications in various fields like AI, web development, and finance, as well as the different versions of Python. Additionally, it covers basic programming concepts including variables, operators, and the structure of Python programs.

Uploaded by

appachud
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Python Programming Python Programming

UNIT 1: INTRODUCTION AND OVERVIEW 2. Indentation


INTRODUCTION Indentation is one of the greatest feature in python
 Python is an interpreted, object-oriented, widely used as general-purpose, high level 3. It’s free or it is an open source
programming language with dynamic semantics. Downloading python and installing python is free and easy.
 Python supports modules and packages, which encourages program modularity and code 4. It is Powerful Language
reuse.  Dynamic typing
 Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of  Built-in types and tools
program maintenance.  Library utilities
 The Python interpreter and the extensive standard library are available in source or binary  Third party utilities (e.g. Numeric, NumPy, sciPy)
form without charge for all major platforms, and can be freely distributed.  Automatic memory management
 Python is a computer programming language often used to build websites and software, 5. It is Portable
automate tasks, and conduct data analysis. Python runs virtually every major platform used today. As long as you have a compatible
 Since there is no compilation step, the edit-test-debug cycle is incredibly fast. Debugging python interpreter installed, python programs will run in exactly the same manner,
Python programs is easy: irrespective of platform.
6. It is easy to use and learn
ORIGIN OF PYTHON
Python Programs are compiled automatically to an intermediate form called byte code, which
 It was initially designed by Guido van Rossum in 1991 and developed by Python Software
the interpreter then reads.
Foundation. He needed a name that was short, unique, and slightly mysterious, so he
7. Interpreted Language
decided to call the language Python.
Python is processed at runtime by python Interpreter
 Python as a successor to ABC programming language, which was inspired by SETL,
8. Interactive Programming Language
capable of exception handling and interfacing with the Amoeba operating system.
Users can interact with the python interpreter directly for writing the programs
 It was mainly developed for emphasis on code readability, and its syntax allows
programmers to express concepts in fewer lines of code. APPLICATIONS OF PYTHON
 Python is a programming language that lets you work quickly and integrate systems more 1. AI and machine learning
efficiently. Python is a stable, flexible, and simple programming language, it’s perfect for various
 There are two major Python versions- Python 2 and Python 3. machine learning (ML) and artificial intelligence (AI) projects. In fact, Python is among the
favorite languages among data scientists, and there are many Python machine learning and AI
FEATURES OF PYTHON
libraries and packages available.
The following are the features of Python
1. Python is object-oriented programming language 2. Desktop GUI Applications

Python program structure supports concepts of polymorphism, operation overloading and The GUI stands for the Graphical User Interface, which provides a smooth interaction to any

multiple inheritance. application.

. Page 1 . Page 2
Python Programming Python Programming

3. Software Development BEGINNING WITH PYTHON PROGRAMMING


Python is useful for the software development process. It works as a support language and 1) Finding an Interpreter:
can be used to build control and management, testing, etc. Before we start Python programming, we need to have an interpreter to interpret and run our
4. Web development programs. There are certain online interpreters like
Python is a best choice for web development. This is largely due to the fact that there are https://ide.geeksforgeeks.org/,http://ideone.com/ or http://codepad.org/ that can be used to start
many Python web development frameworks to choose from, such as Django, Pyramid, and Python without installing an interpreter.
Flask. These frameworks have been used to create sites and services such as Spotify, Mozilla Windows: There are many interpreters available freely to run Python scripts like IDLE
etc. (Integrated Development Language Environment) which is installed when you install the python
5. Game development software from http://python.org/downloads/
It is possible to create simple games using the python programming language, which means it
2) Writing first program:
can be a useful tool for quickly developing a prototype
# Script Begins
6. Language development
Statement1
The simple and elegant design of Python and its syntax means that it has inspired the creation
Statement2
of new programming languages. Languages such as Cobra, CoffeeScript.
Statement3
7. Finance
# Script Ends
Python is increasingly being utilized in the world of finance, often in areas such as
quantitative and qualitative analysis. It can be a valuable tool in determining asset price trends
3) Python Code Execution:
and predictions, as well as in automating workflows across different data sources.
Source code is translated to byte code, which is then run by the Python Virtual Machine (PVM).
Code is automatically compiled, but then it is interpreted. Source code extension is .py , Byte
PYTHON VERSIONS
code extension is .pyc (Compiled python code)
The following table lists all the important versions of Python

Version Release Date


Python 0.9.0 February 1991 m.py m.pyc PVM
Python 1.0 January 1994
Python 2.0 October 2000
Python 3 December 2008
Python 3.6 December 2016
There are two modes for using the Python interpreter
Python 3.6.5 March 2018
 Interactive Mode or Command Line mode
Python 3.7.0 May 2018
 Script Mode
Python 3.8 October 2019
Python 3.9 - Current Version October 2020

. Page 3 . Page 4
Python Programming Python Programming

Running Python in interactive mode PYTHON BASICS


Without passing python script file to the interpreter, directly execute code to Python prompt. Identifier
Interactive mode is a command line shell which gives immediate feedback for each statement, An identifier is a name given to a variable, function, class or module. Identifiers may be one or
while running previously fed statements in active memory. more characters.
Ex: print("hello world") // hello world  Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore ( _ ).
Running python in script mode
Ex: myCountry, other_1 and good_morning etc.
Programmers can store Python script source code in a file with the .py extension, and use the
 A Python identifier can begin with an alphabet (A – Z and a – z and _ ).
interpreter to execute the contents of the file.
 An identifier cannot start with a digit but is allowed everywhere else.

PYTHON IDES  Keywords cannot be used as identifiers.

An IDE (or Integrated Development Environment) is a program dedicated to software  One cannot use spaces and special symbols like !, @, #, $, % etc. as identifiers.
development. As the name implies, IDEs integrate several tools specifically designed for software  Identifier can be of any length.
development.
These tools usually include: Keywords
 An editor designed to handle code (with, for example, syntax highlighting and auto- Keywords are a list of reserved words that have predefined meaning. Keywords are cannot be
completion) used by programmers as identifiers for variables, functions, constants or with any identifier name.
 Build, execution, and debugging tools. The following shows the Python keywords.
 Some form of source control.

Ex: Spyder, Thonny, Jupyter Notebook, Pycham etc.

SIMPLE PYTHON PROGRAM

num1 = input('Enter first number: ') # Store input numbers


num2 = input('Enter second number: ')
sum = float(num1) + float(num2)
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) # Display the sum

Statement and Expression


OUTPUT
A statement is an instruction that the Python interpreter can execute. Python program consists of a
Enter first number: 1.5
sequence of statements. Statements can be a line or several lines of Python code.
Enter second number: 6.3
Ex: z = 1 is an assignment statement.
The sum of 1.5 and 6.3 is 7.8

. Page 5 . Page 6
Python Programming Python Programming

Expression is an arrangement of values and operators which are evaluated to make a new value. Ex: number =100 // integer type value is assigned to a variable number
Expressions are statements as well. A value is the representation of some entity like a letter or a miles =1000.0 // float type value has been assigned to variable miles
number that can be manipulated by a program. name ="Python" // string type value is assigned to variable name
Ex: A single value >>> 20
A single variable >>> z In Python, not only the value of a variable may change during program execution but also the
A combination of variable, operator and value >>> z + 20 type of data that is assigned. We can assign an integer value to a variable, use it as an integer for a
while and then assign a string to the variable. A new assignment overrides any previous
VARIABLE assignments.
Variable is a named placeholder to hold any type of data which the program can use to assign and Ex: century = 100
modify during the course of execution. In Python, there is no need to declare a variable explicitly century = "hundred"
by specifying whether the variable is an integer or a float or any other type. To define a new An integer value is assigned to century variable and then in second expression assigning a string
variable in Python, simply assign a value to a name. value to century variable.

Legal Variable Names Python allows to assign a single value to several variables simultaneously.
 Variable names can consist of any number of letters, underscores and digits. Ex: a = b = c =1
 Variable should not start with a number. An integer value is assigned to variables a, b and c simultaneously. Values for each of these
 Python Keywords are not allowed as variable names. variables are 1.

 Variable names are case-sensitive.


Ex: computer and Computer are different variables. Ex: a,b,c = 1,2,“Python”

 Python variables use lowercase letters with words separated by underscores Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively and

 Avoid naming a variable where the first character is an underscore. This is legal in Python, one string object with the value “Python” is assigned to the variable c. Values for a is 1 b is 2 and

it can limit the interoperability of your code with applications built by using other c is “Python.

programming languages.
 Variable names are descriptive and clear enough. OPERATORS
Operators are symbols, such as +, –, =, >, and <, that perform certain mathematical or logical
operation to manipulate data values and produce a result based on some rules. An operator
Assigning Values to Variables
The general format for assigning values to variables is as follows: manipulates the data values called operands.
Python language supports a wide range of operators. They are
variable_name = expression 1. Arithmetic Operators
2. Assignment Operators
Where variable_name is name of the variable, the equal sign (=) also known as simple
3. Comparison Operators
assignment operator is used to assign values to variables.
4. Logical Operators
. Page 7 . Page 8
Python Programming Python Programming

5. Bitwise Operators Operator


Operator Description Example
6. Identity operators Name
Assigns values from right side operands to
7. Membership operators = Assignment p=3
left side operand.
Adds the value of right operand to the left If p = 3, p + = 1 its
Addition
+= operand and assigns the result to left equivalent to
1. Arithmetic Operators Assignment
operand. p = p+1 = 4
Arithmetic operators are used to execute arithmetic operations such as addition, subtraction, Subtracts the value of right operand from If p = 3, p - = 1 its
Subtraction
division, multiplication etc. The following table shows all the arithmetic operators. -= the left operand and assigns the result to left equivalent to
Assignment
operand. p=p-1 =3
Multiplies the value of right operand with If p = 3, p * = 1 its
Operator Operator Name Description Example Multiplication
*= the left operand and assigns the result to left equivalent to
Adds two operands and producing their If p= 3, q=2 Assignment
+ Addition Operator operand. p= p*1 = 3
sum p+q=5 Divides the value of right operand with the If p = 3, p / = 1 its
Subtracts two operands and producing If p= 3, q=2 Division
- Subtraction Operator /= left operand and assigns the result to left equivalent to
their difference p - q = -1 Assignment
operand. p= p/1 =3
Multiplication If p= 3, q=2 If p = 3, p % = 1
* Produces the product of the operands. Exponentiation Computes the remainder after division and
Operator p*q=6 %= its equivalent to
Assignment Assigns the value to the left operand.
Produces the quotient of its operands p=p%1=0
If p= 3, q=2
/ Division Operator where the left operand is the dividend Produces the integral part of the quotient of
p / q = 1.5 If p = 3, p ** = 1
and the right operand is the divisor. Floor Division its operands where the left operand is the
Divides left hand operand by right hand If p= 3, q=2 ** = its equivalent to
% Modulus Operator Assignment dividend and the right operand is the
operand and returns a remainder. p%q=1 p = p ** 1 = 3
divisor.
Performs exponential (power) If p= 3, q=2 If p = 3, p //=1
** Exponent Operator Remainder Evaluates to the result of raising the first
calculation on operators. p ** q = 9 // = its equivalent to
Floor division If p= 3, q=2 Assignment operand to the power of the second operand.
// Returns the integral part of the quotient. p = p // 1 = 3
Operator p // q = 1

2. Assignment Operators 3. Comparison Operators


Assignment operators are used for assigning the values generated after evaluating the right The values of two operands are to be compared then comparison operators are used. The
operand to the left operand. Assignment operation always works from right to left. Assignment output of these comparison operators is always a Boolean value, either True or False. The
operators are either simple assignment operator or compound assignment operators. Simple operands can be Numbers or Strings or Boolean values. Strings are compared letter by letter
assignment is done with the equal sign (=) and simply assigns the value of its right operand to using their ASCII values,
the variable on the left. The following table shows all the assignment operators. Ex: “P” is less than “Q”, and “Aston” is greater than “Asher”.
Following table shows all the comparison operators.

. Page 9 . Page 10
Python Programming Python Programming

Operator Operator Name Description Example


Operator Operator Name Description Example Performs AND operation and the result is
1 > 2 and 9 > 6 is
If p = 3, q=2 and Logical AND True when both operands are True
If the values of two operands are equal, then False
== Equal to p = = q is otherwise False
the condition becomes True otherwise False
False Performs OR operation and the result is 3 > 2 or 8 < 4 is
or Logical OR True when any one of both operand is
If values of two operands are not equal, then If p= 3, q=2 True
!= Not Equal to True otherwise False
the condition becomes True otherwise False p! = q is True
not(True and False)
If the value of left operand is greater than not Logical NOT Reverses the operand state
If p = 3, q = 2 is True
> Greater than the value of right operand, then condition
p > q is True
becomes True otherwise False
If the value of left operand is less than the 5. Bitwise Operators
If p= 3, q=2
< Lesser than value of right operand, then condition Bitwise operators represent operands as a sequence of bits (0’s and 1’s) and perform bit by bit
p < q is False
becomes True otherwise False
operation. Bitwise operators perform their operations on binary representations, but they return
If the value of left operand is greater than or
If p= 3, q=2 standard Python numerical values.
>= Greater than or equal to the value of right operand, then
p >= q is True
condition becomes True otherwise False Ex: The decimal number 10 has a binary representation of 1010.
If the value of left operand is less than or The following tables show Bitwise truth table and all the bitwise operators.
Lesser than or If p= 3, q=2
<= equal to the value of right operand, then
equal to p <= q is False P Q P& Q P|Q P^Q ~P
condition becomes True otherwise False
0 0 0 0 0 1

4. Logical Operators 0 1 0 1 1 1

The logical operators are used for comparing or negating the logical values of their operands 1 0 0 1 1 0

and to return the resulting logical value. The values of the operands on which the logical 1 1 1 1 0 0

operators operate evaluate to either True or False. The result of the logical operator is always a
Boolean value, True or False. The following tables show Boolean logic truth table and all the Operator Operator Name Description Example
Result is 1, If the corresponding bits of both If p = 60, q=30
logical operators. & Binary AND
operands are 1. p & q is 12
Result is 1, if the corresponding bits of If p= 60, q=30
| Binary OR
either or both operands are 1. p | q is 61
P Q P and Q P or Q not P
Result is 1 If the corresponding bits of either If p = 60, q=30
^ Binary XOR
True True True True False but not both operands are 1. p ^ q is 61
Binary Ones If p= 60
True False False True ~ Inverts the bits of its operand.
Complement ~ p is -61
False True False True True The left operands value is moved left by the
Binary Left If p= 60, q=30
<< number of bits specified by the right
False False False Shift p << q is 240
False operand.
Binary Right The left operands value is moved right by If p= 60, q=30
>> the number of bits specified by the right
Shift p >> q is 15
operand.

. Page 11 . Page 12
Python Programming Python Programming

Ex: PRECEDENCE AND ASSOCIATIVITY


Operator precedence determines the way in which operators are parsed with respect to each other.
Operators with higher precedence become the operands of operators with lower precedence.
Associativity determines the way in which operators of the same precedence are parsed. Almost
all the operators have left-to-right associativity. Operator precedence is listed in table below
starting with the highest precedence to lowest precedence.

6. 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.

Operator Description Example


is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y

7. Python Membership Operators


Membership operators are used to test if a sequence is presented in an object: Ex: (2 + 3) * 6
5 *6 // ( ) is highest precedence

Operator Description Example 30

Returns True if a sequence with the specified


in x in y
value is present in the object
Returns True if a sequence with the specified
not in x not in y
value is not present in the object

. Page 13 . Page 14
Python Programming Python Programming

DATA TYPES INDENTATION


Data types specify the type of data like numbers and characters to be stored and manipulated In Python, Programs get structured through indentation usually, we expect indentation from any
within a program. program code, but in Python it is a requirement. This principle makes the code look cleaner and
Basic data types of Python are easier to understand and read. Any statements written under another statement with the same
• Numbers indentation is interpreted to belong to the same code block. If there is a next statement with less
• Boolean indentation to the left, then it just means the end of the previous code block.
• Strings
• None

 Numbers
Integers, floating point numbers and complex numbers are python numbers category. They are
defined as int, float and complex class in Python. Integers can be of any length; it is only limited
by the memory available. A floating point number is accurate up to 15 decimal places. 1 is an
integer, 1.0 is floating point number. Complex numbers are written in the form, x + yj, where x is
the real part and y is the imaginary part.

 Boolean
In the above diagram, Block 2 and Block 3 are nested under Block 1. Usually, four whitespaces are
Booleans are useful for conditional statements. Boolean values are either True or False. The
used for indentation and are preferred over tabs. Incorrect indentation will result in
Boolean values True and False are treated as reserved words.
IndentationError.
 Strings
A string consists of a sequence of one or more characters, which can include letters, numbers, COMMENTS
and other types of characters. A string can also contain spaces. You can use single quotes or A comment is a text that describes what the program or a particular part of the program is trying
double quotes to represent strings and it is also called a string literal. Multiline strings can be to do and is ignored by the Python interpreter. Comments are used to help you and other
denoted using triple quotes, ''' or " " ". programmers understand, maintain, and debug the program. Python uses two types of comments:
Ex: s = ' This is single quote string’ single-line comment and multiline comments.
s = “ This is double quote string "
Single Line Comment
In Python, the hash (#) symbol is used for Single Line Comment. Hash (#) symbol makes all text
 None
following it on the same line into a comment.
None is another special data type in Python. None is frequently used to represent the absence
Ex: # This is single line Python comment
of a value.
Ex: money = None // None value is assigned to variable money

. Page 15 . Page 16
Python Programming Python Programming

Multiline Comments It prints the string Hello World!! on to the console. There are different ways to print values in
If the comment extends multiple lines, then one way of commenting those lines is to use hash (#) Python, there are two major string formats which are used inside the print () function to display
symbol at the beginning of each line. the contents onto the console. They are
Ex: # This is  str.format()
# multiline comments  f-strings
# In Python
Another way of doing this is to use triple quotes, either ''' or """. These triple quotes are used as a  str.format() Method
multiline comment. str.format() method is to insert the value of a variable, expression or an object into another
Ex: ''' This is string and display it to the user as a single string. The format() method returns a new string with
multiline comment inserted values.
in Python using triple quotes''' Syntax: str.format (p0, p1, ..., k0=v0, k1=v1, ...)

Where p0, p1,... are called as positional arguments and, k0, k1,... are keyword arguments with
BUILT IN FUNCTIONS
their assigned values of v0, v1,... respectively.
CONSOLE INPUT
Positional arguments are a list of arguments that can be accessed with an index of argument inside
1. input (): This function is used to get data from the user.
curly braces like {index}. Index value starts from zero.
Syntax: variable_name = input ([prompt])
Keyword arguments are a list of arguments of type keyword = value, that can be accessed with the
Where prompt is a string written inside the parenthesis that is printed on the screen. The prompt
name of the argument inside curly braces like {keyword}.
statement gives an indication to the user of the value that needs to be entered through the
Here, str is a mixture of text and curly braces of indexed or keyword types. The indexed or
keyboard.
keyword curly brace are replaced by their corresponding argument values and is displayed as a
Ex: person = input ("What is your name?")
single string to the user.
The input() function prints the prompt statement on the screen. The input() function reads the line
from the user and converts the line into a string. The line typed by the user is assigned to the Program to Demonstrate input() and print() Functions

person variable in the above example. country = input("Which country do you live in?")
print("I live in {0}".format(country))

CONSOLE OUTPUT
Output
1. print () : The print() function allows a program to display text onto the console. The print
Which country do you live in? India
function will print everything as strings and anything that is not already a string is
I live in India
automatically converted to its string representation.
The 0 inside the curly braces {0} is the index of the first (0th) argument, where country is a
Syntax: print (“String”) variable

Ex: print("Hello World!!")

. Page 17 . Page 18
Python Programming Python Programming

Program to Demonstrate the Positional Change of Indexes of Arguments Write Python Program to Find the Area and Circumference of a Circle
a = 10 radius = int(input("Enter the radius of a circle"))
b = 20 area_of_a_circle = 3.1415 * radius * radius
print("The values of a is {0} and b is {1}".format(a, b)) circumference_of_a_circle = 2 * 3.1415 * radius
print("The values of b is {1} and a is {0}".format(a, b)) print(f "Area = {area_of_a_circle} and Circumference = {circumference_of_a_circle}")

Output
The values of a is 10 and b is 20 Output
The values of b is 20 and a is 10 Enter the radius of a circle
5
 f-strings Area = 78.53750000000001 and Circumference = 31.415000000000003
Formatted strings or f-strings were introduced in Python 3.6. An f-string is a string literal that
is prefixed with “f”. These strings may contain replacement fields, which are expressions
enclosed within curly braces {}. The expressions are replaced with their values. Specify the name TYPE CONVERSIONS
of the variable inside the curly braces to display its value. An f at the beginning of the string tells Type conversion is explicitly cast, or converts a variable from one type to another.
Python to allow any currently valid variable names within the string.

The int() Function


Program to Demonstrate the Use of f-strings with print() Function To explicitly convert a float number or a string to an integer, convert the number using int()
country = input("Which country do you live in?") function.
print(f " I live in {country}")

Program to demonstrate int() Casting Function


Output a = int (3.5)
Which country do you live in? India b = int ("1") #number treated as string
I live in India print(f "After Float to Integer Casting the result is {a}")
print(f "After String to Integer Casting the result is {b}")
Input string is assigned to variable country , the character f prefixed before the quotes and the
variable name is specified within the curly braces. Output
After Float to Integer Casting the result is 3
After String to Integer Casting the result is 1

. Page 19 . Page 20
Python Programming Python Programming

The float () Function Output


The float () function returns a floating point number constructed from a number or string. Equivalent Character for ASCII value of 100 is d

Program to demonstrate float() Casting Function


The complex() Function
x = float(4)
complex () function to print a complex number with the value real + imag*j or convert a string or
y = float("1") #number treated as string
number to a complex number. If the first argument for the function is a string, it will be
print(f"After Integer to Float Casting the result is {x}")
interpreted as a complex number and the function must be called without a second parameter. The
print(f"After String to Float Casting the result is {y}")
second parameter can never be a string. Each argument may be any numeric type (including
complex). If imag is omitted, it defaults to zero and the function serves as a numeric conversion
Output
function like int(), long() and float(). If both arguments are omitted, the complex() function
After Integer to Float Casting the result is 4.0
returns 0j.
After String to Float Casting the result is 1.0

The str() Function Program to demonstrate complex() Casting Function

The str() function returns a string which is fairly human readable. complex_with_string = complex("1")
complex_with_number = complex(5, 8)
Program to demonstrate str() Casting Function print(f"Result after using string in real part {complex_with_string}")
s = str(8) print(f"Result after using numbers in real and imaginary part {complex_with_number}")
r = str(3.5)
print (f "After Integer to String Casting the result is {s}") Output
print (f "After Float to String Casting the result is {r}") Result after using string in real part (1+0j)
Result after using numbers in real and imaginary part (5+8j)
Output
After Integer to String Casting the result is 8 The ord() Function
After Float to String Casting the result is 3.5 The ord() function returns an integer representing Unicode code point for the given Unicode
character.
The chr() Function
Program to demonstrate ord() Casting Function
It convert an integer to a string of one character whose ASCII code is same as the integer. The
I = ord('4')
integer value should be in the range of 0–255.
A = ord("Z")
C = ord("#")
Program to demonstrate chr() Casting Function
con = chr(100) print(f" Unicode code point for integer value of 4 is {I}")

print(f 'Equivalent Character for ASCII value of 100 is {con}') print(f" Unicode code point for alphabet 'Z' is {A}")
print(f" Unicode code point for character '$' is {C}")
. Page 21 . Page 22
Python Programming Python Programming

Output type(6.4) // It is of type <class 'float'>


Unicode code point for integer value of 4 is 52 type("A") // It is of type <class 'str'>
Unicode code point for alphabet 'A' is 90 type(True) // It is of type <class 'bool>
Unicode code point for character '$' is 35
CONTROL FLOW STATEMENTS
The hex() Function
Python supports a set of control flow statements. The statements inside your Python program are
It Converts an integer number (of any size) to a lowercase hexadecimal string prefixed with “0x”
generally executed sequentially from top to bottom, and decision making and looping control
using hex() function.
flow statements.
The control flow statements in Python Programming are
Program to demonstrate hex() Casting Function
int_to_hex = hex(255)  Sequential Control Flow Statements: This refers to the line by line execution, in which the
print(f"After Integer to Hex Casting the result is {int_to_hex}") statements are executed sequentially
 Decision Control Flow Statements: Depending on whether a condition is True or False, the
Output
decision structure may skip the execution of an entire block of statements or even execute one
After Integer to Hex Casting the result is 0xff
block of statements instead of other.
Ex: if, if…else and if…elif…else
The oct() Function
 Loop Control Flow Statements: This is a control structure that allows the execution of a
It converts an integer number (of any size) to an octal string prefixed with “0o” using oct()
block of statements multiple times until a loop termination condition is met. Loop Control
function.
Flow Statements are also called Repetition statements or Iteration statements.
Ex: for loop and while loop.
Program to demonstrate oct() Casting Function
int_to_oct = oct(255)
1. The if Decision Control Flow Statement
print(f"After Integer to Hex Casting the result is {int_to_oct}")
The syntax for if statement is,
if Expression:
Output
statement (s)
After Integer to Hex Casting the result is 0o377

The if decision control flow statement starts with if keyword and ends with a colon. The
The type() Function
expression in an if statement should be a Boolean expression. If the Boolean expression evaluates
The syntax for type() function is,
to True then statements in the if block will be executed; otherwise the result is False then none of
type(object) the statements are executed.
The type() function returns the data type of the given object.
In Python, the if block statements are determined through indentation and the first unindented
Ex: type(1) // It is of type <class 'int'> statement marks the end.

. Page 23 . Page 24
Python Programming Python Programming

Ex: if 20 > 10: OUTPUT


print(f"20 is greater than 10") Enter a number: 45
45 is Odd number
Program Reads a Number and Prints a Message If It Is Positive
number = int(input("Enter a number:"))
3. The if…elif…else Decision Control Statement
if number > = 0:
The if…elif…else is also called as multi-way decision control statement. When you need to
print(f"The number entered by the user is a positive number")
choose from several possible alternatives, then an elif statement is used along with an If statement.
The keyword ‘elif’ is short for ‘else if’ and is useful to avoid excessive indentation. The else
Output
statement act as the default action.
Enter a number: 67
The syntax for if…elif…else statement is,
The number entered by the user is a positive number

2. The if…else Decision Control Flow Statement if Expression_1:


An if statement is followed by an else statement. An else statement does not have any statement_1
condition. Statements in the if block are executed if the Expression is True. If it is false the else elif Expression_2:
block statement will execute. statement_2
The if…else statement allows for a two-way decision. elif Expression_3:

if Expression: statement_3

statement_1 :
else: :

statement_2 :
If the Expression evaluates to True, then statement_1 is executed, otherwise it is evaluated to else:
False then statement_2 is executed. Indentation is used to separate the blocks. After the execution statement_last
of either statement_1 or statement_2, the control is transferred to the next statement Also, if and
else keywords should be aligned at the same column position. This if…elif…else decision control statement is executed as follows:
 In the case of multiple expressions, only the first logical expression evaluates to True will

Program to Find If a Given Number Is Odd or Even be executed.

number = int(input("Enter a number"))  If Expression_1 is True, then statement_1 is executed.

if number % 2 = = 0:  If Expression_1 is False and Expression_2 is True, then statement_2 is executed.

print(f"{number} is Even number")  If Expression_1 and Expression_2 are False and Expression_3 is True, then statement_3 is

else: executed and so on.

print(f"{number} is Odd number")  If none of the Boolean_Expression is True, then statement_last is executed.

. Page 25 . Page 26
Python Programming Python Programming

Write a Program to Prompt for a Score between 0.0 and 1.0. If the Score Is Out of Range, The syntax of the nested if statement is,
Print an Error. If the Score Is between 0.0 and 1.0, Print a Grade Using the Following Table
if Expression_1:
Score Grade
if Expression_2:
>= 0.9 A
statement_1
>= 0.8 B
else:
>= 0.7 C
statement_2
>= 0.6 D
else:
< 0.6 F
statement_3

If the Expression_1 is evaluated to True, then the control shifts to Expression_2 and if the
score = float(input("Enter your score")) expression is evaluated to True, then statement_1 is executed, if the Expression_2 is evaluated to
if score < 0 or score > 1: False then the statement_2 is executed. If the Expression_1 is evaluated to False, then
print('Wrong Input') statement_3 is executed.
elif score >= 0.9:
print('Your Grade is "A" ') Program to Check If a Given Year Is a Leap Year
elif score >= 0.8:
year = int(input('Enter a year'))
print('Your Grade is "B" ')
if year % 4 = = 0:
elif score >= 0.7:
if year % 100 = = 0:
print('Your Grade is "C" ')
if year % 400 = = 0:
elif score >= 0.6:
print(f'{year} is a Leap Year')
print('Your Grade is "D" ')
else:
else:
print(f'{year} is not a Leap Year')
print('Your Grade is "F" ')
else:
print(f'{year} is a Leap Year')
OUTPUT
else:
Enter your score 0.92
print(f'{year} is not a Leap Year')
Your Grade is "A"

4. Nested if Statement
Output
An if statement that contains another if statement either in its if block or else block is called a
Enter a year 2014
Nested if statement.
2014 is not a Leap Year

. Page 27 . Page 28
Python Programming Python Programming

5. The for Loop Program to demonstrate for Loop Using range() Function
The syntax for the for loop is, print("Only ''stop'' argument value specified in range function")
for iteration_variable in sequence: for i in range(3):
statement(s) print(f"{i}")
The for loop starts with for keyword and ends with a colon. iteration_variable can be any valid print("Both ''start'' and ''stop'' argument values specified in range function")
variable name and first item in the sequence gets assigned to the iteration variable. This process of for i in range(2, 5):
assigning items from the sequence to the iteration_variable and then executing the statement print(f"{i}")
continues until all the items in the sequence are completed. print("All three arguments ''start'', ''stop'' and ''step'' specified in range function")
Ex: for each_character in "Blue": for i in range(1, 8, 3):
print(f "Iterate through character {each_character} in the string 'Blue'") print(f"{i}")

Output OUTPUT
Iterate through character B in the string 'Blue' Only ''stop'' argument value specified in range function
Iterate through character l in the string 'Blue' 0
Iterate through character u in the string 'Blue' 1
Iterate through character e in the string 'Blue' 2
Both ''start'' and ''stop'' argument values specified in range function
range() function 2
It is a built-in function, it is useful in for loop. The range() function generates a sequence of 3
numbers which can be iterated through using for loop. 4
All three arguments ''start'', ''stop'' and ''step'' specified in range function
The syntax for range() function is,
1
range([start ,] stop [, step])
4
Both start and step arguments are optional and the range argument value should always be an 7
integer. exit() function
start → value indicates the beginning of the sequence. If the start argument is not specified, then The exit() is defined in site module. It is built-in function to quit and come out of the execution
the sequence of numbers starts from zero by default. loop of the program.
stop → Generates numbers up to this value but not including the number itself.
Ex: for i in range(10):
step → indicates the difference between every two consecutive numbers in the sequence. The step
if i = = 5:
value can be both negative and positive but not zero.
exit()
print(i)

. Page 29 . Page 30
Python Programming Python Programming

OUTPUT Write a Program to Find the Average of n Natural Numbers Where n Is the Input from the
0 User
1 number = int(input("Enter a number up to which you want to find the average"))
2 i=0
3 sum = 0
4 count = 0
while i < number:
6. The while Loop i=i+1
The syntax for while loop is, sum = sum + i6
while Expression: count = count + 1
statement(s) average = sum/count
The while loop starts with the while keyword and ends with a colon. A while statement expression print(f"The average of {number} natural numbers is {average}")
is evaluated, if the expression evaluates to True, the statement in while loop block is executed and
loop is iterated till the condition becomes false. Execution then continues with the first statement OUTPUT
after the while loop. Enter a number up to which you want to find the average 5
The average of 5 natural numbers is 3.0
Ex: i = 0
while i < 5: 7. The continue and break Statements
print(f"Current value of i is {i}") The break and continue statements provide greater control over the execution of code in a
i=i+1 loop. Both continue and break statements can be used in while and for loops.

OUTPUT: break statement:


Current value of i is 0 It terminates the current loop and resumes execution at the next statement. The break statement
Current value of i is 1 can be used in both while and for loops.
Current value of i is 2 If you are using nested loops, the break statement stops the execution of the innermost loop and
Current value of i is 3 start executing the next line of code after the block.
Current value of i is 4 The syntax for a break statement in Python is

break

. Page 31 . Page 32
Python Programming Python Programming

Program to Demonstrate Infinite while Loop and break PYTHON LIBRARIES


n=0 Python Module is a file that contains some definition and statements. Set of modules that are pre-
while True: installed in python known as standard library.
print(f"The latest value of n is {n}") Ex: datetime, math, random, os, string, calendar etc.
n= n+ 1 We can import the definitions inside a module to another module or the Interactive interpreter in
if n > 5: Python.
print(f"The value of n is greater than 5") Syntax; import module name.
break Ex: import math

OUTPUT Write a python program to display date, time


The latest value of n is 0 import datetime
The latest value of n is 1 a=datetime.datetime(2019,5,27,6,35,40)
The latest value of n is 2 print(a)
The latest value of n is 3
The latest value of n is 4 OUTPUT
The latest value of n is 5 2019-05-27 06:35:40
The value of n is greater than 5

continue statement: Write a python program to display calendar

continue statement is useful to skip the execution of the current iteration of the loop and continue import calendar

to the next iteration. print(calendar.month(2023, 5))

The syntax of the continue statement in python.


May 2023
continue
Mo Tu We Th Fr Sa Su
Program to Demonstrate continue Statement
1 2 3 4 5 6 7
for x in range(5):
8 9 10 11 12 13 14
if x = = 3:
15 16 17 18 19 20 21
continue
22 23 24 25 26 27 28
print(x)
29 30 31
OUTPUT
0
1
2
4
. Page 33 . Page 34
Python Programming Python Programming

Write a python program to print absolute value, square root and cube of a number. OUTPUT
import math Absolute value of -20 is: 20
def cube(x):
A Few Built-in Functions in Python are as shown in table below.
return x**3
a= -100
Function
print(“a = ”,a) Syntax Explanation
a=abs(a) Name

print(a) abs(x), where x is an integer or The abs() function returns the absolute
abs()
print("Square root of",a,"=", math.sqrt(a)) floating-point number. value of a number. Ex: abs(-3) = 3
print("Cube of", a,"=", cube(a)) min(arg_1, arg_2, arg_3,…, arg_n) The min () function returns the smallest of
min() where arg_1, arg_2, arg_3 are the two or more arguments.
OUTPUT
arguments. Ex: min(1, 2, 3, 4, 5) = 1
a = -100
max(arg_1, arg_2, arg_3,…,arg_n) The max () function returns the largest of
100
max() where arg_1, arg_2, arg_3 are the two or more arguments.
Square root of 100 = 10.0
arguments. Ex: max(4, 5, 6, 7, 8) = 8
Cube of 100 = 1000000
The pow(x, y) function returns x to the
pow() pow (x, y) where x and y are numbers.
PYTHON FUNCTIONS power y. Ex: pow(3, 2) = 9
Function is a group of related statements that perform a specific task. Functions help break our The len() function returns the length or
len(s) where s may be a string, byte,
program into smaller and modular chunks. As our program grows larger and larger, functions len() the number of items in an object.
list, tuple, range, dictionary or a set.
make it more organized and manageable. It avoids repetition and makes code reusable. Ex: len("Japan") = 5
Basically, we can divide functions into the following two types: The divmod() function takes two numbers
divmod(a, b) where a and b are
1. Built-in Function as arguments and return a pair of numbers
divmod() numbers representing numerator and
2. User defined Function consisting of their quotient and remainder.
denominator.
Ex: divmod (5, 2) = (2, 1)
1. Built-in functions
Functions that are built or predefined into Python.
2. User-defined functions - User-defined functions are reusable code blocks created by users to
Ex: abs (), all (), asci (), bool () etc.
perform some specific task in the program.
The syntax for function definition is,
Ex:
integer = -20 def function_name(parameter_1, parameter_2, …, parameter_n):

print("Absolute value of -20 is:", abs(integer)) statement(s)


A function definition consists of the def keyword, followed by
. Page 35 . Page 36
Python Programming Python Programming

 The function’s name is same naming rules as variables: use letters, numbers, or an underscore, variable to have a string value "__main__". Block of statements in the function definition is
but the name cannot start with a number. Also, you cannot use a keyword as a function name. executed when the function is called.
 A list of parameters to the function are enclosed in parentheses and separated by commas.
if __name == "__main__":
Functions may have one or more parameters or any parameters.
statement(s)
 A colon is required at the end of the function header. The first line of the function definition
which includes the name of the function is called the function header. The special variable, __name__ with "__main__", is the entry point to your program. When

 Block of statements that define the body of the function start at the next line of the function Python interpreter reads the if statement and sees that __name__ does equal to "__main__", it will

header and they must have the same indentation level. execute the block of statements present there.

Program to Find the Area of Trapezium


FUNCTION CALLING
def area_trapezium(a, b, h):
Calling the function actually performs the specified actions with the indicated parameters. The area = 0.5 * (a + b) * h
syntax for function call or calling function is, print(f"Area of a Trapezium is {area}")

function_name( ); / / Without parameter def main():


area_trapezium(10, 15, 20)
function_name(argument_1, argument_2,…,argument_n) / / With parameter if __name__ == "__main__":

Arguments or parameters are the actual value that is passed into the calling function. There must main()

be a one to one correspondence between the formal parameters in the function definition and the
actual arguments of the calling function. A function should be defined before it is called and the PASSING PARAMETER/ARGUMENTS

block of statements in the function definition are executed only after calling the function. A function can take parameters nothing but some values that are passed to it so that function can
manipulate them to produce the desired result. These parameter are normal variables are defined
Ex : def my_function():
when we call the function and passed to the function.
print("Hello from a function")
my_function() //Function Call  Parameters are specified within the pair of parenthesis in the function definition.
 The function name and number of parameter in the function call must be same that given
Function definitions do not alter the flow of execution of the program. When you call a function,
in the function definition otherwise error will be returned.
the control flows from the calling function to the function definition. Once the block of statements
in the function definition is executed, then the control flows back to the calling function and Ex: def area_trapezium(a, b, h):

proceeds with the next statement. area = 0.5 * (a + b) * h


print(f"Area of a Trapezium is {area}")
The Python interpreter automatically defines few special variables. If the Python interpreter is
area_trapezium(10, 15, 20) //Passing Parameter
running the source program as a stand-alone main program, it sets the special built-in __name__

. Page 37 . Page 38
Python Programming Python Programming

THE RETURN STATEMENT Program to Check If a 3 Digit Number Is Armstrong Number or Not
The function to perform its specified task to calculate a value and return the value to the calling user_number = int(input("Enter a 3 digit positive number to check for Armstrong number"))
function so that it can be stored in a variable and used later. This can be achieved using the def check_armstrong_number(number): //Function Definition
optional return statement in the function definition. result = 0
The syntax for return statement is, temp = number
while temp != 0:
return [expression_list]
last_digit = temp % 10
The return statement terminates the execution of the function definition in which it appears and result += pow(last_digit, 3)
returns control to the calling function. A function can return only a single value, but that value can temp = int(temp / 10)
be a list or tuple. if number = = result:
print(f"Entered number {number} is a Armstrong number")

Program to write sum, different, product and mod using arguments with return value else:
function. print(f"Entered number {number} is not a Armstrong number")
def calculate(a,b): def main():
total = a+b check_armstrong_number(user_number) //Function Call
diff = a-b if __name__ == "__main__":
prod = a*b main()
div = a/b
mod = a%b DEFAULT PARAMETERS
return total, diff, prod, div, mod //return statement It is useful to set a default value to the parameters of the function definition. Each default
a = int(input("Enter a value")) parameter has a default value as part of its function definition. Any calling function must provide
b = int(input("Enter b value")) arguments for all required parameters in the function definition but can omit arguments for
s,d,p,q,m = calculate(a,b) // function call with parameter default parameters. If no argument is sent for that parameter, the default value is used.
print("Sum=",s,"diff= ",d,"mul= ",p,"div= ",q,"mod= ",m) Usually, the default parameters are defined at the end of the parameter list, after any required
parameters and non-default parameters cannot follow default parameters. The default value is
OUTPUT evaluated only once.
Enter a value 6
Enter b value 8 Program to Demonstrate the Use of Default Parameters
Sum= 14 diff= -2 mul= 48 div= 0.75 mod= 6 def area(a, b=30):
print(f"{a} {b}")
area(10, 20)
area(10)
. Page 39 . Page 40
Python Programming Python Programming

OUTPUT print("\nName of Python script:", sys.argv[0])


10 20 print("\nArguments passed:", end = " ")
10 30 for i in range(1, n):
print(sys.argv[i], end = " ")
KEYWORD ARGUMENTS
We can explicitly specify the argument name along with their value in the form kwarg = value. In OUTPUT
the calling function, keyword arguments must follow positional arguments. All the keyword Prg.py 2 5 6 7
arguments passed must match one of the parameters in the function definition and their order is Total arguments passed:5
not important. No parameter in the function definition may receive a value more than once. Name of Python script:Prg.py
Arguments passed:2 5 6 7
Program to Demonstrate the Use of Keyword Arguments
def printinfo( name, age ):
SCOPE AND LIFETIME OF VARIABLES
print( "Name: ", name)
Python programs have two scopes: global and local.
print( "Age: ", age)
 A variable is a global variable if its value is accessible and modifiable throughout your
return;
program. Global variables have a global scope.
printinfo( age=50, name="miki" ) // Keyword Argument
 A variable that is defined inside a function definition is a local variable. The lifetime of a
variable refers to the duration of its existence. The local variable is created and destroyed
OUTPUT
every time the function is executed, and it cannot be accessed by any code outside the
Name:miki
function definition. Local variables inside a function definition have local scope and exist
Age:50
as long as the function is executing.
 It is possible to access global variables from inside a function, as long as you have not
COMMAND LINE ARGUMENTS
defined a local variable with the same name.
A Python program can accept any number of arguments from the command line. Command line
arguments is a methodology in which user will give inputs to the program through the console  A local variable can have the same name as a global variable, but they are totally different

using commands. import sys module is used to access command line arguments. All the command so changing the value of the local variable has no effect on the global variable. Only the

line arguments in Python can be printed as a list of string by executing sys.argv. local variable has meaning inside the function in which it is defined.

Syntax: Program. py arg_1 arg_2 arg_3


Program to Demonstrate the Scope of Variables
Program to demonstrate the command line argument test_variable = 5
import sys def outer_function():
n = len(sys.argv) test_variable = 60
print("Total arguments passed:", n) def inner_function():

. Page 41 . Page 42
Python Programming Python Programming

test_variable = 100 EXCEPTIONAL HANDLING


print(f"Local variable value of {test_variable} having local scope to inner function is TYPES OF ERRORS
displayed") There are two distinguishable kinds of errors
inner_function() 1. Syntax Errors
print(f"Local variable value of {test_variable} having local scope to outer function is displayed ") 2. Exceptions
outer_function()
1. Syntax Errors
print(f"Global variable value of {test_variable} is displayed ")
Syntax errors also known as parsing errors, this error occurs during the time of compiling
when the syntax is incorrect.
OUTPUT
Ex: missing semi-colon, spelling mistakes, syntactic mistake etc.
Local variable value of 100 having local scope to inner function is displayed
Ex: while True
Local variable value of 60 having local scope to outer function is displayed
print("Hello World)
Global variable value of 5 is displayed
OUTPUT
RECURSIVE FUNCTION File "<ipython-input-3-c231969faf4f>", line 1
It is even possible for the function to call itself. A function that calls itself are termed as recursive while True // SyntaxError: invalid syntax
functions. ^ // The error is caused by a missing colon (':').
For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Following is an example of recursive function to find the factorial of an integer. EXCEPTIONS
Errors detected during execution are called exceptions. An exception is an unwanted event that
Program to calculate the factorial of a number using recursion
interrupts the normal flow of the program. When an exception occurs in the program, execution
def fact(n):
gets terminated.
if(n==1 or n==0):
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is
return 1
made to execute it. In such cases, we get a system-generated error message.
else:
However, these exceptions can be handled in Python.
return n*fact(n-1)
Exceptions can be either built-in exceptions or user-defined exceptions. The interpreter or built-in
n=int(input("enter the value of n:"))
functions can generate the built-in exceptions while user-defined exceptions are custom
print("the factorial of ",n,"is",fact(n))
exceptions created by the user.
When the exceptions are not handled by programs it results in error messages as shown below.
OUTPUT
enter the value of n: 3 Ex: 110 * (1/0) // ZeroDivisionError: division by zero
the factorial of 3 is 6 4 + spam*3 // NameError: name 'spam' is not defined
'2' + 2 // TypeError: Can't convert 'int' object to str implicitly

. Page 43 . Page 44
Python Programming Python Programming

EXCEPTION HANDLING USING TRY…EXCEPT…FINALLY The try…except statement has an optional else block, which, when present, must follow all except
Handling of exception ensures that the flow of the program does not get interrupted when an blocks. It is useful for code that must be executed if the try block does not raise an exception.
exception occurs which is done by trapping run-time errors. Handling of exceptions results in the
Instead of having multiple except blocks with multiple exception names for different exceptions,
execution of all the statements in the program.
we can combine multiple exception names together separated by a comma (also called
It is possible to write programs to handle exceptions by using try…except…finally statements.
parenthesized tuples) in a single except block.
The syntax for try…except…finally are as follows
The syntax for combining multiple exception names in an except block is,
try:
try:
statement_1
statement_1
except Exception_Name_1:
except (Exception_Name_1, Exception_Name_2, Exception_Name_3):
statement_2
statement(s)
If any statement within the try block throws an exception, control immediately shifts to except where Exception_Name_1, Exception_Name_2 and Exception_Name_3 are different exception
block. If no exception is thrown in the try block, the except block is skipped. names

try block with multiple exception: Multiple except blocks with different exception names can be A finally block is always executed before leaving the try statement, whether an exception has

chained together. The except blocks are evaluated from top to bottom in code, but only one except occurred or not. When an exception has occurred in the try block and has not been handled by an

block is executed for each exception that is thrown. The first except block that specifies the exact except block, it is re-raised after the finally block has been executed. The finally clause is also

exception name of the thrown exception is executed. executed “on the way out” when any other clause of the try statement is left via a break, continue

If no except block specifies a matching exception name then an except block that does not have or return statement.

an exception name is selected, if one is present in the code. Program to Check for ValueError Exception
while True:
try:
try:
statement_1
number = int(input("Please enter a number: "))
except Exception_Name_1:
print(f"The number you have entered is {number}")
statement_2
break
except Exception_Name_2:
except ValueError:
statement_3
print("Oops! That was no valid number. Try again…")

OUTPUT
else:
Please enter a number: g
statement_4
Oops! That was no valid number. Try again…
finally:
Please enter a number: 4
statement_5
The number you have entered is 4

. Page 45 . Page 46
Python Programming

PROGRAM TO CHECK FOR ZERO DIVISION ERROR EXCEPTION


x = int(input("Enter value for x: "))
y = int(input("Enter value for y: "))
try:
result = x / y
except ZeroDivisionError:
print("Division by zero!")
else:
print(f"Result is {result}")
finally:
print("Executing finally clause")

OUTPUT
Case 1
Enter value for x: 8
Enter value for y: 0
Division by zero!
Executing finally clause

Case 2
Enter value for x: p
Enter value for y: q
Executing finally clause

. Page 47

You might also like