Python Unit-I - Basics of Python Notes
Python Unit-I - Basics of Python Notes
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.
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 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.
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.
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.
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.
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.
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.[
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
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.
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
as To create an alias
or A logical operator
pass A null statement, a statement that will do nothing
# 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:
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
********************
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.
Output:
example of True, False, and, or, not keywords
True
True
True
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
Output:
One
Two
else block execute
else block execute
Output:
In this example, „def‟ keyword is used to define the GFG() function. Whereas „i‟ and „GFG‟ are
identifiers.
given number is even
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
Output:
2
3
4
5
6
# 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
del l[2]
Output:
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'd', 'e']
# declare fun2()
def fun2():
# declare global value gvar
global gvar
gvar = 100
# call fun1()
fun1()
# call fun2()
fun2()
Output:
10
Output:
1
2
3
4
5
6
money = []
print("sum of money:",sumOfMoney(money))
Output:
AssertionError: List is empty.
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
import math
print("factorial of 5 is :", math.factorial(5))
Output
factorial of 5 is : 120
Output
True
False
Output:
gcd of 345 and 675 is : 15
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
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = range(6) range
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
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"
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"
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)
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)
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
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
+= 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
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result not(x < 5 and x < 10)
is true
is not Returns True if both variables are not the same object x is not y
<< 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
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is not in not in Comparisons, identity, and membership operators
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.
Output:
<class 'int'>
<class 'float'>
10.0
<class 'float'>
21.0
<class 'float'>
# 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.
# 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.
# 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))
# 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.
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) 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)
# 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 '='.
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?')
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)
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}
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")
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
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
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
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!
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
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
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.
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.
if b > a:
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
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.