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

Python

The document provides an overview of machine language, programming languages, and specifically Python programming. It explains the types of programming languages, including low-level, high-level, and middle-level languages, along with their advantages and examples. Additionally, it covers Python's features, character set, tokens, literals, and operators, highlighting its ease of use and integration with other languages.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python

The document provides an overview of machine language, programming languages, and specifically Python programming. It explains the types of programming languages, including low-level, high-level, and middle-level languages, along with their advantages and examples. Additionally, it covers Python's features, character set, tokens, literals, and operators, highlighting its ease of use and integration with other languages.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 150

Python Programming

Introduction

N Manjunath Gowda
Asst. Professor
Department of Mechanical Engineering
University BDT College of Engineering, Davangere.
What is Machine Language?

 Machine language is a low-level language made up of


binary numbers or bits that a computer can understand.
 It is also known as machine code or object code and is
extremely tough to comprehend.
 The only language that the computer understands is
machine language, as it is a digital device.
 In the computer, all data like videos, programs,
pictures are represented in binary.
 The CPU processes this machine code or binary data
as input.
 Then, an application or operating system gets the
resulting output from the CPU and displays it visually.
 Computers work in binary code. Information is coded
using 0s and 1s. Each 0 or 1 is called a bit.
 ASCII is an 8-bit code.
 Eight bits are called a byte. A binary code with eight

digits, such as 1101 10112, can be stored in one byte


of computer memory.
 The word "CAT" in a word processor becomes

0100 00112, 0100 00012 , and 0101 01002


Bit - a value of either a 1 or 0
Nibble - 4 bits
Byte - 8 bits 1 character, e.g., "a", is one byte.

Kilobyte - 1,024 bytes 2 or 3 paragraphs of text.

Megabyte - 1,024 kilobytes 873 pages of plain text


(1,200 characters).
4 books
(200 pages or 240,000 characters).
Gigabyte -1,024 megabytes
Terabyte - 1,024 gigabytes,

Petabyte (PB) Exabyte (EB) Zettabyte (ZB) Yottabyte (YB)


AS
CII
CO
DE
What is Programming Language?

It is a computer language that is used by programmers


(developers) to communicate with computers. It is a set
of instructions written in any specific language to
perform a specific task.
Types of programming language
I. Low-level programming language

Low-level language is machine-dependent (0s and 1s)


programming language. The processor runs low- level programs
directly without the need of a compiler or interpreter, so the
programs written in low-level language can be run very fast.

Low-level language is further divided into two parts :


a. Machine Language

 Machine language is a type of low-level programming language.


It is also called as machine code or object code.
 It does not require a translator to convert the programs because
computers directly understand the machine language programs.
 The advantage of machine language is that it helps the
programmer to execute the programs faster than the high-level
programming language.
Example:
Say that a light bulb is controlled by a processor running a program in main
memory. The controller can turn the light bulb fully on and fully off, can brighten or
dim the bulb (but not beyond fully on or off.)

Machine Instruction Machine Operation


00000000 Stop Program
00000001 Turn bulb fully on
00000010 Turn bulb fully off
00000100 Dim bulb by 10%
00001000 Brighten bulb by 10%
00010000 If bulb is fully on, skip over next instruction
00100000 If bulb is fully off, skip over next instruction
01000000 Go to start of program (address 0)
b. Assembly Language

 Assembly language (ASM) is also a type of low-level


programming language that is designed for specific processors.
 Assembly Language is expressed in a more human readable form
than the binary instructions and names are allowed for memory
locations, registers, operations etc.
 It uses an assembler to convert the assembly language to
machine language.
 The advantage of assembly language is that it requires less
memory and less execution time to execute a program.
Example:
In this example of an assembly language, "1:" is the label which lets the
computer know where to begin the operation. The "MOV" is the
mnemonic command to move the number "3" into a part of the
computer processor, which can function as a variable. "EAX," "EBX" and
"ECX" are the variables. The first line of code loads "3" into the register
"eax." The second line of code loads "4" into the register "ebx." Finally,
the last line of code adds "eax" and "ebx" and stores the result of the
addition, which is seven, in "ecx."
Altogether, this assembly language looks like this:

1: MOV eax, 3
MOV ebx, 4
ADD eax, ebx, ecx
II. High-level programming language
 High-level programming language (HLL) is designed for
developing user-friendly software programs and websites.
 This programming language requires a compiler or interpreter
to translate the program into machine language (execute the
program).
 The main advantage of a high-level language is that it is easy to
read, write, and maintain.
 High-level programming language includes Python, Java,
JavaScript, PHP, C#, C++, Objective C, Cobol, Perl, Pascal, LISP,
FORTRAN, and Swift programming language.

A high-level language is further divided into three parts :


a. Procedural Oriented programming language

 Procedural Oriented Programming (POP) language is derived


from structured programming and based upon the procedure call
concept. It divides a program into small procedures called
routines or functions.
 Procedural Oriented programming language is used by a software
programmer to create a program that can be accomplished by
using a programming editor like IDE, Adobe Dreamweaver, or
Microsoft Visual Studio.
 The advantage of POP language is that it helps programmers to
easily track the program flow and code can be reused in different
parts of the program.

Example: C, FORTRAN, Basic, Pascal, etc...


b. Object-Oriented Programming language

 Object-Oriented Programming (OOP) language is based upon the


objects.
 In this programming language, programs are divided into small
parts called objects.
 It is used to implement real-world entities like inheritance,
polymorphism, abstraction, etc in the program to makes the
program reusable, efficient, and easy-to-use.
 The main advantage of object-oriented programming is that OOP
is faster and easier to execute, maintain, modify, as well as
debug.
Example: C++, Java, Python, C#, etc.
c. Natural language

 Natural language is a part of human languages such as English,


Russian, German, and Japanese.
 It is used by machines to understand, manipulate, and
interpret human's language.
 It is used by developers to perform tasks such as translation,
automatic summarization, Named Entity Recognition (NER),
relationship extraction, and topic segmentation.
 The main advantage of natural language is that it helps users
to ask questions in any subject and directly respond within
seconds.
III. Middle-level programming language

Middle-level programming language lies between the low-level


programming language and high-level programming language.
It is also known as the intermediate programming language and
pseudo-language.
A middle-level programming language's advantages are that it
supports the features of high-level programming, it is a user-
friendly language, and closely related to machine language and
human language.
Example: C, C++, language
Processing of C Program
Processing of C Program
Processing of Python Program
Python

Python is an interpreted, high level, general purpose


programming language. It is dynamically typed and
garbage collected.
Advantages
 Python is easy to read, easy to understand, and easy to write.
 It integrates with other programming languages like C, C++, and Java.
 Python executes code line-by-line, so it is easy for the programmer to
find the error that occurred in the code.
 Python is platform-independent means you can write code once and
run it anywhere.
Disadvantages
 Python is not suitable for developing mobile applications and games.
 Python works with the interpreter. That's why it is slower than other
programming languages like C and C++.
Brief History of Python

 Invented in the Netherlands, early 90’s by Guido van Rossum


 Named after Monty Python
 Open sourced from the beginning
 Considered a scripting language, but is much more
 Scalable, object oriented and functional from the beginning
 Used by Google from the beginning
 Increasingly popular
Python Character Set
What is Character Set?
Character set is a bunch of identifying elements in the
programming language.

PYTHON
CHARACTER
SET

• Letters:- A-Z, a-z


• Digits:- 0 to 9
• Special Symbols:- space + - / ( ) [ ] = ! = < > , ‘ “ $ # ; : ? &
• White Spaces:- Blank Space , Horizontal Tab, Vertical tab,
Carriage Return.
• Other Characters:- Python can process all 256 ASCII and
Unicode Characters.
Python Token or lexical unit
What is Token?
Individual elements that are identified by programming
language are called tokens or lexical unit.

Key
Words

Punctuators Identifiers

TOKENS

Operators Literals
Key word
Keyword
Keywords are also called as reserved words, these are having special meaning in
python language. The words are defined in the python interpreter hence these
cant be used as programming identifiers.

and assert global if


break class import in
continue def is lambda
del elif not or
else except pass print
exec finally raise return
for from try while
with yield
Example:

var = 1;

if(var==1):
print("odd")
else:
print("even")
Identifier
Identifier or Python Variables
Python variables are nothing but the reserved memory locations to store the
values. In other words, it is the name of the memory location where the data is
stored. And if once the variable is stored a separate space is allocated in the
memory.

Example:

a = 100
print(a)
a 100
Rules of Defining Variable

SOME INVALID IDENTIFIERS


MY-REC 28dre break
elif false del
Literals
Literals (Data Types)
Literals are also called as constants or constant values, these are the values
which never change during the execution of program.
Numerical Literals
int (Integer)
float

Exponent Form: It consists of two parts Mantissa and Exponent. for example 5.8
can be represented as 0.58 x 10-1 = 0.58E01. where mantissa part is 0.58 and E01 is
Strings
str (String)
Sequence of letters enclosed in quotes is called string or string literal or
constant.
Single Line Strings
Strings created using single quote or double quote, end in one line are called
single line strings.

Example: Item=“Computer”
Or Item= ‘Computer’
Multi Line Strings
A multiline string in Python begins and ends with either three single quotes or three
double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are
considered part of the string. Python’s indentation rules for blocks do not apply to lines
inside a multiline string.
Example:

Output
The following print() call would print identical text but doesn’t use a multiline
string:
Booleans
Boolean
Special Literal
Special Literal

The None literal is used to indicate absence of value.


For example: val = None
Literal Collections
Literal Collections

Python supports literal collections also, such as tuple and lists ..etc
Operators
Operators
Operators are special symbols that perform operations on variables and values.

Types of Python Operators

 Arithmetic operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 Bitwise Operators
 Special Operators
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.

Operator Operation Example


+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2*3=6
/ Division 4/2=2
% Modulus / Remainder 5%2=1
** Power 4 ** 2 = 16
Integer Division /
// Floored Quotient 23 // 7 = 3
Example:

Output
Assignment Operators
Assignment operators are used to assign values to variables.

Operator Name Example


= Assignment Operator a=7
+= Addition Assignment a += 1 #a=a+1
-= Subtraction Assignment a -= 3 #a=a-3
*= Multiplication Assignment a *= 4 #a=a*4
/= Division Assignment a /= 3 #a=a/3
%= Remainder Assignment a %= 10 # a = a % 10
**= Exponent Assignment a **= 10 # a = a ** 10
Example:
Comparison Operators
Comparison operators compare two values/variables and return a Boolean result:
True or False.

Operator Meaning Example


== Is Equal To 3 == 5 gives us False
!= Not Equal To 3 != 5 gives us True
> Greater Than 3 > 5 gives us False
< Less Than 3 < 5 gives us True
>= Greater Than or Equal To 3 >= 5 give us False
<= Less Than or Equal To 3 <= 5 gives us True
Example:

Output

Comparison operators are used in decision-making and loops.


Logical Operators
Logical operators are used to check whether an expression is True or False.

a=5
b=6

print((a > 2) and (b >= 6)) # True

Operator Example Meaning


Logical AND:
and a and b True only if both the operands are True
Logical OR:
or a or b True if at least one of the operands is True
Logical NOT:
not not a True if the operand is False and vice-versa.
Example:
Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They
operate bit by bit, hence the name.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Operator Meaning Example


& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x << 2 = 40 (0010 1000)
Special operators
Python language offers some special types of operators like the identity operator
and the membership operator.
Identity operators
In Python, is and is not are used to check if two values are located on the same
part of the memory. Two variables that are equal does not imply that they are
identical.

Operator Meaning Example


True if the operands are identical
is x is True
(refer to the same object)
True if the operands are not identical
is not x is not True
(do not refer to the same object)
Example:

Here, we see that x1 and y1 are integers of the same values, so they are equal as
well as identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the
interpreter locates them separately in memory although they are equal.
Membership operators
In Python, in and not in are the membership operators. They are used to test
whether a value or variable is found in a sequence (string, list, tuple, set and
dictionary).
In a dictionary we can only test for presence of key, not the value.

Operator Meaning Example


True if value/variable is found in the
in 5 in x
sequence
True if value/variable is not found in the
not in 5 not in x
sequence
Example:

Output

Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similarly, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
Punctuators
Punctuators
Punctuators are also called as separators, They are used to organize the structures,
statements and expressions.

Brackets []
Parentheses ()
Braces {}
Comma ,
Semicolon ;
Colon :
Asterisk *
Ellipsis …
Equal Sign =
Pound Sign #
Comments
Comments are non executable statements in a program. In computer
programming, comments are hints that we use to make our code more
understandable.
Comments are completely ignored by the interpreter. They are meant for fellow
programmers.
Single-line Comment
A single-line comment starts and ends in the same line.
We use the # symbol to write a single-line comment.

Example:

Output

We can also use the single-line comment along with the code.
Multi-line Comment

Another way of doing this is to use triple quotes, either ''' or """
Use of Python Comment
1. Make Code Easier to Understand
If we write comments in our code, it will be easier for future reference.
Also, it will be easier for other developers to understand the code.
2. Using Comments for Debugging
If we get an error while running the program, we can comment the line of code
that causes the error instead of removing it. For example,

Here, print("Error Line) was causing an error so we have changed it as a comment.


Now, the program runs without any errors.
This is how comments can be a valuable debugging tool.
Debugging

It is the process of finding and fixing errors or bugs in the source


code of any software.
The debugging process typically requires the following steps.
Error identification
Developers, testers, and end-users report bugs they discover while testing or
using the software. Developers locate the exact line of codes or code module
causing the bug. This can be a tedious and time-consuming process.
Error analysis
Coders analyze the error by recording all program state changes and data values.
They also prioritize the bug fix based on its impact on software functionality. The
software team also identifies a timeline for bug fixing depending on
development goals and requirements.
Fix and validation
Developers fix the bug and run tests to ensure the software continues to work as
expected. They may write new tests to check if the bug recurs in the future.
Debugging & Testing
Debugging and testing are complementary processes that ensure software
programs run as they should. After writing a complete section or part of a
code, programmers test to identify bugs and errors. Once bugs are found,
coders can begin the process of debugging and work towards ridding software
of any errors.
Coding Errors in Python-Programming

Syntax Errors

Logical Errors
Syntax Errors
A syntax error is one of the most basic types of error in programming. Whenever
we do not write the proper syntax of the python programming language (or any
other language) then the python interpreter or parser throws an error known as a
syntax error. The syntax error simply means that the python parser is unable to
understand a line of code.

number = 100

if number > 50
print("Number is greater than 50!")
File "test.py", line 3
if number > 50
^
SyntaxError: invalid syntax

Since we have missed the colon (:) after the if statement.


Logical Errors (Runtime Errors)
Logical Errors are those errors that cannot be caught during compilation time.
As we cannot check these errors during compile time, we name
them exceptions. Since we cannot check the logical errors during compilation
time, it is difficult to find them.

number = 100
divided_by_zero = number / 0

print(divided_by_zero)
Traceback (most recent call last):
File "d:\test.py", line 2, in <module>
divided_by_zero = number / 0
ZeroDivisionError: division by zero

Zero Division Error is raised by the Python interpreter when we try to divide any number
by zero.
Dynamic Typing
Dynamic Typing
Dynamic typing means that the type of the variable is determined only during
runtime. A variable pointing to a value of certain type can be made to point to a
value/object of different type this is called Dynamic Typing.
x=10
Output will be
print(x)
10
x=“ Hello World”
Hello World
print(x)

Caution with Dynamic Typing

x = ‘day’
y = x/2 Error! String can not be divided.
Functions
Function
A function is a block of code(reusable) that performs a specific task.

Types of function
There are two types of function in Python programming:
Standard library functions - These are built-in functions in Python that are
available to use.
User-defined functions - We can create our own functions based on our
requirements.
Python Function Declaration
Function Header
The syntax to declare a function is:

def - keyword used to declare a function

function_name - any name given to the function

arguments - any value passed to function

return (optional) - returns value from a function


Example:
This functions has only
output, takes no input

Here, we have created a function named greet().


It simply prints the text Hello World!.
This function doesn't have any arguments and doesn't return any values.
Calling a function

Output
How it works?
 When the function is called, the control of the program goes to the function
definition.
 All codes inside the function are executed.
 The control of the program jumps to the next statement after the function call.
Python Function Arguments
If we create a function with arguments, we need to pass the corresponding
values while calling them.
Example:

We can also call the function by mentioning the argument name as:
Function return Type This functions has both
input and output

we have created a function named


find_square().
The function accepts a number and returns
the square of the number.
Example:
Temperature into Fahrenheit conversion using Functions
Temperature into Fahrenheit conversion using Functions
Python Library Functions
In Python, standard library functions are the built-in functions that can be used
directly in our program. For example,
 print() - prints the string inside the quotation marks
 sqrt() - returns the square root of a number
 pow() - returns the power of a number

These library functions are defined inside the module. And, to use them we must
include the module inside our program.
For example, sqrt() is defined inside the math module.
Example:

Output

Here, we have used


 math.sqrt(4) - to compute the square root of 4
 pow(2, 3) - computes the power of a number i.e. 23
Benefits of Using Functions
1. Code Reusable - We can use the same function multiple times in our program
which makes our code reusable. For example,

Output

In the above example, we have created the function named get_square() to


calculate the square of a number. Here, the function is used to calculate the
square of numbers from 1 to 3.
Hence, the same method is used again and again
2. Code Readability - Functions help us break our code into chunks to make our
program readable and easy to understand.
3. Simplifies Program Development- As each function is written separately,
they can be tested separately and hence the program development becomes
simple. Otherwise, big problem will have many lines of program, maintaining
that program will be a big mess.
4. Predefined and Tested- All the libraries contain predefined and tested
functions, which the programmers are free to use in their programs, without
worrying about the code details.
5. When a big program is broken down into smaller functions, then the
programmers working on that problem can divide the work load accordingly.
Modules
Module
The python modules are a type of a file, which contains statements and definitions. A
module is simply a Python file with a .py extension that can be imported inside another
Python program.

There are two types of python modules:


Built-in python modules
User-defined python modules

Advantages of modules
Reusability : Working with modules makes the code reusable.
Simplicity: Module focuses on a small proportion of the problem, rather than focusing on
the entire problem.
Scoping: A separate namespace is defined by a module that helps to avoid collisions
between identifiers.
Built-in modules
Python has a large number of built-in modules, which are used to make tasks easy and
more readable. These modules provide a wide range of functionality and are always
available for use without the need to install any additional packages.
A list of a few most frequently used built-in python modules is given below
math: This module is very useful to perform complex mathematical functions such as
trigonometric functions and logarithmic functions.
date: The date module can be used to work with date and time such as time, date, and
datetime.
os: Provides a way to interact with the underlying operating system, such as reading or
writing files, executing shell commands, and working with directories.
sys: Provides access to some variables used or maintained by the Python interpreter,
such as the command-line arguments passed to the script, the Python version, and the
location of the Python executable.
User-defined modules
User-defined python modules are the modules, which are created by the user to
simplify their project. These modules can contain functions, classes, variables, and
other code that you can reuse across multiple scripts.
Create a normal Import it in another
python file python file
Importing the whole module object using its original name

The first way is to use the import statement, using the syntax import module_name
>>> import math
We've just imported the math module. We can use the things within this module
by looking up attributes on the math module object.
For example, we can get the square root of a number by calling math.sqrt

>>> math.sqrt(25)

5.0
Or we can access the number π with math.pi

>>> math.pi

3.141592653589793

But we can't access just pi or sqrt (without that math. prefix). The reason is, when we import

a module using that import module_name syntax, we get just one thing:

a variable that points to a module object.


Importing specific things from a module

If you wanted to just type pi instead of math.pi, you could use the from syntax for importing:

>>> from math import pi

>>> pi

3.141592653589793
So now we have pi, but not sqrt (because we didn't import it).
If you want to import multiple things from a module using this from syntax,
you could put commas each thing you'd like to import:
>>> from math import pi, sqrt
>>> pi
3.141592653589793
>>> sqrt(25)
5.0
That from math import pi, sqrt line plucks out pi and sqrt from the math module, but nothing
else.
Importing specific things from a module, with as syntax

>>> from math import sqrt

>>> from cmath import sqrt as csqrt


So, sqrt is now the sqrt function from the math module and
csqrt is the one from the cmath module.

>>> sqrt(25)

5.0

>>> csqrt(25)

(5+0j)
Import the whole module and rename it

You can also use the as syntax when importing a whole module.
>>> import math as m
The variable m now points to the math module object which means we can't say math.pi
anymore:
>>> m.pi
3.141592653589793 >
>> m.sqrt(25)
5.0
from _module import * statement

You can import all attributes of a module using this statement.


This will make all attributes of imported module visible in your code.

from calculation import *


print(add(1,2))
print(sub(3,2))
Storing values in variables
A variable is like a box in the computer’s memory where you can store a single
value.
Values are stored in variables with an assignment statement.

Variable = Expression
 A variable is initialized (or created) the first time a value is stored in it.
 After that, you can use it in expressions with other variables and values.
 When a variable is assigned a new value , the old value is forgotten, which
is why spam evaluated to 42 instead of 40 at the end of the example. This
is called overwriting the variable.
Python allows multiple assignments

x, y = 10, 20 Binds x to 10 and y to 20

x is bound to 21 and y
x, y = 10, 20 to 11 at the end of the
x, y = y+1, x+1 program

Output
Output

Assigning different data types to variables

Output
Assigning different operation results to multiple variable

Output

Storing different characters in a different variables

Output
Local and Global Variables
Local and Global Variables

Variables that are created outside of the function are global variables.
Local variables are those which are defined inside a function and its scope limited to
that function only means local variables are accessible only inside the function. it
cannot be accessed anywhere outside the function.

Global Variables

Local Variable

Error
Global Variable

Global Variable

Local Variable

Error
Python Input Function
input()
The input() function takes input from the user and returns it.

Variable_to_hold_the_value = input(message)
input() function without prompt

Output

input() function with prompt

Output
The input() function always returns a string, even if the user enters a number.

Use the int() function to get the integer form of spam and then store this as the
new value in spam.

The int() function is also useful if you need to round a floating-point number down.
p = input(“Enter the value:”)
x = int(input(“Enter x value:”))
reads the value and converts it in to integer type data or value.
y=float(input(“Enter y value:”))
reads the value and converts it in to float type data or value.
Note:

Python makes this distinction because strings are text, while integers and
floats are both numbers.
Python Print Function
print()
The print() function prints the given object to the standard output device (screen)
or to the text stream file.
The general format or syntax of the input() is:

print("Python is fun.") Output


a=5
#Two objects are passed: Python is fun.
print("a =", a) a=5
b=a a=5=b
# Three objects are passed:
print('a =', a, '= b‘)
a = 3.564
>>> print("a = \n", a)
a=
3.564
>>>
print() with separator and end parameters
Output

print() with file parameter

This program tries to open the python.txt in writing mode. If this file doesn't exist,
python.txt file is created and opened in writing mode.
Here, we have passed sourceFile file object to the file parameter. The string object
'Pretty cool, huh!' is printed to the python.txt file (check it in your system).
Finally, the file is closed using the close() method.
Python Length Function
len()
The len() function takes a single argument/s, which can be
•sequence - string, bytes, tuple, list, range OR,
•collection - dictionary, set, frozen set

len() Return Value


len() function returns the number of items of an object.
Failing to pass an argument or passing an invalid argument will raise a TypeError excep
x = len("Hello")
Output 5
print(x)

Output
Python Type Casting
Type Casting (type conversion)
Conversion of value of one type to other
Examples

Note that float to int conversion


is truncation, not rounding off
Python Programming Conventions
Statement Termination: python does not use any symbol to terminate the
statement.
Maximum Line Length: Line Length be maximum 79 characters.
Whitespaces: you should always have whitespace around operators but not
with parenthesis.
Block or Code Block: A group of statements which are part of another
statement or function is called Block or Code Block.
Case Sensitive: Python is case sensitive.
Break, Continue and Pass
BREAK, CONTINUE and PASS

Break: A break statement in Python alters the flow of a loop by terminating it once a
specified condition is met.
Continue: The continue statement in Python is used to skip the remaining code inside a
loop for the current iteration only.
Pass: The pass statement in Python is used when a statement or a condition is required
to be present in the program, but we don’t want any command or code to execute. It’s
typically used as a placeholder for future code.
BREAK Statement

count=0 Output
while count<=7:
if count==5:
break
else:
print(count)
count+=1
print("ok bye!")
CONTINUE Statement

Output

var=10
while var>0:
var=var-1
if var==3:
continue
print(var)
print("Ok bye!")
PASS Statement

x=10
if x>10:
pass
Exception Handling
Errors that occur at runtime (after passing the syntax test) are called exceptions or

logical errors.
An exception is an unexpected event that occurs during program execution.
For example,
divide_by_zero = 7 / 0
The above code causes an exception as it is not possible to divide a number by 0.

Python Built-in Exceptions


Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python
that are raised when corresponding errors occur.
Exception Description
As the name suggests, the IndexError is raised when the wrong
IndexError
index of a list is used.
AssertionError AssertionError is raised when the assert statement fails
AttributeError AttributeError is raised when an attribute assignment is failed.
ImportError is raised when an imported module is not found
ImportError
or there is a problem in importing the required module.
KeyError KeyError is raised when the key of the dictionary is not found.
NameError NameError is raised when the variable is not yet defined.
MemoryError MemoryError is raised when a program runs out of memory.
TypeError is raised when a function or an operation is applied
TypeError
in an incorrect type.
EOFError EOFError is raised when the input() function hits the condition of
end-of-file.

FloatingPointError FloatingPointError is raised when a floating-point operation fails.

GeneratorExit TypeError is raised when we call the generator's close() method.

KeyboardInterrupt KeyboardInterrupt is raised when a user hits the interrupt key


i.e. Ctrl+C or Delete.

NotImplementedError NotImplementedError is raised by abstract methods when they are


defined.

OSError OSError is raised when system operation causes system-related


errors.

OverflowError OverflowError is raised when the result of an arithmetic operation


is too large.

ReferenceError ReferenceError is raised when a weak reference proxy is used to


access a garbage collected referent.

RuntimeError is raised when an error does not fall under


RuntimeError
any other category of built-in Python exceptions.
StopIteration is raised by the iterator's next() function to
StopIteration indicate that there is no further item to be returned by the
iterator.
IndentationError IndentationError is raised when there is incorrect indentation.
TabError TabError is raised when interpreter detects internal error.
SystemError is raised when indentation consists of inconsistent tabs
SystemError and spaces.
UnboundLocalError is raised when a reference is made to a local
UnboundLocalError variable in a function or method, having no value bound to that
variable.
UnicodeError is raised when a Unicode-related encoding or
UnicodeError decoding error occurs.
UnicodeEncodeError UnicodeEncodeError is raised when a Unicode-related error occurs
at the time of encoding.
UnicodeDecodeError UnicodeDecodeError is raised when a Unicode-related error occurs
at the time of decoding.
UnicodeTranslateError is raised when a Unicode-related error
UnicodeTranslateError occurs during translating.
ValueError is raised when a function is given the correct type of
ValueError argument but with an improper value.
ZeroDivisionError is raised when we try to divide any number by
ZeroDivisionError zero.
Exception Handling

def add(x,y):
return (x+y)

print(add(2,7))
print(add(5,10))
print(add(7,'a'))
print(add(12,2))
print('Execution done')
def add(x,y):
try:
return (x+y)
except TypeError:
return ("Invalid")

print(add(2,7))
print(add(5,10))
print(add(7,'a'))
print(add(12,2))
print('Execution done')
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and
except blocks.

You might also like