0% found this document useful (0 votes)
45 views40 pages

Python Unit-I - Basics of Python Notes

Uploaded by

Neel Barot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
45 views40 pages

Python Unit-I - Basics of Python Notes

Uploaded by

Neel Barot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 40

Unit-I Basics of Python

1.1 Introduction to Python, Python Features, Python Applications


1.2 Installing Python
1.3 Basic Structure of Python Program, Keywords, Identifiers, Data types, Variables, Operators, Type
Casting
1.4 Input-Output functions: input, print
1.5 Introduction to Control Structures
1.6 Decision Making Structures: if, if-else statements, Nested if-else and if-elif-else statements
1.7 Loops : for loop, while loop, Nested loops,
1.8 break, continue and pass statements

1.1Introduction to Python, Python Features, Python Applications


History of Python
Python is a general purpose, high-level, interpreted programming language developed by Guido van
Rossum in the late 1980s at the National Research Institute for Mathematics and Computer Science in
the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
and Unix shell and other scripting languages.

Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public
License (GPL).

Python is now maintained by a core development team at the institute, although Guido van Rossum still
holds a vital role in directing its progress.

Python is one of the most popular and widely used programming language used for set of tasks including
console based, GUI based, web programming and data analysis.

Python is an easy to learn and simple programming language so even if you are new to programming,
you can learn python without facing any problems.

What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
 web development (server-side),
 software development,
 mathematics,
 system scripting.

What can Python do?


 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.

Why Python?
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is written.
This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.

Good to know
 The most recent major version of Python is Python 3. However, Python 2, although not being
updated with anything other than security updates, is still quite popular.
 In this tutorial Python will be written in a text editor. It is possible to write Python in an
Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are
particularly useful when managing larger collections of Python files.

Python Syntax compared to other programming languages


 Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this purpose.

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed
to be highly readable. It uses English keywords frequently where as other languages use punctuation, and
it has fewer syntactical constructions than other languages.

 Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
 Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.

Python's features include −


 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
 Easy-to-read − Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.
 A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode which allows interactive testing
and debugging of snippets of code.
 Portable − Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
 Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
 Scalable − Python provides a better structure and support for large programs than shell scripting.

Apart from the above-mentioned features, Python has a big list of good features, few are listed below-
 It supports functional and structured programming methods as well as OOP.
 It can be used as a scripting language or can be compiled to byte-code for building large
applications.
 It provides very high-level dynamic data types and supports dynamic type checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Python Features and Advantages


The following are some of the features in Python that are discussed below:

1. Easy to Code
Python is a very high-level programming language, yet it is effortless to learn. Anyone can learn to code
in Python in just a few hours or a few days. Mastering Python and all its advanced concepts, packages
and modules might take some more time. However, learning the basic Python syntax is very easy, as
compared to other popular languages like C, C++, and Java.

2. Easy to Read
Python code looks like simple English words. There is no use of semicolons or brackets, and the
indentations define the code block. You can tell what the code is supposed to do simply by looking at it.

3. Free and Open-Source


Python is developed under an OSI-approved open source license. Hence, it is completely free to use, even
for commercial purposes. It doesn't cost anything to download Python or to include it in your application.
It can also be freely modified and re-distributed. Python can be downloaded from the official Python
website.

4. Robust Standard Library


Python has an extensive standard library available for anyone to use. This means that programmers don‟t
have to write their code for every single thing unlike other programming languages. There are libraries
for image manipulation, databases, unit-testing, expressions and a lot of other functionalities. In addition
to the standard library, there is also a growing collection of thousands of components, which are all
available in the Python Package Index.

5. Interpreted
When a programming language is interpreted, it means that the source code is executed line by line, and
not all at once. Programming languages such as C++ or Java are not interpreted, and hence need to be
compiled first to run them. There is no need to compile Python because it is processed at runtime by the
interpreter.

6. Portable
Python is portable in the sense that the same code can be used on different machines. Suppose you write
a Python code on a Mac. If you want to run it on Windows or Linux later, you don‟t have to make any
changes to it. As such, there is no need to write a program multiple times for several platforms.

7. Object-Oriented and Procedure-Oriented


A programming language is object-oriented if it focuses design around data and objects, rather than
functions and logic. On the contrary, a programming language is procedure-oriented if it focuses more on
functions (code that can be reused). One of the critical Python features is that it supports both object-
oriented and procedure-oriented programming.

8. Extensible
A programming language is said to be extensible if it can be extended to other languages. Python code
can also be written in other languages like C++, making it a highly extensible language.

9. Expressive
Python needs to use only a few lines of code to perform complex tasks. For example, to display Hello
World, you simply need to type one line - print(“Hello World”). Other languages like Java or C would
take up multiple lines to execute this.

10. Support for GUI


One of the key aspects of any programming language is support for GUI or Graphical User Interface. A
user can easily interact with the software using a GUI. Python offers various toolkits, such as Tkinter,
wxPython and JPython, which allows for GUI's easy and fast development.

11. Dynamically Typed


Many programming languages need to declare the type of the variable before runtime. With Python, the
type of the variable can be decided during runtime. This makes Python a dynamically typed language.
For example, if you have to assign an integer value 20 to a variable “x”, you don‟t need to write int x =
20. You just have to write x = 15.

12. High-level Language


Python is a high-level programming language because programmers don‟t need to remember the system
architecture, nor do they have to manage the memory. This makes it super programmer-friendly and is
one of the key features of Python.

13. Simplify Complex Software Development


Python can be used to develop both desktop and web apps and complex scientific and numerical
applications. Python's data analysis features help you create custom big data solutions without so much
time and effort. You can also use the Python data visualization libraries and APIs to present data in a
more appealing way. Several advanced software developers use Python to accomplish high-end AI and
natural language processing tasks.

14. Other Advanced Programming Features


Python contains several advanced programming features such as generators (used to create iterators with
a different approach that most other languages) and list comprehensions (used to create new lists from
other iterables). Python also has automatic memory management eliminating the need to manually
allocate and free memory in the code.

Python Features
1) Easy to Learn and Use. Python is easy to learn as compared to other programming languages.
2) Expressive Language. Python can perform complex tasks using a few lines of code.
3) Interpreted Language. ...
4) Cross-platform Language. ...
5) Free and Open Source. ...
6) Object-Oriented Language. ...
7) Extensible.

Python is often used as a support language for software developers, for build control and management,
testing, and in many other ways. SCons for build control. Buildbot and Apache Gump for automated
continuous compilation and testing. Roundup or Trac for bug tracking and project management.

Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code
readability with the use of significant indentation. Python. Paradigm. Multi-paradigm: object-oriented,
procedural (imperative), functional, structured, reflective.
 Web Development.
 Data Science — including machine learning, data analysis, and data visualization.
 Scripting.
When he began implementing Python, Guido van Rossum was also reading the published scripts from
“Monty Python's Flying Circus”, a BBC comedy series from the 1970s. Van Rossum thought he needed a
name that was short, unique, and slightly mysterious, so he decided to call the language Python.

Python's main limitations include its performance and speed, memory management, support for
concurrency and parallelism, static typing, and web support. Python is an interpreted language executed
at runtime by a virtual machine or interpreter.

Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code
readability with the use of significant indentation.[

Python is dynamically typed and garbage-collected. It supports multiple programming paradigms,


including structured (particularly procedural), object-oriented and functional programming. It is often
described as a "batteries included" language due to its comprehensive standard library.

Guido van Rossum began working on Python in the late 1980s as a successor to the ABC programming
language and first released it in 1991 as Python 0.9.0.[37] Python 2.0 was released in 2000. Python 3.0,
released in 2008, was a major revision not completely backward-compatible with earlier versions.
Python 2.7.18, released in 2020, was the last release of Python 2
Python consistently ranks as one of the most popular programming languages.

Python Applications

Python is used in many application domains. Here's a sampling.


 The Python Package Index lists thousands of third party modules for Python.
Web and Internet Development
Python offers many choices for web development:
 Frameworks such as Django and Pyramid.
 Micro-frameworks such as Flask and Bottle.
 Advanced content management systems such as Plone and django CMS.
Python's standard library supports many Internet protocols:
 HTML and XML
 JSON
 E-mail processing.
 Support for FTP, IMAP, and other Internet protocols.
 Easy-to-use socket interface.
And the Package Index has yet more libraries:
 Requests, a powerful HTTP client library.
 Beautiful Soup, an HTML parser that can handle all sorts of oddball HTML.
 Feedparser for parsing RSS/Atom feeds.
 Paramiko, implementing the SSH2 protocol.
 Twisted Python, a framework for asynchronous network programming

Scientific and Numeric


Python is widely used in scientific and numeric computing:
 SciPy is a collection of packages for mathematics, science, and engineering.
 Pandas is a data analysis and modeling library.
 IPython is a powerful interactive shell that features easy editing and recording of a work session, and
supports visualizations and parallel computing.
 The Software Carpentry Course teaches basic skills for scientific computing, running bootcamps and
providing open-access teaching materials.

Education
Python is a superb language for teaching programming, both at the introductory level and in more
advanced courses.
 Books such as How to Think Like a Computer Scientist, Python Programming: An Introduction to
Computer Science, and Practical Programming.
 The Education Special Interest Group is a good place to discuss teaching issues.
Desktop GUIs
The Tk GUI library is included with most binary distributions of Python.
Some toolkits that are usable on several platforms are available separately:
 wxWidgets
 Kivy, for writing multitouch applications.
 Qt via pyqt or pyside
Platform-specific toolkits are also available:
 GTK+
 Microsoft Foundation Classes through the win32 extensions
Software Development
Python is often used as a support language for software developers, for build control and management,
testing, and in many other ways.
 SCons for build control.
 Buildbot and Apache Gump for automated continuous compilation and testing.
 Roundup or Trac for bug tracking and project management.
Business Applications
Python is also used to build ERP and e-commerce systems:
 Odoo is an all-in-one management software that offers a range of business applications that form a
complete suite of enterprise management applications.
 Tryton is a three-tier high-level general purpose application platform.

What is Python? Executive Summary

Python is an interpreted, object-oriented, high-level programming language with dynamic


semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding,
make it very attractive for Rapid Application Development, as well as for use as a scripting or glue
language to connect existing components together. Python's simple, easy to learn syntax emphasizes
readability and therefore reduces the cost of program maintenance. Python supports modules and
packages, which encourages program modularity and code reuse. The Python interpreter and the
extensive standard library are available in source or binary form without charge for all major platforms,
and can be freely distributed.

Often, programmers fall in love with Python because of the increased productivity it provides. Since
there is no compilation step, the edit-test-debug cycle is incredibly fast. Debugging Python programs is
easy: a bug or bad input will never cause a segmentation fault. Instead, when the interpreter discovers an
error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack
trace. A source level debugger allows inspection of local and global variables, evaluation of arbitrary
expressions, setting breakpoints, stepping through the code a line at a time, and so on. The debugger is
written in Python itself, testifying to Python's introspective power. On the other hand, often the quickest
way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle
makes this simple approach very effective.

1.2Installing Python
As per Lab Manual Practical 1

1.3Basic Structure of Python Program, Keywords, Identifiers, Data types, Variables,


Operators, Type Casting
Python Keywords
Python has a set of keywords that are reserved words that cannot be used as variable names, function
names, or any other identifiers:
Keyword Description

and A logical operator

as To create an alias

assert For debugging

async It is used to create asynchronous coroutine.

await It releases the flow of control back to the event loop.

break To break out of a loop

class To define a class

continue To continue to the next iteration of a loop

def To define a function

del To delete an object

elif Used in conditional statements, same as else if

else Used in conditional statements

except Used with exceptions, what to do when an exception occurs

False Boolean value, result of comparison operations

finally Used with exceptions, a block of code that will be executed no


matter if there is an exception or not

for To create a for loop

from To import specific parts of a module

global To declare a global variable

if To make a conditional statement

import To import a module

in To check if a value is present in a list, tuple, etc.

is To test if two variables are equal

lambda To create an anonymous function

None Represents a null value

nonlocal To declare a non-local variable

not A logical operator

or A logical operator
pass A null statement, a statement that will do nothing

raise To raise an exception

return To exit a function and return a value

True Boolean value, result of comparison operations

try To make a try...except statement

while To create a while loop

with Used to simplify exception handling

yield To end a function, returns a generator

Rules for Keywords in Python


 Python keywords cannot be used as identifiers.
 All the keywords in python should be in lowercase except True and False.

# code
import keyword

print(keyword.kwlist)

Output
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif ', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']

Python keywords are special reserved words that have specific meanings and purposes and can‟t be used
for anything but those specific purposes. These keywords are always available—you‟ll never have to
import them into your code.

Python keywords are different from Python‟s built-in functions and types. The built-in functions and
types are also always available, but they aren‟t as restrictive as the keywords in their usage.
An example of something you can’t do with Python keywords is assign something to them. If you try,
then you‟ll get a SyntaxError. You won‟t get a SyntaxError if you try to assign something to a built-in
function or type, but it still isn‟t a good idea. For a more in-depth explanation of ways keywords can be
misused, check out Invalid Syntax in Python: Common Reasons for SyntaxError.

As of Python 3.8, there are thirty-five keywords in Python. Here they are with links to the relevant
sections throughout the rest of this article:

False await else import pass


None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

You can use these links to jump to the keywords you‟d like to read about, or you can continue reading for
a guided tour.
>>> help("keywords")
>>> help("pass")
The "pass" statement
********************

pass_stmt ::= "pass"

"pass" is a null operation — when it is executed, nothing happens. It


is useful as a placeholder when a statement is required syntactically,
but no code needs to be executed, for example:

def f(arg): pass # a function that does nothing (yet)

class C: pass # a class with no methods (yet)

Python also provides a keyword module for working with Python keywords in a programmatic way.
The keyword module in Python provides two helpful members for dealing with keywords:
1. kwlist provides a list of all the Python keywords for the version of Python you‟re running.
2. iskeyword() provides a handy way to determine if a string is also a keyword.
To get a list of all the keywords in the version of Python you‟re running, and to quickly determine how
many keywords are defined, use keyword.kwlist:
>>>
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', ...
>>> len(keyword.kwlist)

Identifiers

Python Identifier is the name we give to identify a variable, function, class, module or other object. That
means whenever we want to give an entity a name, that's called identifier. Sometimes variable and
identifier are often misunderstood as same but they are not

Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module, etc. The identifier is a
combination of character digits and an underscore. They are case-sensitive i.e., „num‟ and „Num‟ and
„NUM‟ are three different identifiers in python. It is a good programming practice to give meaningful
names to identifiers to make the code understandable.
We can also use the Python string isidentifier() method to check whether a string is a valid identifier or
not.

Rules for Naming Python Identifiers


 It cannot be a reserved python keyword.
 It should not contain white space.
 It can be a combination of A-Z, a-z, 0-9, or underscore.
 It should start with an alphabet character or an underscore ( _ ).
 It should not contain any special character other than an underscore ( _ ).

Examples of Python Identifiers


Valid identifiers:
 var1
 _var1
 _1_var
 var_1
Invalid Identifiers
 !var1
 1var
 1_var
 var#1
 var 1

Python Keywords and Identifiers Examples

Example 1: Example of and, or, not, True, False keywords.

print("example of True, False, and, or, not keywords")

# compare two operands using and operator


print(True and True)

# compare two operands using or operator


print(True or False)

# use of not operator


print(not False)

Output:
example of True, False, and, or, not keywords
True
True
True

Example 2: Example of a break, continue keywords and identifier.


# execute for loop
for i in range(1, 11):

# print the value of i


print(i)

# check the value of i is less than 5


# if i lessthan 5 then continue loop
if i < 5:
continue

# if i greater than 5 then break loop


else:
break

Output:
In this example, „if‟ and „else‟ keywords are used to specify some conditions. Whereas „i‟ is a user-
defined variable which is an identifier that temporarily stores the value from 1 to 10.
1
2
3
4
5

Example 3: example of for, in, if, elif, and else keywords.


# run for loop
for t in range(1, 5):
# print one of t ==1
if t == 1:
print('One')
# print two if t ==2
elif t == 2:
print('Two')
else:
print('else block execute')

Output:
One
Two
else block execute
else block execute

Example 4: Example of def, if, and else keywords.

# define GFG() function using def keyword


def GFG():
i=20
# check i is odd or not
# using if and else keyword
if(i % 2 == 0):
print("given number is even")
else:
print("given number is odd")

# call GFG() function


GFG()

Output:

In this example, „def‟ keyword is used to define the GFG() function. Whereas „i‟ and „GFG‟ are
identifiers.
given number is even

Example 5: Example of try, except, raise.

def fun(num):
try:
r = 1.0/num
except:
print('Exception raises')
return
return r

print(fun(10))
print(fun(0))

Output:
In this example, „r‟ and „num‟ are user-defined variables.
0.1
Exception raises
None

Example 6: Example of a lambda keyword.

# define a anonymous using lambda keyword


# this lambda function increment the value of b
a = lambda b: b+1

# run a for loop


for i in range(1, 6):
print(a(i))

Output:
2
3
4
5
6

Example 7: use of return keyword.

# define a function
def fun():
# declare a variable
a=5
# return the value of a
return a
# call fun method and store
# it's return value in a variable
t = fun()
# print the value of t
print(t)
Output:
5

Example 8: use of a del keyword.


# create a list
l = ['a', 'b', 'c', 'd', 'e']

# print list before using del keyword


print(l)

del l[2]

# print list after using del keyword


print(l)

Output:
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'd', 'e']

Example 9: use of global keyword


# declare a variable
gvar = 10
# create a function
def fun1():
# print the value of gvar
print(gvar)

# declare fun2()
def fun2():
# declare global value gvar
global gvar
gvar = 100

# call fun1()
fun1()

# call fun2()
fun2()

Output:
10

Example 10: example of yield keyword.


def Generator():
for i in range(6):
yield i+1
t = Generator()
for i in t:
print(i)

Output:
1
2
3
4
5
6

Example 11: Use of assert keyword.


def sumOfMoney(money):
assert len(money) != 0,"List is empty."
return sum(money)

money = []
print("sum of money:",sumOfMoney(money))

Output:
AssertionError: List is empty.

Example 12: Use of pass keyword


class GFG:
pass
g = GFG

Output
Example 13: Use of finally keyword
def divide(a, b):
try:
c = a/b
print("Inside try block")
except:
print("Inside Exception block")
finally:
print("Inside finally block")
divide(3,2)
divide(3,0)

Output
Inside try block
Inside finally block
Inside Exception block
Inside finally block

Example 14: Use of import keyword

import math
print("factorial of 5 is :", math.factorial(5))

Output
factorial of 5 is : 120

Example 15: Use of is keyword


x = 10
y = 20
z=x
print(x is z)
print(x is y)

Output
True
False

Example 16: Use of from keyword


from math import gcd
print("gcd of 345 and 675 is : ", gcd(345, 675))

Output:
gcd of 345 and 675 is : 15

FAQs on Python Keywords and Identifiers

Q: What are Keywords and Identifiers in Python?


Answer: Keywords in Python are predefined words that have a special meaning to the interpreter.
They are reserved words that are used to perform a specific task in Python programming.
Identifiers in Python are names given to different parts of a Python program like variables, functions,
classes, etc. They are user-defined and the users must follow a set of rules to define them in a python
program.

Q: What is the difference between a Keyword and an Identifier in Python?


Answer: A Keyword in Python is a predefined reserved word that is meaningful to the interpreter and
performs a specific task. Whereas, an identifier is a userdefined word given to different parts of python
programming. An identifier can be a name given to a variable, function or a class.

Data Types
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Getting the Data Type


You can get the data type of any object by using the type() function:
Example
Print the data type of the variable x:
x=5
print(type(x))

Setting the Data Type


In Python, the data type is set when you assign a value to a variable:
Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset


x = True bool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

x = None NoneType

Setting the Specific Data Type


If you want to specify the data type, you can use the following constructor functions:
Example Data Type

x = str("Hello World") str

x = int(20) int

x = float(20.5) float

x = complex(1j) complex

x = list(("apple", "banana", "cherry")) list

x = tuple(("apple", "banana", "cherry")) tuple

x = range(6) range

x = dict(name="John", age=36) dict

x = set(("apple", "banana", "cherry")) set

x = frozenset(("apple", "banana", "cherry")) frozenset

x = bool(5) bool

x = bytes(5) bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

Variables
Variables are containers for storing data values.

Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0

Get the Type


You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes?
String variables can be declared either by using single or double quotes:
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
#A will not overwrite a

Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for Python variables:
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)
 A variable name cannot be any of the Python keywords.

Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Multi Words Variable Names


Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"

Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"

Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"

Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

One Value to Multiple Variables


And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.
Example
Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)

Output Variables
The Python print() function is often used to output variables.
Example
x = "Python is awesome"
print(x)

In the print() function, you output multiple variables, separated by a comma:


Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
You can also use the + operator to output multiple variables:
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

For numbers, the + character works as a mathematical operator:


Example
x=5
y = 10
print(x + y)
In the print() function, when you try to combine a string and a number with the + operator, Python will
give you an error:
Example
x=5
y = "John"
print(x + y)

The best way to output multiple variables in the print() function is to separate them with commas, which
even support different data types:
Example
x=5
y = "John"
print(x, y)

Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as global
variables.
Global variables can be used by everyone, both inside of functions and outside.

Example
Create a variable outside of a function, and use it inside the function
x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

If you create a variable with the same name inside a function, this variable will be local, and can only be
used inside the function. The global variable with the same name will remain as it was, global and with
the original value.
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)

The global Keyword


Normally, when you create a variable inside a function, that variable is local, and can only be used inside
that function.
To create a global variable inside a function, you can use the global keyword.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"

myfunc()
print("Python is " + x)

Also, use the global keyword if you want to change a global variable inside a function.
Example
To change the value of a global variable inside a function, refer to the variable by using
the global keyword:
x = "awesome"

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)

Python Operators

Operators are used to perform operations on variables and values.


In the example below, we use the + operator to add together two values:
Example
print(10 + 5)
Python divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical operations:
Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:


Operator Example Same As
= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Python Comparison Operators


Comparison operators are used to compare two values:
Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Python Logical Operators


Logical operators are used to combine conditional statements:
Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result not(x < 5 and x < 10)
is true

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are actually the same
object, with the same memory location:
Operator Description Example

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

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

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:
Operator Description Example

in Returns True if a sequence with the specified x in y


value is present in the object

not in Returns True if a sequence with the specified x not in y


value is not present in the object

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:
Operator Name Description Example

& AND Sets each bit to 1 if both bits are 1 x&y

| OR Sets each bit to 1 if one of two bits is 1 x|y

^ XOR Sets each bit to 1 if only one of two x^y


bits is 1

~ NOT Inverts all the bits ~x

<< Zero fill left shift Shift left by pushing zeros in from the x << 2
right and let the leftmost bits fall off

>> Signed right shift Shift right by pushing copies of the x >> 2
leftmost bit in from the left, and let the
rightmost bits fall off

Operator Precedence
Operator precedence describes the order in which operations are performed.
Example
Parentheses has the highest precedence, meaning that expressions inside parentheses must be evaluated
first:
print((6 + 3) - (6 + 3))

Example
Multiplication * has higher precedence than addition +, and therefor multiplications are evaluated before
additions:
print(100 + 5 * 3)

The precedence order is described in the table below, starting with the highest precedence at the top:
Operator Description
() Parentheses

** Exponentiation

+x -x ~x Unary plus, unary minus, and bitwise NOT

* / // % Multiplication, division, floor division, and


modulus

+ - Addition and subtraction

<< >> Bitwise left and right shifts

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

== != > >= < <= is is not in not in Comparisons, identity, and membership operators

not Logical NOT

and AND

or OR

If two operators have the same precedence, the expression is evaluated from left to right.

Example
Addition + and subtraction - has the same precedence, and there for we evaluate the expression from left
to right:
print(5 + 4 - 7 + 3)

Type Casting
The conversion of one data type into the other data type is known as type casting in python or type
conversion in python. Python supports a wide variety of functions or methods like: int(), float(), str(),
ord(), hex(), oct(), tuple(), set(), list(), dict(), etc.
Type Casting in Python (Implicit and Explicit)

Type Casting is the method to convert the Python variable datatype into a certain data type in order to
perform the required operation by users. In this article, we will see the various techniques for
typecasting. There can be two types of Type Casting in Python:
 Python Implicit Type Conversion
 Python Explicit Type Conversion
Implicit Type Conversion in Python
In this, method, Python converts the datatype into another datatype automatically. Users don‟t have to
involve in this process.

# Python program to demonstrate


# implicit type Casting

# Python automatically converts


# a to int
a=7
print(type(a))
# Python automatically converts
# b to float
b = 3.0
print(type(b))

# Python automatically converts


# c to float as it is a float addition
c=a+b
print(c)
print(type(c))

# Python automatically converts


# d to float as it is a float multiplication
d=a*b
print(d)
print(type(d))

Output:
<class 'int'>
<class 'float'>
10.0
<class 'float'>
21.0
<class 'float'>

Explicit Type Conversion in Python


In this method, Python needs user involvement to convert the variable data type into the required data
type.

Examples of Type Casting in Python


Mainly type casting can be done with these data type functions:
 Int(): Python Int() function take float or string as an argument and returns int type object.
 float(): Python float() function take int or string as an argument and return float type object.
 str(): Python str() function takes float or int as an argument and returns string type object.
Python Convert Int to Float
Here, we are Converting Int to Float in Python with the float() function.

# Python program to demonstrate


# type Casting

# int variable
a=5

# typecast to float
n = float(a)

print(n)
print(type(n))

Output:
5.0
<class 'float'>
Python Convert Float to Int
Here, we are Converting Float to int datatype in Python with int() function.
# Python program to demonstrate
# type Casting

# int variable
a = 5.9

# typecast to int
n = int(a)

print(n)
print(type(n))

Output:
5
<class 'int'>
Python Convert int to String
Here, we are Converting int to String datatype in Python with str() function.

# Python program to demonstrate


# type Casting

# int variable
a=5

# typecast to str
n = str(a)

print(n)
print(type(n))

Output:
5
<class 'str'>
Python Convert String to float
Here, we are casting string data type into float data type with float() function.

# Python program to demonstrate


# type Casting

# string variable
a = "5.9"

# typecast to float
n = float(a)

print(n)
print(type(n))

Output:
5.9
<class 'float'>
Python Convert string to int
Here, we are Converting string to int datatype in Python with int() function. If the given string is
not number, then it will throw an error.

# string variable
a = "5"
b = 't'

# typecast to int
n = int(a)

print(n)
print(type(n))

print(int(b))
print(type(b))

Output:
5
<class 'int'>
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[3], line 14
11 print(n)
12 print(type(n))
---> 14 print(int(b))
15 print(type(b))

ValueError: invalid literal for int() with base 10: 't'

Addition of string and integer Using Explicit Conversion


# integer variable
a=5
# string variable
b = 't'

# typecast to int
n = a+b

print(n)
print(type(n))

Output:
TypeError Traceback (most recent call last)
Cell In[5], line 10
7 b = 't'
9 # typecast to int
---> 10 n = a+b
12 print(n)
13 print(type(n))

Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be done with casting.
Python is an object-orientated language, and as such it uses classes to define data types, including its
primitive types.

Casting in python is therefore done using constructor functions:


 int() - constructs an integer number from an integer literal, a float literal (by removing all
decimals), or a string literal (providing the string represents a whole number)
 float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
 str() - constructs a string from a wide variety of data types, including strings, integer literals and
float literals
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Example
Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

Example
Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

1.4Input-Output functions: input, print


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 programming language.
Entered value is: Python is a programming 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}

1.5 Introduction to Control Structures


Most programs don't operate by carrying out a straightforward sequence of statements. A code is written
to allow making choices and several pathways through the program to be followed depending on shifts in
variable values.
All programming languages contain a pre-included set of control structures that enable these control
flows to execute, which makes it conceivable.
This tutorial will examine how to add loops and branches, i.e., conditions to our Python programs.
Types of Control Structures
Control flow refers to the sequence a program will follow during its execution.

Conditions, loops, and calling functions significantly influence how a Python program is controlled.
There are three types of control structures in Python:
o Sequential - The default working of a program
o Selection - This structure is used for making decisions by checking conditions and branching
o Repetition - This structure is used for looping, i.e., repeatedly executing a certain piece of a code
block.
Sequential
Sequential statements are a set of statements whose execution process happens in a sequence. The
problem with sequential statements is that if the logic has broken in any one of the lines, then the
complete source code execution will break.
Code
1. # Python program to show how a sequential control structure works
2.
3. # We will initialize some variables
4. # Then operations will be done
5. # And, at last, results will be printed
6. # Execution flow will be the same as the code is written, and there is no hidden flow
7. a = 20
8. b = 10
9. c = a - b
10. d = a + b
11. e = a * b
12. print("The result of the subtraction is: ", c)
13. print("The result of the addition is: ", d)
14. print("The result of the multiplication is: ", e)
Output:
The result of the subtraction is: 10
The result of the addition is :
30
The result of the multiplication is: 200
Selection/Decision Control Statements
The statements used in selection control structures are also referred to as branching statements or, as their
fundamental role is to make decisions, decision control statements.
A program can test many conditions using these selection statements, and depending on whether the
given condition is true or not, it can execute different code blocks.
There can be many forms of decision control structures. Here are some most commonly used control
structures:
o Only if
o if-else
o The nested if
o The complete if-elif-else
Simple if
If statements in Python are called control flow statements. The selection statements assist us in running a
certain piece of code, but only in certain circumstances. There is only one condition to test in a basic if
statement.
The if statement's fundamental structure is as follows:
Syntax
1. if <conditional expression> :
2. The code block to be executed if the condition is True
These statements will always be executed. They are part of the main code.
All the statements written indented after the if statement will run if the condition giver after the if the
keyword is True. Only the code statement that will always be executed regardless of the if the condition
is the statement written aligned to the main code. Python uses these types of indentations to identify a
code block of a particular control flow statement. The specified control structure will alter the flow of
only those indented statements.
Here are a few instances:
Code
1. # Python program to show how a simple if keyword works
2.
3. # Initializing some variables
4. v = 5
5. t = 4
6. print("The initial value of v is", v, "and that of t is ",t)
7.
8. # Creating a selection control structure
9. if v > t :
10. print(v, "is bigger than ", t)
11. v -= 2
12.
13. print("The new value of v is", v, "and the t is ",t)
14.
15. # Creating the second control structure
16. if v < t :
17. print(v , "is smaller than ", t)
18. v += 1
19.
20. print("the new value of v is ", v)
21.
22. # Creating the third control structure
23. if v == t:
24. print("The value of v, ", v, " and t,", t, ", are equal")
Output:
The initial value of v is 5 and that of t is 4
5 is bigger than 4
The new value of v is 3 and the t is 4
3 is smaller than 4
the new value of v is
4
The value of v,
4 and t, 4, are equal
if-else
If the condition given in if is False, the if-else block will perform the code t=given in the else block.
Code
1. # Python program to show how to use the if-else control structure
2.
3. # Initializing two variables
4. v = 4
5. t = 5
6. print("The value of v is ", v, "and that of t is ", t)
7.
8. # Checking the condition
9. if v > t :
10. print("v is greater than t")
11. # Giving the instructions to perform if the if condition is not true
12. else :
13. print("v is less than t")
Output:
The value of v is 4 and that of t is 5
v is less than t
Repetition
To repeat a certain set of statements, we use the repetition structure.
There are generally two loop statements to implement the repetition structure:
o The for loop
o The while loop
For Loop
We use a for loop to iterate over an iterable Python sequence. Examples of these data structures are lists,
strings, tuples, dictionaries, etc. Under the for loop code block, we write the commands we want to
execute repeatedly for each sequence item.
Code
1. # Python program to show how to execute a for loop
2.
3. # Creating a sequence. In this case, a list
4. l = [2, 4, 7, 1, 6, 4]
5.
6. # Executing the for loops
7. for i in range(len(l)):
8. print(l[i], end = ", ")
9. print("\n")
10. for j in range(0,10):
11. print(j, end = ", ")
Output:
2, 4, 7, 1, 6, 4,

0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
While Loop
While loops are also used to execute a certain code block repeatedly, the difference is that loops continue
to work until a given precondition is satisfied. The expression is checked before each execution. Once the
condition results in Boolean False, the loop stops the iteration.
Code
1. # Python program to show how to execute a while loop
2.
3. b = 9
4. a = 2
5.
6. # Starting the while loop
7. # The condition a < b will be checked before each iteration
8. while a < b:
9. print(a, end = " ")
10. a=a+1
11. print("While loop is completed")
Output:
2 3 4 5 6 7 8 While loop is completed

1.6 Decision Making Structures: if, if-else statements, Nested if-else and if-elif- else
statements
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.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

Ex 1:
x = 'spam'
if x == 'spammy':
50
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.

Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

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

A nested if example - using if/else


Ex 1:
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:
51
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:
statement
Ex 1:
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

1.7 Loops: for loop, while loop, Nested loops


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 for loop in computing


n = [6,4,5,7,8,6,2,3,1]
s=0
for val in n:
s=s+val
print(s)
Output:

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!

Example: 'break' with the for loop


for c in range (1,6):
if c == 3:
break
print c
Output:
1
2

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

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.
for loop, the else statement is executed when the loop has
exhausted iterating the list.

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!'

1.8 break, continue and pass statements


The break Keyword
If you need to exit a loop early, then you can use the break keyword. This keyword will work in
both for and while loops:
for <element> in <container>:
if <expr>:
break
An example of using the break keyword would be if you were summing the integers in a list of numbers
and wanted to quit when the total went above a given value:
>>>
>>> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> total_sum = 0
>>> for num in nums:
... total_sum += num
... if total_sum > 10:
... break
...
>>> total_sum
15

Both the Python keywords break and continue can be useful tools when working with loops. For a deeper
discussion of their uses, check out Python “while” Loops (Indefinite Iteration). If you‟d like to explore
another use case for the break keyword, then you can learn how to emulate do-while loops in Python.

The continue Keyword

Python also has a continue keyword for when you want to skip to the next loop iteration. Like in most
other programming languages, the continue keyword allows you to stop executing the current loop
iteration and move on to the next iteration:
for <element> in <container>:
if <expr>:
continue
The continue keyword also works in while loops. If the continue keyword is reached in a loop, then the
current iteration is stopped, and the next iteration of the loop is started.

The pass Statement


if statements cannot be empty, but if you for some reason have an if statement with no content, put in
the pass statement to avoid getting an error.
Example
a = 33
b = 200

if b > a:
pass

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