0% found this document useful (0 votes)
1 views65 pages

Python Unit I

The document provides an overview of programming languages, focusing on Python as a high-level, multipurpose, and object-oriented language. It covers Python's history, features, applications, types of program errors, and the structure of a Python program, including syntax, indentation, comments, variables, and operators. Additionally, it distinguishes between mutable and immutable data types and introduces numeric data types in Python.

Uploaded by

Shameem Sulthana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views65 pages

Python Unit I

The document provides an overview of programming languages, focusing on Python as a high-level, multipurpose, and object-oriented language. It covers Python's history, features, applications, types of program errors, and the structure of a Python program, including syntax, indentation, comments, variables, and operators. Additionally, it distinguishes between mutable and immutable data types and introduces numeric data types in Python.

Uploaded by

Shameem Sulthana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

UNIT - I

OVERVIEW OF PROGRAMMING

A programming language is a formal computer language or constructed language designed to


communicate instructions to a machine, particularly a computer. Programming languages can be used
to create programs to control the behaviour of a machine or to express algorithms.

INTRODUCTION OF PYTHON

● Python is an object-oriented, high level language, interpreted, dynamic and multipurpose programming
language.
● Python is easy to learn yet powerful and versatile scripting language which makes it attractive for
Application Development.
● Python's syntax and dynamic typing with its interpreted nature, make it an ideal language for
scripting and rapid application development in many areas.
● Python supports multiple programming pattern, including object oriented programming,
imperative and functional programming or procedural styles.
● Python is not intended to work on special area such as web programming. That is why it is known as
multipurpose because it can be used with web, enterprise, 3D CAD etc.
● We don't need to use data types to declare variable because it is dynamically typed so we can
write a=10 to declare an integer value in a variable.
● Python makes the development and debugging fast because there is no compilation step included
in python development and edit-test-debug cycle is very fast.
● It is used for GUI and database programming, client- and server-side web programming, and
application testing.
● It is used by scientists writing applications for the world's fastest supercomputers and by children first
learning to program.

HISTORY OF PYTHON

Python was conceptualized by Guido Van Rossum in the late 1980s. Rossum published the first version
of Python code (0.9.0) in February 1991 at the CWI (Centrum Wiskunde & Informatica) in the
Netherlands, Amsterdam. Python is derived from ABC programming language, which is a general-
purpose programming language that had been developed at the CWI. Rossum chose the name "Python",
since he was a big fan of Monty Python's Flying Circus. Python is now maintained by a core
development team at the institute, although Rossum still holds a vital role in directing its progress.

COMPILER vs INTERPRETER

An interpreter is a program that reads and executes code. This includes source code, pre-compiled code,
and scripts. Common interpreters include Perl, Python, and Ruby interpreters, which execute Perl,
Python, and Ruby code respectively. Interpreters and compilers are similar, since they both recognize
and process source code.
However, a compiler does not execute the code like and interpreter does. Instead, a compiler simply
converts the source code into machine code, which can be run directly by the operating system as an
executable program.
Interpreters bypass the compilation process and execute the code directly.
Interpreters are commonly installed on Web servers, which allows developers to run executable scripts
within their webpages. These scripts can be easily edited and saved without the need to recompile the
code. Without an interpreter, the source code serves as a plain text file rather than an executable
program.

PYTHON VERSIONS

● Python 1.0
● Python 2.0
● Python 3.0

PYTHON FEATURES

● Easy to learn, easy to read and easy to maintain.


● Portable: It can run on various hardware platforms and has the same interface on
all platforms.
● Extendable: You can add low-level modules to the Python interpreter.
● Scalable: Python provides a good structure and support for large programs. Python
has support for an interactive mode of testing and debugging.
● Python has a broad standard library cross-platform.
● Everything in Python is an object: variables, functions, even code. Every object has an ID, a
type, and a value.
● Python provides interfaces to all major commercial databases.
● Python supports functional and structured programming methods as well as OOP.
● Python provides very high-level dynamic data types and supports dynamic type checking.
● Python supports GUI applications
● Python supports automatic garbage collection.
● Python can be easily integrated with C, C++, and Java.

APPLICATIONS OF PYTHON

● Machine Learning
● GUI Applications (like Kivy, Tkinter, PyQt etc. )
● Web frameworks like Django (used by YouTube, Instagram, Dropbox)
● Image processing (like OpenCV, Pillow)
● Web scraping (like Scrapy, BeautifulSoup, Selenium)
● Test frameworks
● Multimedia
● Scientific computing
● Text processing

TYPES OF PROGRAM ERRORS

We distinguish between the following types of errors:

1. Syntax errors: errors due to the fact that the syntax of the language is not respected.
2. Semantic errors: errors due to an improper use of program statements.
3. Logical errors: errors due to the fact that the specification is not respected.

From the point of view of when errors are detected, we distinguish:

1. Compile time errors: syntax errors and static semantic errors indicated by the compiler.
2. Runtime errors: dynamic semantic errors, and logical errors, that cannot be detected by
the compiler (debugging).

Syntax errors

Syntax errors are due to the fact that the syntax of the Python llanguage is not
respected. Let us see some examples of syntax errors.

Example 1: Missing semicolon:


int a = 5; // semicolon is missing

Compiler message:
Example.java:20: ';' expected int a
=5
Example 2: Errors in expressions:
x = ( 3 + 5; // missing closing parenthesis ')'
y = 3 + * 5; // missing argument between '+' and '*'

Semantic errors

Semantic errors indicate an improper use of Java statements.


Let us see some examples of semantic errors.

Example 1: Use of a non-initialized variable:


int i
i++; // the variable i is not
initialized

Example 2: Type incompatibility:


int a = "hello"; // the types String and int are not
compatible

Example 3: Errors in expressions:


String s = "...";
int a = 5 - s; // the - operator does not support arguments of type String

Example 4: Unknown references:


Strin x; // Strin is not defined
system.out.println("hello");
// system is not defined
String s;
s.println(); // println is not a method of the class
String
Example 5: Array index out of range (dynamic semantic error)
int[] v = new int[10];
v[10] = 100; // 10 is not a legal index for an array of 10 elements
The array v has been created with 10 elements (with indexes ranging from 0 to 9), and we are trying
to access the element with index 10, which does not exist. This type of error is not caught during
compilation, but causes an exception to be thrown at runtime.

Logical errors

Logical errors are caused by the fact that the software specification is not respected. The program is
compiled and executed without errors, but does not generate the requested result.
Let us see some examples of logical errors:
Example 1: Errors in the performed
computation:

public static int sum(int a, int b)


{

return a - b ;
}

// this method returns the wrong value wrt the specification that requires
// to sum two integers
Example 2: Non termination:
String s = br.readLine();
while (s != null)

{
System.out.println(s);
} // this loop does not terminate
Errors detected by the compiler and runtime errors

All syntax errors and some of the semantic errors (the static semantic errors) are detected by the
compiler, which generates a message indicating the type of error and the position in the Java source
file where the error occurred (notice that the actual error could have occurred before the position
signaled by the compiler).
Other semantic errors (the dynamic semantic errors) and the logical errors cannot be detected by the
compiler, and hence they are detected only when the program is executed.
Let us see some examples of errors detected at runtime:
Example 1: Division by zero:
int a, b, x;
a = 10;
b = Integer.parseInt(kb.readLine());
x = a / b; //ERROR if b = 0
This error occurs only for a certain configuration of the input (b = 0).
Example 2: File does not exist:
FileReader f = new FileReader("pippo.txt");
The error occurs only if the file pippo.txt does not exist on the harddisk.
Example 3: Dereferencing of a null reference:
String s, t;
s = null;
t = s.concat("a");

The concat() method cannot be applied to a reference whose value is null. Note that the
above code is syntactically correct, since the concat() method is correctly applied to a
reference of type String, but it contains a dynamic semantic error due the fact that a
method cannot be applied to a reference whose value is null.

STRUCTURE OF A PYTHON PROGRAM

Python Statements

In general, the interpreter reads and executes the statements line by line i.e. sequentially. Though, there
are some statements that can alter this behavior like conditional statements. Mostly, python
statements are written in such a format that one statement is only written in a single line. The interpreter
considers the ‘new line character’ as the terminator of one instruction.

Example 1:
print('Welcome to Geeks for Geeks')

Instructions that a Python interpreter can execute are called statements.


For example, a = 1 is an assignment statement.
if statement,
for
statement,
while statement etc. 3wexc
Multi-line statement

In Python, end of a statement is marked by a newline character. But we can make a statement extend
over multiple lines with the line continuation character (\). For example:

a=1+2+3+\
4+5+6+\
7+8+9

This is explicit line continuation. In Python, line continuation is implied inside parentheses ( ),
brackets [ ] and braces { }. For instance, we can implement the above multi-line statement as,

a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)

Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [ ] and
{ }. For example:

colors = ['red',
'blue',
'green']

We could also put multiple statements in a single line using semicolons, as follows:

a = 1; b = 2; c = 3

Python Indentation

Most of the programming languages like C, C++, Java use braces { } to define a block of code.
Python uses indentation.

A code block (body of a function, loop etc.) starts with indentation and ends with the first unindented
line. The amount of indentation is up to you, but it must be consistent throughout that block.

Generally four whitespaces are used for indentation and is preferred over tabs. Here is an example.

for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results into Python
programs that look similar and consistent.

Indentation can be ignored in line continuation. But it's a good idea to always indent. It makes the code
more readable. For example:

if True:
print('Hello')
a=5

and

if True: print('Hello'); a = 5

both are valid and do the same thing. But the former style is clearer.
Incorrect indentation will result into IndentationError.

Python Comments

Comments are very important while writing a program. It describes what's going on inside a program
so that a person looking at the source code does not have a hard time figuring it out. You might forget
the key details of the program you just wrote in a month's time. So taking time to explain these
concepts in form of comments is always fruitful.

In Python, we use the hash (#) symbol to start writing a comment.

It extends up to the newline character. Comments are for programmers for better understanding of a
program. Python Interpreter ignores comment.

#This is a comment
#print out Hello
print('Hello')

Multi-line comments

If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line. For example:

#This is a long comment


#and it extends
#to multiple lines
Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are generally used for multi-line strings. But they can be used as multi-line
comment as well. Unless they are not docstrings, they do not generate any extra code.

"""This is also a
perfect example of
multi-line comments"""

Python Variables
A variable is a named location used to store data in the memory. It is helpful to think of variables as a
container that holds data which can be changed later throughout programming.

Example 1: N1=10
N2=10.5
Example 2:
x = y = z = "same" # assign the same value to multiple variables at once
print (x)
print (y)
print (z)

Constants
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as
containers that hold information which cannot be changed later.

Example 1:

PI = 3.14
GRAVITY = 9.8

Literals
Literal is a raw data given in a variable or constant. In Python, there are various types of literals they
are as follows:

Example 1:
a = 01010 #Binary Literals
b = 100.1 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal

#Float Literal
float_1 = 10.5
float_2 = 1.5e2

#Complex Literal
x = 3.1432424j

Python Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The value
that the operator operates on is called the operand.

Operators are used to perform operations on variables and values.

● Arithmetic operators
● Relational operators < > <= >= == !=
● Logical operators AND OR NOT
● Bitwise operators
● Assignment operators
● Special operators
✔ Identity operators
✔ Membership operators

Example:
# Python Program to find the area of triangle

a=5
b=6
c=7

# Uncomment below to take inputs from the user


# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))

# calculate the semi-perimeter


s = (a + b + c) / 2

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Output:
The area of the triangle is 14.70
ELEMENTS OF PYTHON

● A Python program, sometimes called a script, is a sequence of definitions and commands.


● These definitions are evaluated and the commands are executed by the Python interpreter in
something called the shell.
● Typically, a new shell is created whenever execution of a program begins. In most cases, a
window is associated with the shell.
● A command, often called a statement, instructs the interpreter to do

something. The basic elements of Python are:

1. Keywords: and, assert, break, class, continue, def,del, elif, else, except, exec, finally, for,
from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield
2. Operators: + - * / % ** // > & | ^ ~ >= <> != ==
3. Delimiters: ( ) [ ] { }, :. ' = ; += -= *= /= //= %= &= |= ^= >>= <<= **=
4. Data types: Numeric, Dictionary, Boolean, Set, Strings, List, Tuple

Mutable and Immutable data types/objects:

● Example for mutable data types are: List, Set and Dictionary
● Example for Immutable data types are: Strings, tuple, int, float, bool,Unicode.

Numeric

In Python, numeric data type represent the data which has numeric value. Numeric value can be
interger, floating number or even complex numbers. These values are defined as int, float and
complex class in Python.
● Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fraction or decimal). In Python there is no limit to how long an integer value can be.
● Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
● Complex Numbers – Complex number is represented by complex class. It is specified as (real
part) + (imaginary part)j. For example – 2+3j
# Python program to demonstrate numeric value

a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))

OUTPUT:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>

Strings
In Python, Updation or deletion of characters from a String is not allowed. This will cause an error
because item assignment or item deletion from a String is not supported. This is because Strings are
immutable, hence elements of a String cannot be changed once it has been assigned.
Program:
String1 = "IIIBSC STUDENTS"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

print("\n8th char: ")


print(String1[8])
# Updation or deletion of characters from a String is not allowed

Output:
Initial String:
IIIBSC STUDENTS

First character of String is:


I

Last character of String is:


S

8th char:
T

Lists
Lists are just like the arrays, declared in other languages.
Lists need not be homogeneous always which makes it the most powerful tool in Python.
A single list may contain DataTypes like Integers, Strings, as well as Objects.
Lists are mutable, and hence, they can be altered even after their creation.
List in Python are ordered and have a definite count.
The elements in a list are indexed according to a definite sequence and the indexing of a list is done
with 0 being the first index.
Each element in the list has its definite place in the list, which allows duplicating of elements in the
list, with each element having its own distinct place and credibility.
It is represented by list class.

Creating a list

Lists in Python can be created by just placing the sequence inside the square brackets[].

#Python program to demonstrate Creation of List

# Creating a List
List = []
print("Intial blank List: ")
print(List)

# Creating a List with the use of a String


List = ['IIIBSCSTUDENTS']
print("\nList with the use of String: ")
print(List)

# Creating a List with the use of multiple values


List = ["III", "BSC", "STUDENTS"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List (By Nesting a list inside a List)


List = [['III', 'BSC'], ['STUDENTS']]
print("\nMulti-Dimensional List: ")
print(List)

Methods used in a List

#Append an element (ADD an element)


List.append(4)
print("\nList after Adding a number: ")
print(List)

# Addition of Element at specific Position (using Insert Method)


List.insert(2, 12)
print(List)

List.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
print(List)
# Addition of multiple elements to the List at the end (using Extend Method)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)

# accessing a element from the list using index number


print("Accessing element from the list")
print(List[0])
print(List[2])

# accessing a element using negative indexing


print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])

List1=[1,2,3,4,5,6,7,8]
print("Original List")
print(List1)
# Removing elements from List using Remove() method
List1.remove(5)

print("\nList after Removal of element: ")


print(List1)

List1.pop()
print("\nList after popping an element: ")
print(List1)

# Removing element at a specific location from the set using the pop() method
List1.pop(2)
print("\nList after popping a specific element: ")
print(List1)

Output:

Intial blank List:


[]

List with the use of String:


['IIIBSCSTUDENTS']

List containing multiple values:


III
STUDENTS
Multi-Dimensional List:
[['III', 'BSC'], ['STUDENTS']]

List after Adding a number:


[['III', 'BSC'], ['STUDENTS'], 4]
[['III', 'BSC'], ['STUDENTS'], 12, 4]

List after performing Insert Operation:


['Geeks', ['III', 'BSC'], ['STUDENTS'], 12, 4]

List after performing Extend Operation:


['Geeks', ['III', 'BSC'], ['STUDENTS'], 12, 4, 8, 'Geeks', 'Always']
Accessing element from the list
Geeks
['STUDENTS']
Accessing element using negative indexing
Always
8
Original List
[1, 2, 3, 4, 5, 6, 7, 8]

List after Removal of element:


[1, 2, 3, 4, 6, 7, 8]

List after popping an element:


[1, 2, 3, 4, 6, 7]

List after popping a specific element:


[1, 2, 4, 6, 7]

Adding Elements to a List

Elements can be added to the List by using built-in append() function.


Only one element at a time can be added to the list by using append() method.
For addition of element at the desired position, insert() method is used.
Other than append() and insert() methods.
extend() method is used to add multiple elements at the same time at the end of the list.

Removing Elements from the List

Elements can be removed from the List by using built-in remove() function.
Pop() function can also be used to remove and return an element from the set, but by default it removes
only the last element of the set, to remove element from a specific position of the List, index of the
element is passed as an argument to the pop() method.
Remove method in List will only remove the first occurrence of the searched element.
Tuple
Tuple is an ordered collection of Python objects much like a list. The sequence of values stored in a
tuple can be of any type, and they are indexed by integers. The important difference between a list
and a tuple is that tuples are immutable. Also, Tuples are hashable whereas lists are not. It is
represented by tuple class.
Creating a Tuple
In Python, tuples are created by placing sequence of values separated by ‘comma’ with or without the
use of parentheses for grouping of data sequence. Tuples can contain any number of elements and of
any datatype (like strings, integers, list, etc.). Tuples can also be created with a single element, but it is
a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’
to make it a tuple.
In python, deletion or updation of a tuple is not allowed.

# Python program to demonstrate creation of Tuple

# Creating an empty tuple


Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)

# Creating a Tuple with the use of Strings


Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with the use of list


list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a Tuple with the use of built-in function


Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)

# Creating a Tuple with nested tuples


Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)

# Accessing element using indexing


print("Frist element of tuple")
print(Tuple1[0])

# Accessing element from last -- negative indexing


print("\nLast element of tuple")
print(Tuple1[-1])

print("\nThird last element of tuple")


print(Tuple1[-3])

OUTPUT:
Initial empty Tuple:
()

Tuple with the use of String:


('Geeks', 'For')

Tuple using List:


(1, 2, 4, 5, 6)

Tuple with the use of function:


('G', 'e', 'e', 'k', 's')

Tuple with nested tuples:


((0, 1, 2, 3), ('python', 'geek'))
Frist element of tuple
0

Last element of tuple


3

Third last element of tuple


1

Boolean

Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are
truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in
Boolean context as well and determined to be true or false. It is denoted by the class bool.
# Python program to demonstrate boolean type
print(type(True))
print(type(False))
print(type(true)) # Error, Small t for true is wrong

Set
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate
elements. The order of elements in a set is undefined though it may consist of various elements. The
major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking
whether a specific element is contained in the set.
Creating a set

Sets can be created by using the built-in set() function with an iterable object or a sequence by placing
the sequence inside curly braces, separated by ‘comma’. A set contains only unique elements but at the
time of set creation, multiple duplicate values can also be passed. The order of elements in a set is
undefined and is unchangeable. Type of elements in a set need not be the same, various mixed-up data
type values can also be passed to the set.
Set items cannot be accessed by referring to an index, since sets are unordered the items has no index.
# Python program to demonstrate Creation of Set in Python

# Creating a Set
set1 = set()
print("Intial blank Set: ")
print(set1)

# Creating a Set with the use of a String


set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)

# Creating a Set with the use of a List


set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)

# Creating a Set with a mixed type of values (Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)

Methods used

set1.add(9)
print("\nSet after Addition of Three elements: ")
print(set1)

# Addition of elements to the Set using Update function


set1.update([10, 11])
print("\nSet after Addition of elements using Update: ")
print(set1)
# Removing elements from Set using Remove() method
set1.remove(9)
print("\nSet after Removal of two elements: ")
print(set1)

# Removing elements from Set using Discard() method


set1.discard(4)

print("\nSet after Discarding two elements: ")


print(set1)

# Removing element from the Set using the pop() method


set1.pop()
print("\nSet after popping an element: ")
print(set1)

# Removing all the elements from Set using clear() method


set1.clear()
print("\nSet after clearing all the elements: ")
print(set1)

Output:
Intial blank Set:
set()

Set with the use of String:


{'s', 'k', 'e', 'F', 'o', 'G', 'r'}

Set with the use of List:


{'Geeks', 'For'}

Set with the use of Mixed Values


{1, 2, 4, 'Geeks', 6, 'For'}

Set after Addition of Three elements:


{1, 2, 4, 'Geeks', 6, 'For', 9}

Set after Addition of elements using Update:


{1, 2, 4, 'Geeks', 6, 'For', 9, 10, 11}

Set after Removal of two elements:


{1, 2, 4, 'Geeks', 6, 'For', 10, 11}

Set after Discarding two elements:


{1, 2, 'Geeks', 6, 'For', 10, 11}

Set after popping an element:


{2, 'Geeks', 6, 'For', 10, 11}

Set after clearing all the elements:


set()

Removing elements from a set

Elements can be removed from the Set by using built-in remove() function but a KeyError arises if
element doesn’t exist in the set. To remove elements from a set without KeyError, use discard().
Pop() function can also be used to remove and return an element from the set, but it removes only the
last element of the set. To remove all the elements from the set, clear() function is used.
Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map,
which unlike other Data Types that hold only single value as an element, Dictionary holds key:value
pair. Key-value is provided in the dictionary to make it more optimized. Each key- value pair in a
Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.

Creating a dictionary

In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding
pair element being its Key:value. Values in a dictionary can be of any datatype and can be duplicated,
whereas keys can’t be repeated and must be immutable.
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by
just placing to curly braces{}.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated
distinctly.
# Python Program
Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary with Integer Keys


Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary with Mixed keys


Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

# Creating a Dictionary with dict() method


Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary with each item as a Pair


Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)

# Adding elements one at a time


Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)

Methods used
# Python program to demonstrate for accessing elements from a Dictionary

# Creating a Dictionary

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key


print("Accessing a element using key:")
print(Dict['name'])

# accessing a element using get() method


print("Accessing a element using get:")
print(Dict.get(3))

# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks',
'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'},
'B' : {1 : 'Geeks', 2 : 'Life'}}
print("Initial Dictionary: ")
print(Dict)

# Deleting a Key value


del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)

# Deleting a Key using pop()


Dict.pop(5)
print("\nPopping specific element: ")
print(Dict)

# Deleting an arbitrary Key-value pair using popitem()


Dict.popitem()
print("\nPops an arbitrary key-value pair: ")
print(Dict)

# Deleting entire Dictionary


Dict.clear()
print("\nDeleting Entire Dictionary: ")
print(Dict)
Output:
Empty Dictionary:
{}

Dictionary with the use of Integer Keys:


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys:


{'Name': 'Geeks', 1: [1, 2, 3, 4]}

Dictionary with the use of dict():


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with each item as a pair:


{1: 'Geeks', 2: 'For'}

Dictionary after adding 3 elements:


{1: 'Geeks', 2: 'For', 0: 'Geeks', 3: 1}

Updated key value:


{1: 'Geeks', 2: 'Welcome', 0: 'Geeks', 3: 1}
Accessing a element using key:
For
Accessing a element using get:
Geeks
Initial Dictionary:
{5: 'Welcome', 6: 'To', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2:
'Life'}}

Deleting a specific key:


{5: 'Welcome', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}

Popping specific element:


{7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}

Pops an arbitrary key-value pair:


{7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}}

Deleting Entire Dictionary:


{}
PYTHON INTERPRETER

FEATURES OF PYTHON INTERPRETER

Python interpreter offers some pretty cool features:

● Interactive editing
● History substitution
● Code completion on systems with support for readline

INVOKING THE PYTHON INTERPRETER

On your machine, you can find your interpreter at an address like:


C:\Python36
Or it may reside on the location you selected at the time of installation. Add path using this
command:

set path=%path%;C:\python36

INTERACTIVE MODE

Python interpreter is in an interactive mode when it reads commands from a tty. The primary
prompt is the following:

1. >>>
When it shows this prompt, it means it prompts the developer for the next command. This is the
REPL. Before it prints the first prompt, Python interpreter prints a welcome message that also states
its version number and a copyright notice.
This is the secondary prompt:

1. …
This prompt denotes continuation lines.

$ python3.7
Python 3.7 (default, Jul 16 2018, 04:38:07)
[GCC 4.8.2] on Windows
Type "help", "copyright", "credits" or "license" for more information.
>>>
You will find continuation lines when working with a multi-line construct:

>>> it_rains =True


>>> if it_rains:
>>> print("The produce will be good")
Output:

The produce will be good


We can also use the Python interpreter as a calculator:

>>> 2*7
14
>>> 4/2
2.0

HOW DOES PYTHON INTERPRETER WORKS?

Four things happen in a REPL:


i. Lexing- The lexer breaks the line of code into tokens.
ii. Parsing- The parser uses these tokens to generate a structure, here, an Abstract Syntax
Tree, to depict the relationship between these tokens.
iii. Compiling- The compiler turns this AST into code object(s).
iv. Interpreting- The interpreter executes each code object.

USING PYTHON AS A CALCULATOR

Numbers
Start with simple Python commands. Start the interpreter and wait for the primary prompt, >>>.
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value.
Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages
(for example, Pascal or C); parentheses (()) can be used for grouping. For example:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6

The integer numbers (e.g. 2, 4, 20) have type int, the ones with a fractional part (e.g. 5.0, 1.6) have
type float.

Division (/) always returns a float. To do floor division and get an integer result (discarding any fractional
result) you can use the // operator; to calculate the remainder you can use %:
>>> 17 / 3 # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # result * divisor + remainder
17

With Python, it is possible to use the ** operator to calculate powers 1:

>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128

The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the
next interactive prompt:

>>> width = 20
>>> height = 5 * 9
>>> width * height
900

Strings

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They
can be enclosed in single quotes ('...') or double quotes ("...") with the same result 2. \ can be used to
escape quotes:

>>>

>>> 'spam eggs' # single quotes


'spam eggs'
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s) # with print(), \n produces a new line
First line.
Second line.
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
Lists

Python knows a number of compound data types, used to group together other values. The most
versatile is the list, which can be written as a list of comma-separated values (items) between square
brackets. Lists might contain items of different types, but usually the items all have the same type.

>>> squares = [1, 4, 9, 16, 25]


>>> squares
[1, 4, 9, 16, 25]

Like strings (and all other built-in sequence types), lists can be indexed and sliced:

>>> squares[0] # indexing returns the item


1
>>> squares[-
1] 25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]

All slice operations return a new list containing the requested elements.

>>> squares[:]
[1, 4, 9, 16, 25]

Lists also support operations like concatenation:

>>> squares + [36, 49, 64, 81, 100]


[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:

>>> cubes = [1, 8, 27, 65, 125] # something's wrong here


>>> 4 ** 3 # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64 # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

#Program 1:

>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536
#Program 2:

>>> a, b = 0, 1
>>> while a < 1000:
... print(a, end=',')
... a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

PYTHON - SHELL (INTERPRETER)

Python is an interpreter language. It means it executes the code line by line. Python provides a Python
Shell (also known as Python Interactive Shell) which is used to execute a single Python command and
get the result.

Python Shell waits for the input command from the user. As soon as the user enters the command, it
executes it and displays the result.

To open the Python Shell on Windows, open the command prompt, write python and press enter.

Python Shell
As you can see, a Python Prompt comprising of three Greater Than symbols (>>>) appears. Now, you
can enter a single statement and get the result. For example, enter a simple expression like 3 + 2, press
enter and it will display the result in the next line.
Command Execution on Python Shell

Execute Python Script

Python Shell executes a single statement. To execute multiple statements, create a Python file with
extension .py, and write Python scripts (multiple statements).

For example, enter the following statement in a text editor such as Notepad.
Example: myPythonScript.py print
("This is Python Script.")
print ("Welcome to Python Tutorial by TutorialsTeacher.com")

Save it as myPythonScript.py, navigate command prompt to the folder where you have saved this file
and execute the python myPythonScript.py command, as shown below.

Python Shell
Thus, you can execute Python expressions and commands using Python Shell.

PYTHON – IDLE

IDLE (Integrated Development and Learning Environment) is an integrated development


environment (IDE) for Python. The Python installer for Windows contains the IDLE module by
default.

IDLE can be used to execute a single statement just like Python Shell and also to create, modify and
execute Python scripts. IDLE provides a fully-featured text editor to create Python scripts that includes
features like syntax highlighting, autocompletion and smart indent. It also has a debugger with
stepping and breakpoints features.

Goto File->New File and open a new Script page and enter multiple statements and then save the file
with extension .py using File -> Save. For example, save the following code as hello.py.

Python Script in IDLE

Now, press F5 to run the script in the editor window. The IDLE shell will show the output.

Python Script Execution Result in IDLE

Thus, it is easy to write, test and run Python scripts in IDLE.

PYTHON INDENTATION

Most of the programming languages like C, C++, Java use braces { } to define a block of code.
Python uses indentation.

A code block (body of a function, loop etc.) starts with indentation and ends with the first unindented
line. The amount of indentation is up to you, but it must be consistent throughout that block.

Generally four whitespaces are used for indentation and is preferred over tabs. Here is an example.

for i in range(1,11):
print(i)
if i == 5:
break

The enforcement of indentation in Python makes the code look neat and clean. This results into
Python programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to always indent. It makes the code
more readable. For example:

if True:
print('Hello')
a=5

and

if True: print('Hello'); a = 5

both are valid and do the same thing. But the former style is clearer.
Incorrect indentation will result into IndentationError.

ATOMS

Atoms are the most basic elements of expressions. The simplest atoms are identifiers or literals. Forms
enclosed in reverse quotes or in parentheses, brackets or braces are also categorized syntactically as
atoms. The syntax for atoms is:

atom: identifier | literal | enclosure


enclosure: parenth_form|list_display|dict_display|string_conversion

PYTHON IDENTIFIERS

An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate
one entity from another.

Rules for writing identifiers


1. 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 _. Names like myClass, var_1 and print_this_to_screen, all are valid
example.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.

>>> global = 1
File "<interactive input>", line 1
global = 1
^
SyntaxError: invalid syntax
4. We cannot use special symbols like !, @, #, $, % etc. in the identifier.
>>> a@ = 0
File "<interactive input>",
line 1 a@ = 0
^
SyntaxError: invalid syntax

5. Identifier can be of any length.

PYTHON KEYWORDS

Keywords are the reserved words in Python.

We cannot use a keyword as a variable name, function name or any other identifier. They are used to
define the syntax and structure of the Python language. In Python, keywords are case sensitive. There
are 33 keywords in Python 3.7. This number can vary slightly in the course of time.

All the keywords except True, False and None are in lowercase and they must be written as it is. The
list of all the keywords is given below.

LITERALS
Literal is a raw data given in a variable or constant. In Python, there are various types of literals they
are as follows:
Example 1:
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal

#Float Literal
float_1 = 10.5
float_2 = 1.5e2

#Complex Literal

STRINGS
x = 3.14j
In Python, Updation or deletion of characters from a String is not allowed. This will cause an error
because item assignment or item deletion from a String is not supported. This is because Strings are
immutable, hence elements of a String cannot be changed once it has been assigned.
Program:
String1 = "IIIBSC STUDENTS"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

print("\n8th char: ")


print(String1[8])
# Updation or deletion of characters from a String is not allowed

Output:
Initial String:
IIIBSC STUDENTS

First character of String is:


I

Last character of String is:


S

8th char:
T
OPERATORS IN PYTHON

Operators are special symbols in Python that carry out arithmetic or logical computation. The value
that the operator operates on is called the operand.

Operators are used to perform operations on variables and values.

● Arithmetic operators
● Relational operators
● Logical operators
● Bitwise operators
● Assignment operators
● Special operators
✔ Identity operators
✔ Membership operators

Program:
# Examples of Arithmetic Operator
a=9
b=4

# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b

# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)

Output:
13
5
36
2.25
2
1

Program:

# Examples of Relational Operators


a = 13
b = 33

# a > b is False
print(a > b)

# a < b is True
print(a < b)

# a == b is False
print(a == b)

# a != b is True
print(a != b)

# a >= b is False
print(a >= b)

# a <= b is True
print(a <= b)

Output:
False
True
False
True
False
True

Program:
# Examples of Logical Operator
a = True
b = False

# Print a and b is False


print(a and b)

# Print a or b is True
print(a or b)

# Print not a is False


print(not a)

Output:
False
True
False

Program:

a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0

c = a & b; # 12 = 0000 1100


print "Line 1 - Value of c is ", c

c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c

c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c

c = ~a; # -61 = 1100 0011


print "Line 4 - Value of c is ", c

c = a << 2; # 240 = 1111 0000


print "Line 5 - Value of c is ", c

c = a >> 2; # 15 = 0000 1111


print "Line 6 - Value of c is ", c

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Output:
Program:

# Examples of Identity operators


a1 = 3
b1 = 3
a2 = 'GeeksforGeeks'
b2 = 'GeeksforGeeks'
a3 = [1,2,3]
b3 = [1,2,3]
print(a1 is not b1)
print(a2 is b2)

# Output is False, since lists are mutable.


print(a3 is b3)

Output:
False
True
False

Program:

# Examples of Membership operator


x = 'Geeks for Geeks'
y = {3:'a',4:'b'}

print('G' in x)

print('geeks' not in x)

print('Geeks' not in x)

print(3 in y)

print('b' in y)

x = ["apple", "banana"]
print("banana" in x)

# returns True because a sequence with the value "banana" is in the list
print("pineapple" not in x)

# returns True because a sequence with the value "pineapple" is not in the list

Output:
True
True
False
True
False
True
True

Ternary operator

Ternary operators also known as conditional expressions are operators that evaluate something based
on a condition being true or false. It was added to Python in version 2.5. It simply allows to
test a condition in a single line replacing the multiline if-else making the code compact.

Syntax :
[on_true] if [expression] else [on_false]

Example 1: Simple Method to use ternary operator


# Program to demonstrate conditional operator
a, b = 10, 20

# Copy value of a in min if a < b else copy b


min = a if a < b else b
print(min)

Output:

10
Example 2: Python 3 program to find the factorial of given number
def factorial(n):
# single line to find factorial
return 1 if (n==1 or n==0) else n * factorial(n - 1)

# Driver Code
num = 5
print ("Factorial of",num,"is", factorial(num))
Output:
Factorial of 5 is 120

Increment and Decrement Operators in Python

Python is designed to be consistent and readable. One common error by a novice programmer in
languages with ++ and -- operators is mixing up the differences (both in precedence and in return value)
between pre and post increment/decrement operators. Simple increment and decrement operators aren’t
needed as much as in other languages.
for (int i = 0; i < 5; ++i)

In Python, instead we write it like,

# A Sample Python program to show loop (unlike many # other languages, it doesn't use
++)

for i in range(0, 5):


print(i)

Output:
0
1
2
3
4

We can almost always avoid use of ++ and --. For example, x++ can be written as x += 1 and x-
- can be written as x -= 1.
INPUT AND OUTPUT STATEMENTS
Input Statement:
Input means the data entered by the user of the program. In python, we have input() and raw_input (
) function available for Input.

1) input() function

Syntax:
input (expression)

If prompt is present, it is displayed on monitor, after which the user can provide data from keyboard.
Input takes whatever is typed from the keyboard and evaluates it. As the input provided is evaluated,
it expects valid python expression. If the input provided is not correct then either syntax error or
exception is raised by python.

Example 1:

# python input operations

# user input
x = input("Enter any value: ")

# printing value
print("Entered value is: ", x)

Output

RUN 1:
Enter any value: 12345
Entered value is: 12345

RUN 2:
Enter any value: IncludeHelp
Entered value is: IncludeHelp

RUN 3:
Enter any value: Python is a progamming language.
Entered value is: Python is a progamming language.

Example 2:

# python input operations

# just provide a value and entered value prints


print(input())

# provide another
value x = input()
print("Your input is: ", x)
# prompting message for input
val1 = input("Enter a value: ")
val2 = input("Enter another value: ")
val3 = input("Enter another value: ")

# printing values
print("val1 =", val1)
print("val2 =", val2)
print("val3 =", val3)

Output

Hello
Hello
I'm Shivang!
Your input is: I'm Shivang!
Enter a value: 100
Enter another value: 23.45
Enter another value: Helllooooooo
val1 = 100
val2 = 23.45
val3 = Helllooooooo

2) raw_input() function

This input method fairly works in older versions (like 2.x).

Syntax:

raw_input (expression)

If prompt is present, it is displayed on the monitor after which user can provide the data from
keyboard. The function takes exactly what is typed from keyboard, convert it to string and then return
it to the variable on LHS of '='.

Example: In interactive mode

>>>x=raw_input ('Enter your name: ')

Enter your name: ABC

x is a variable which will get the string (ABC), typed by user during the execution of program.
Typing of data for the raw_input function is terminated by enter key.

We can use raw_input() to enter numeric data also. In that case we typecast, i.e., change the data type
using function, the string data accepted from user to appropriate Numeric type.

Example:
>>>y=int(raw_input("Enter your roll no."))

Enter your roll no. 5

It will convert the accepted string i.e., 5 to integer before assigning it to 'y'.

Output Statement:
1). print() function/statement

print evaluates the expression before printing it on the monitor. Print statement outputs an entire
(complete) line and then goes to next line for subsequent output (s). To print more than one item on a
single line, comma (,) may be used.

Syntax:

print (expression/constant/variable)

Example 1:

# print() example in Python

# using single quotes


print('Hello!')
print('How are you?')

# using double quotes


print("Hello!")
print("How are you?")

# using triple single quotes


# those can be used to print multiple line string
print('''Hello!''')
print('''How are you?''')

# printing multiline string


print('''Hello... how are you?
Hey! I am good, what about you?
I am good also, thanks.''')

Output

Hello!
How are you?
Hello!
How are you?
Hello!
How are you?
Hello... how are you?
Hey! I am good, what about you?
I am good also, thanks.

Example 2:

# print() example in Python

# printing values
print("Printing direct values...")
print(10) # printing an integer
print(10.2345) # printing a float
print([10, 20, 30, 40, 50]) # printing a list
print({10, 20, 30, 40, 50}) # printing a set

# printing variables
a = 10
b = 10.2345
c = [10, 20, 30, 40, 50]
d = {10, 20, 30, 40, 50}

print("Printing variables...")
print(a
)
print(b)
print(c)
print(d)

# printing message with variables


print("Printing message variables...")
print("a = ", a)
print("b = ", b)
print("c = ", c)
print("d = ", d)

Output

Printing direct values...


10
10.2345
[10, 20, 30, 40, 50]
{40, 10, 50, 20, 30}
Printing variables...
10
10.2345
[10, 20, 30, 40, 50]
{40, 10, 50, 20, 30}
Printing message variables...
a = 10
b = 10.2345
c = [10, 20, 30, 40, 50]
d = {40, 10, 50, 20, 30}
CONTROL STATEMENTS

(BRANCHING, LOOPING, CONDITIONAL STATEMENT, EXIT FUNCTION,


DIFFERENCE BETWEEN BREAK, CONTINUE AND PASS)

The if statement

if statement is the most simple decision making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a block
of statement is executed otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true

Ex 1:
x = eval(input("Enter x: "))

if x>0:

print("x is positive")
***************************************************************************

The if else statement with multiple statements

The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false. Here
comes the else statement. We can use the else statement with if statement to execute a block of code
when the condition is false.

if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

Syntax:

Ex 1:
x = 'spam'
if x == 'spammy':
print 'Hi spam\n'
print "Nice weather we're having"
print 'Have a nice day!'
else:
print 'not spam'
print 'Not having a good day?'
A nested if example
(an if statement within another if statement)

nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements means an
if statement inside another if statement. Yes, Python allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement.

if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is
true # if Block is end here
# if Block is end here
Syntax:
Ex 1:
score=raw_input("Enter score: ") score=int(score)
if score>=80: grade='A'
else:
if score>=70: grade='B'
else:
grade='C'
print "Grade is:" +grade

Ex 1:
A nested if example - using if/else
score = raw_input("Enter score: ")
score = int(score)
if score >= 80:
grade = 'A'
else:
if score >= 70:
grade = 'B'
else:
if score >= 55:
grade = 'C'
else:
if score >= 50:
grade = 'Pass'
else:
grade = 'Fail'
print "\n\nGrade is: " + grade

A nested if example - using if/elif/else

if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed from the top down.
As soon as one of the conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed.
Syntax:-
if
(condition)
: statement
elif
(condition):
statement
.
.
else:
Ex 1:
statement
score = raw_input("Enter score: ")
score = int(score)
if score >= 80:
grade = 'A'
elif score >= 70:
grade = 'B'
elif score >= 55:
grade = 'C'
elif score >= 50:
grade = 'Pass'
else:
grade = 'Fail'
print "\n\nGrade is: " + grade

Examples of while loops

While Loop
Syntax :

while expression:
statement(s)

Example:
x=1
while x <= 5:
print ('Hi spam')
x=x+1
print ('I love spam')
print ('done')
print ('gone')
Output:
Hi spam
I love spam
Hi spam
I love spam
Hi spam
I love spam
Hi spam
I love spam
Hi spam
I love spam
done

gone

Examples : Using else Statement with Loops(while)


Python supports to have an else statement associated with a loop statement.
● If the else statement is used with a for loop, the else statement is executed when the loop has
exhausted iterating the list.
● If the else statement is used with a while loop, the else statement is executed when the
condition becomes false.
Ex:
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")

Output:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
Examples of while loops - the infinite loop

x=1
while x:
print 'Hi spam'
x=x+1
print 'I love spam'
print 'Press the Ctrl key and the C key together'
print 'to interupt this program...'
print 'done'
print 'gone'
Example: use of break to end an infinite loop
while 1:
print 'Spam'
answer = raw_input('Press y to end this
loop') if answer == 'y':
print 'Fries with that?'
break
print 'Have a '
print 'nice day!'
Example: use of continue in a loop
while 1:
print 'Spam'
answer = raw_input('Press y for large fries ')
if answer == 'y':
print 'Large fries with spam, mmmm, yummy '
continue
answer = raw_input('Had enough yet?
') if answer == 'y':
break
print 'Have a '
print 'nice
day!'

Example: the counter-controlled for loop

For Loop

Syntax:
for iterator_var in sequence:
statements(s)
Example:
for c in range (10):
print c
# Note: range (10) is 0 through 9
Example: the counter-controlled for loop
for c in range (5,10):
print c

# Note: range (5,10) is 5 through 9


Output:
5
6
7
8
9
Example: how to use a
n = [6,4,5,7,8,6,2,3,1] for loop in computing
s=0
for val in n: s=s+val
print(s) Output: 42

Example: For loop with


strings
for letter in 'Python': # First Example
print ('Current Letter :', letter)

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second
Example print ('Current fruit :', fruit)
print ("Good bye!")
Output:
Current Letter : P Current Letter : y Current
Letter : t Current Letter : h Current Letter : o
Current Letter : n Current fruit : banana Current
fruit : apple Current fruit : mango Good bye!

for c in range (1,6): if c == 3:


break print c

Output:
1
2 Example: 'break' with the for loop
Example: how to use a loop within a loop a nested for loop

print ("This is the start of the program")


for i in range (1,3):
for j in range (1,3):
for k in range (1,3):
print ("i: " + str(i) + " j: " + str(j) + " k: " + str(k))
print ("Hi")
Output:
This is the start of the program
i: 1 j: 1 k: 1
i: 1 j: 1 k: 2
i: 1 j: 2 k: 1
i: 1 j: 2 k: 2
i: 2 j: 1 k: 1
i: 2 j: 1 k: 2
i: 2 j: 2 k: 1
i: 2 j: 2 k: 2

EXIT() FUNCTION
exit()
exit() is defined in site.py and it works only if the site module is imported so it should be used in the
interpreter only. It is like a synonym of quit() to make the Python more user-friendly. It too gives a
message when printed:

Example:
# Python program to demonstrate
# exit()

for i in range(10):

# If the value of i becomes


# 5 then the program is forced
# to exit
if i == 5:

# prints the exit message


print(exit)
exit()
print(i)

Output:
0
1
2
3
4
Use exit() or Ctrl-D (i.e. EOF) to exit
DIFFERENCE BETWEEN BREAK, CONTINUE AND PASS

Break statement

The break statement is used to terminate the loop or statement in which it is present. After that, the
control will pass to the statements that are present after the break statement, if available. If the break
statement is present in the nested loop, then it terminates only those loops which
contains break statement.
Syntax:
break

Continue statement
This statement is used to skip over the execution part of the loop on a certain condition. After that, it
transfers the control to the beginning of the loop. Basically, it skips its following statements and
continues with the next iteration of the loop.
Syntax:
continue

Pass statement
As the name suggests pass statement simply does nothing. We use pass statement to write empty
loops. Pass is also used for empty control statements, functions and classes.
Syntax:
pass
Example:
# Python program to demonstrate
# difference between pass and
# continue statements

s = "geeks"

# Pass statement
for i in s:
if i == 'k':
print('Pass executed')
pass
print(i)

print()

# Continue statement
for i in s:
if i == 'k':
print('Continue executed')
continue
print(i)

OUTPUT:

g
e
e
Pass executed
k
s

g
e
e
Continue executed
s

Break Statement : It brings control out of the loop


Pass Statement:
We use pass statement to write empty loops. Pass is also used for empty control statement, function
and classes.
Continue statement: forces the loop to continue or execute the next iteration.

You might also like