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

unit1 python (1)

The document provides a comprehensive overview of Python programming, including its history, features, advantages, applications, and structure. It covers essential concepts such as data types, variables, control structures, and the Python interpreter, along with practical examples and lab exercises. Additionally, it highlights the increasing popularity of Python due to its readability, versatility, and extensive library support.

Uploaded by

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

unit1 python (1)

The document provides a comprehensive overview of Python programming, including its history, features, advantages, applications, and structure. It covers essential concepts such as data types, variables, control structures, and the Python interpreter, along with practical examples and lab exercises. Additionally, it highlights the increasing popularity of Python due to its readability, versatility, and extensive library support.

Uploaded by

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

Duration

24 24 24 24 24
(hour)
An introduction to The Structure of Introduction to Introduction to Introduction to
SLO-1 python programming Strings Lists function classes
S- Functions as
1 SLO-2 Structure of a Python The Subscript List literals Abstraction Design with
program Operator Mechanisms Classes
understanding Program using Functions Objects and
S- SLO-1 Python interpreter subscript operator Basic list operators Eliminate
Redundancy Classes
2 understanding Slicing for Replacing an Functions Hide An example for
SLO-2 Python Shell Substrings Element in a List Complexity class
Functions Support
Program for slicing Replacing an General Methods
SLO-1 Datatypes substrings Element in a List with Systematic Docstrings
S- Variations
3 Testing for a Example program to Functions Support
Example program Substring with the Replace an Element the Division of Method
SLO-2 using all data types Definitions
in Operator in a List Labor
Program using List Methods for Defining a
SLO-1 String literals substring Inserting Elements Recursive Function The init Method
S- The Positional Program to List
4 SLO-2 Escape Sequences System for Methods for Tracing a
Representing Inserting Elements Recursive Function Instance Variables
Numbers
SLO-1 Lab 1: Write a Lab 7: Program to
S Python code to Lab 4:Make a Transpose a Matrix Lab 10: Program Lab 13: Program
display system simple calculator Program to List using recursive using classes and
5-8 SLO-2 information Methods for function methods
usingpywhois Inserting Elements
Using Recursive
Definitions to
S- SLO-1 String Concatenation Converting
to decimal
binary List Methods for
Removing Elements Construct The str Method
Recursive
9 Functions
Variables and the Program to convert Searching a List Recursion in Accessors
SLO-2 assignment statement binary to decimal Sentence Structure
Example program Converting decimal Sorting a List Infinite Recursion Mutators
SLO-1 using variables to binary
S- The Costs and
10 SLO-2 Program Comments Program to convert Mutator Methods Benefits of The Lifetime of
and Doc Strings decimal to binary Recursion Objects
Managing a Rules for Defining
SLO-1 Numerical Datatypes String Methods Aliasing Program’s a Simple Class
S- Namespace
Module Variables, Rational Number
11 Program using
SLO-2 Character sets string method Aliasing side effects Parameters,
Temporary
and Arithmetic and
Operator
Variables Overloading
Arithmetic Octal and Equality: Object Comparison
S- SLO-1 expressions Hexadecimal Identity Scope Methods
Numbers
12 Understanding error Text Files and Structural Equality and the
SLO-2 messages Their Format Equivalence Lifetime eq Method
SLO-1 Lab 5: Find the Lab 8: Using a List Lab 11: Write the
Factorial
Lab 2: The Magic 8 Number of a to Find the Median code for a mapping Lab 14: Python
S
Ball is a toy used for Python Program to of a Set of Numbers that generates a list
of the absolute Program for
13- fortune-telling or
16
SLO-2
seeking advice. Convert Decimal to Program
sorting
using
and values of the Operator
overloading
Binary, Octal and searching numbers in a list
Hexadecimal named numbers.
Writing Text to a Tuples Default (Keyword) Using pickle for
SLO-1 Logical operators File Arguments Permanent
S- Storage of Objects
17 Definite iteration : Writing Numbers Creation
tuples
of several Functions as First- Input of Objects
and the try-except
SLO-2 For loop to a File Class Data Objects Statement
Example program Reading Text from Dictionaries Inheritance
S- SLO-1 using for loop a File Mapping Hierarchies and
Modeling
18 Formatting text for Reading Numbers Dictionary Literals Polymorphic
SLO-2 output from a File Filtering Methods
Selection : if and if Example program Adding Keys and
SLO-1 else statement to read and write Replacing Values Reducing Abstract Classes
S- text and numbers
Accessing Files Using lambda to The Costs and
19 Example program Benefits of Object-
SLO-2 using if and if else and Directories on Accessing Values Create Anonymous Oriented
Disk Functions Programming
Conditional iteration Manipulating Files
and Directories on Removing Keys Creating Jump Event-Driven
SLO-1 :while loop Tables Programming
S- Disk
20 Example program Example program Traversing a Example program Example for
SLO-2 using while loop to access and Dictionary using functions Event-Driven
manipulate files Programming
SLO-1 Lab 9: When the
user enters a
statement, the
program responds in
one of two ways: 1
With a randomly
chosen hedge, such Lab 12: Write the
as “Please tell me code for a filtering
Lab 3: Check more.” 2 By
whether a number is Lab 6: Program to changing some key that generates a list
of the positive Lab 15: Program
S words in the user’s
prime or not, read and write text input string and numbers in a list using
21-
SLO-2 Python Program to and numbers appending this named numbers. polymorphism,
24 Generate a Random string to a randomly You should use a abstract classes
Number chosen qualifier. lambda to create
Thus, to “My the auxiliary
teacher always plays function.
favorites,” the
program might
reply, “Why do you
say that your
teacher always plays
favorites?”

Learning
Resourc Kenneth A. Lambert, (2011), “The Fundamentals of Python: First Programs”, Cengage Learning
es

Unit 1
Introduction To PYTHON
Python is a widely used general-purpose, high level programming language. It was created by Guido van Rossum
in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code
readability, and its syntax allows programmers to express their concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.

There are two major Python versions: Python 2 and Python 3. Both are quite different.

History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties 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.

Reason for increasing popularity

1. Emphasis on code readability, shorter codes, ease of writing


2. Programmers can express logical concepts in fewer lines of code in comparison to languages such as
C++ or Java.
3. Python supports multiple programming paradigms, like object-oriented, imperative and functional
programming or procedural.
4. There exists inbuilt functions for almost all of the frequently used concepts.
5. Philosophy is “Simplicity is the best”.

LANGUAGE FEATURES

• Interpreted
• There are no separate compilation and execution steps like C and C++.
• Directly run the program from the source code.
• Internally, Python converts the source code into an intermediate form called bytecodes which
is then translated into native language of specific computer to run it.
• No need to worry about linking and loading with libraries, etc.
• Platform Independent
• Python programs can be developed and executed on multiple operating system platforms.
• Python can be used on Linux, Windows, Macintosh, Solaris and many more.
• Free and Open Source; Redistributable
• High-level Language
• In Python, no need to take care about low-level details such as managing the memory used by
the program.
• Simple
• Closer to English language;Easy to Learn
• More emphasis on the solution to the problem rather than the syntax
• Embeddable
• Python can be used within C/C++ program to give scripting capabilities for the program’s
users.
• Robust:
• Exceptional handling features
• Memory management techniques in built
• Rich Library Support
• The Python Standard Library is very vast.
• Known as the “batteries included” philosophy of Python ;It can help do various things
involving regular expressions, documentation generation, unit testing, threading, databases,
web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.
• Besides the standard library, there are various other high-quality libraries such as the Python
Imaging Library which is an amazingly simple image manipulation library.
Advantages :
1. Presence of third-party modules
2. Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc)
3. Open source and community development
4. Versatile, Easy to read, learn and write
5. User-friendly data structures
6. High-level language
7. Dynamically typed language(No need to mention data type based on the value assigned, it takes data
type)
8. Object-oriented language
9. Portable and Interactive
10. Ideal for prototypes – provide more functionality with less coding
11. Highly Efficient(Python’s clean object-oriented design provides enhanced process control, and the
language is equipped with excellent text processing and integration capabilities, as well as its own unit
testing framework, which makes it more efficient.)
12. (IoT)Internet of Things Opportunities
13. Interpreted Language
14. Portable across Operating systems

Applications :
1. GUI based desktop applications
2. Graphic design, image processing applications, Games, and Scientific/ computational Applications
3. Web frameworks and applications
4. Enterprise and Business applications
5. Operating Systems
6. Education
7. Database Access
8. Language Development
9. Prototyping
10. SoftwareDevelopment

Organizations using Python :


1. Google(Components of Google spider and Search Engine)
2. Yahoo(Maps)
3. YouTube
4. Mozilla
5. Dropbox
6. Microsoft
7. Cisco
8. Spotify
9. Quora

Elements of Python Python has 4 components


1. IDLE (Python GUI): It is a cross platform GUI IntegratedDevelopment Environmental that is provided with
Python for editing and running a Python programs. It is a bundled set of software’s tools such as Python Shell
for Scripting programs and text editor for creating and modifying Python’s source code, an integrated
interactive debugger for finding error, help system etc.

2. Module Docs: This component allows us to access the python documents such as build in modules, DLLs,
libraries, packages etc.

3. Python (Command line): Python can also be access from the command line. Command line mode provide
very less features in comparison to IDLE but it is fast.

4. Python Manual : This component include various documents related to Python such as :installation cum
setup guide, tutorials, Python API , FAQs etc.

Python Interpreter

Python is a high level language. We know that computer understand machine language or binary language which
is also known as low level language. The job to translate programming code written in high level language to
low level language is done with the help of two type of softwares : compilers and interpreters.

Working of Compiler

Compiler is a special type of software it first check the source code of the complete program for the syntax errors,
if no error found in the program code then the source code of the program is converted to the machine code and
finally the executive file of the program is created. The executive file can be executed by the CPU and can
produce desired result as per the program requirements.

Working of Interpreter

Interpreter check the code of program line by line if no error is found it is converted into themachine code
and simultaneously gets executed by the CPU.

An interpreter is a computer program, which coverts each high-level program statement into themachine code.
This includes source code, pre-compiled code, and scripts. Both compiler and interpreters do the same job which
is converting higher level programming language to machine code. However, a compiler will convert the code
into machine code (create an exe) before program run. Interpreters convert code into machine code when the
program is run.

Atoms

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

atom: identifier | literal | enclosure


enclosure: parenth_form|list_display|dict_display|string_conversion

Indentation

Indentation in Python refers to the (spaces and tabs) that are used at the beginning of a statement. The statements
with the same indentation belong to the same group.
For Example a=2
print(a) if a==3 :
print(“hello world”) print(“HELLO WORLD”)
else :
print(“ bye world”) print(“ BYE WORLD”)

Structure of Python Program


The typical structure of a python program include 3 parts Import statements
// import statements are used to include library files to the python program
Function definitions
//This section include the definitions of various functions written in a Python ProgramProgram statements
// This section include the set of statements for solving the given problem.

Identifier
Identifier is a name given to various programming elements such as a variable, function, class,module or any
other object. Following are the rules to create an identifier.
1. The allowed characters are a-z, A-Z, 0-9 and underscore (_)
2. It should begin with an alphabet or underscore
3. It should not be a keyword
4. It is case sensitive
5. No blank spaces are allowed.
6. It can be of any size
Valid identifiers examples : si, rate_of_interest, student1, ageStudentInvalid identifier examples : rate of interest,
1student, @age Keywords
Keywords are the identifiers which have a specific meaning in python, there are 33 keywords inpython. These
may vary from version to version.
False None True and
as assert 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

Variables and Types


When we create a program, we often need store values so that it can be used in a program. Weuse variables to
store data which can be manipulated by the computer program.
Every variable has:
A. Name and memory location where it is stored.A variable name:
1. Can be of any size
2. Have allowed characters, which are a-z, A-Z, 0-9 and underscore (_)
3. should begin with an alphabet or underscore
4. should not be a keyword
It is a good practice to follow these identifier naming conventions:
1. Variable name should be meaningful and short
2. Generally, they are written in lower case letters

B. A type or datatype which specify the nature of variable (what type of values can be stored inthat variable and
what operations can be performed)
We can check the type of the variable by using type command
>>> type(variable_name)
C. A value

Various datatypes available in python are as follow :

1. Number
Number data type stores Numerical Values. These are of three different types:

a) Integer & Long


b) Float/floating point
c) Complex

Integers are the whole numbers consisting of + or – sign like 100000, -99, 0, 17. Whilewriting a large
integer value

e.g. age=19
salary=20000

Floating Point: Numbers with fractions or decimal point are called floating point numbers.A floating point
number will consist of sign (+,-) and a decimal sign(.)
e.g. temperature= -21.9, growth_rate= 0.98333328

The floating point numbers can be represented in scientific notation such as

-2.0X 105 will be represented as -2.0e52.0X10-5 will be 2.0E-5

Complex: Complex number is made up of two floating point values, one each for real and imaginary part. For
accessing different parts of a variable x we will use x.real and x.imag. Imaginary part of the number is
represented by j instead of i, so 1+0j denotes zero imaginary part.
Example
>>> x = 1+0j
>>> print x.real,x.imag1.0 0.0

2. None
This is special data type with single value. It is used to signify the absence of value/false in asituation. It is
represented by None.

3. Sequence
A sequence is an ordered collection of items, indexed by positive integers. Three types ofsequence data
type available in Python are Strings, Lists & Tuples.

String: is an ordered sequence of letters/characters. They are enclosed in single quotes (‘’) or double (“”).
Example
>>> a = 'Ram'
>>>a=”Ram”

Lists: List is also a sequence of values of any type. Values in the list are called elements / items. The items of
list are accessed with the help of index (index start from 0). List is enclosed in square brackets.
Example
Student = [“Ajay”, 567, “CS”]
Tuples: Tuples are a sequence of values of any type, and are indexed by integers. They areimmutable i.e.
we cannot change the value of items of tuples . Tuples are enclosed in ().
Student = (“Ajay”, 567, “CS”)

4. Sets
Set is an unordered collection of values, of any type, with no duplicate entry. Sets are immutable.
Example
s = set ([1,2,3,4])

5. Dictionaries: Dictionaries store a key – value pairs, which are accessed using key. Dictionaryis enclosed in
curly brackets.
Example
d = {1:'a', 2:'b', 3:'c'}

Literals
A literal is a constant that appear directly in a program and this value does not change during the program
execution i.e. remain fixed.
Example:
Num1=5 Principle_amount= 5000.00

Here 5 and 5000.00 are literals. Python support the following literals
• Numeric literals
• String Literals
• Special Literals
• Collection Literals

Operators and Operands


Operators are special symbols which represents specific operations. They are applied on operand(s), which
can be values or variables. Same operator can behave differently on different data types. Operators when applied
on operands form an expression. Following is the partial list of operators:
Arithmetic Operators : Arithmetic operators are used to apply arithmetic operation.

Relational Operators : Relation operators are used to compare two items. The result of relational operator is
True or False.
Logical Operators
Logical Operators give the logical relationship based upon the truth table.
AND OR NOT
Value1 Value2 Result Value1 Value2 Result Value1 Result
False False False False False False True False
False True False False True True False True
True False False True False True
True True True True True True

Bitwise Operators : Bitwise operators are applied upon the bits.

Membership Operator
Assignment Operators
Assignment operators are used to assign a value to the variable.

Identity Operator
Operator Precedence :

Input and Output Statements

How to print/display a statement in Python A statement is print with the help of print() method.
The syntax to use print() is as follow :
>>>print(“message to be printed”)Or
>>>print(‘message to be printed’)Or
>>>print(variable_name)Or
>>>print(“message to be printed”, variable_name)Or
>>>print(‘message to be printed’, variable_name)

How to input a value for the user in Python


A value can be input from the user with the help of input() method the syntax is as follow :
variable_name = input(“Enter any number”)
input method return a string. It can be changed to other datatypes by using type.
age = int(input(“Enter your age”))
percentage= float(input(“Enter you percentage”))

Control statements

Control structureis used to control the sequence of execution of statements written in a program.
Without using Control structure sequence of executionof statements in a program is line line by
and every statement is executed once .

In python we can divide the control structureinto two parts


1. conditional control structure
2. looping/iterative control structure

Control Flow in Python


There comes situations in real life when we need to make some decisions and based on these
decisions, we decide what should we do next. Similar situations arise in programming also
where we need to make some decisions and based on these decisions we will execute the next
block of code. Decision-making statements in programming languages decide the direction of
the flow of program execution.
In Python, if-else elif statement is used for decision making.
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
Here, the condition after evaluation will be either true or false. if the statement accepts boolean
values – if the value is true then it will execute the block of statements below it otherwise not.
We can use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if statement will
be identified as shown in the below example:
if condition:
statement1
statement2

# Here if the condition is true, if block


# will consider only statement1 to be inside
# its block.
Flowchart of Python if statement

Example: Python if Statement

# python program to illustrate If statement

i = 10

if (i > 15):
print("10 is less than 15")

print("I am Not in if")

Output:
I am Not in if
As the condition present in the if statement is false. So, the block below the if statement is
executed.
if-else
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
FlowChart of Python if-else statement

Example 1: Python if-else statement

• Python3

# python program to illustrate If else statement

#!/usr/bin/python
i = 20

if (i < 15):

print("i is smaller than 15")

print("i'm in if Block")

else:

print("i is greater than 15")

print("i'm in else Block")

print("i'm not in if and not in else Block")

Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the if
statement is false after calling the statement which is not in block(without spaces).

Example 2: Python if else in list comprehension

# Explicit function

def digitSum(n):

dsum = 0

for ele in str(n):

dsum += int(ele)

return dsum

# Initializing list

List = [367, 111, 562, 945, 6726, 873]


# Using the function on odd elements of the list

newList = [digitSum(i) for i in List if i & 1]

# Displaying new list

print(newList)

Output
[16, 3, 18, 18]
nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements mean
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
Flowchart of Python Nested if Statement

Example: Python Nested if

# python program to illustrate nested If statement


#!/usr/bin/python

i = 10

if (i == 10):

# First if statement

if (i < 15):

print("i is smaller than 15")

# Nested - if statement

# Will only be executed if statement above

# it is true

if (i < 12):

print("i is smaller than 12 too")

else:

print("i is greater than 15")

Output:

i is smaller than 15
i is smaller than 12 too
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
FlowChart of Python if else elif statements

Example: Python if else elif statements

# Python program to illustrate if-elif-else ladder

#!/usr/bin/python

i = 20

if (i == 10):

print("i is 10")

elif (i == 15):

print("i is 15")

elif (i == 20):

print("i is 20")

else:

print("i is not present")

Output:
i is 20

Python For Loops


Python For loop is used for sequential traversal i.e. it is used for iterating over an iterable like
String, Tuple, List, Set or Dictionary.
In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for” loop which is similar
to each loop in other languages. Let us learn how to use for in loop for sequential traversals
Note: In Python, for loops only implements the collection-based iteration.
For Loops Syntax
for var in iterable:
# statements
Flowchart of for loop

Here the iterable is a collection of objects like lists, tuples. The indented statements inside the for
loops are executed once for each item in an iterable. The variable var takes the value of the next
item of the iterable each time through the loop.
Examples of For Loops in Python

Example 1: Using For Loops in Python List

# Python program to illustrate

# Iterating over a list

l = ["geeks", "for", "geeks"]


for i in l:

print(i)

Output:
Geeks
for
geeks

Example 2: Using For Loops in Python Dictionary

# Iterating over dictionary

print("Dictionary Iteration")

d = dict()

d['xyz'] = 123

d['abc'] = 345

for i in d:

print("% s % d" % (i, d[i]))

Output:
Dictionary Iteration
xyz 123
abc 345

Example 3: Using For Loops in Python String

# Iterating over a String

print("String Iteration")
s = "Geeks"

for i in s:

print(i)

Output:
String Iteration
G
e
e
k
s
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Python supports the
following control statements.

Continue Statement in Python

Python continue Statement returns the control to the beginning of the loop.
Example: Python for Loop with Continue Statement

# Prints all letters except 'e' and 's'

for letter in 'geeksforgeeks':

if letter == 'e' or letter == 's':

continue

print('Current Letter :', letter)

Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Break Statement in Python
Python break statement brings control out of the loop.
Example: Python For Loop with Break Statement

for letter in 'geeksforgeeks':

# break the loop as soon it sees 'e'

# or 's'

if letter == 'e' or letter == 's':

break

print('Current Letter :', letter)

Output:
Current Letter : e
Pass Statement in Python
The pass statement to write empty loops. Pass is also used for empty control statements, functions,
and classes.
Example: Python For Loop with Pass Statement

• Python3

# An empty loop

for letter in 'geeksforgeeks':

pass

print('Last Letter :', letter)

Output:
Last Letter : s
range() function in Python
Python range() is a built-in function that is used when a user needs to perform an action a specific
number of times. range() in Python(3.x) is just a renamed version of a function called xrange() in
Python(2.x).
The range() function is used to generate a sequence of numbers. Depending on how many
arguments the user is passing to the function, user can decide where that series of numbers will
begin and end as well as how big the difference will be between one number and the next.range()
takes mainly three arguments.
• start: integer starting from which the sequence of integers is to be returned
• stop: integer before which the sequence of integers is to be returned.
The range of integers end at stop – 1.
• step: integer value which determines the increment between each integer in the sequence

Example: Python for loop with range function

• Python3

# Python Program to

# show range() basics

# printing a number

for i in range(10):

print(i, end=" ")

# performing sum of first 10 numbers

sum = 0

for i in range(1, 10):

sum = sum + i

print("\nSum of first 10 numbers :", sum)

Output:
0123456789
Sum of first 10 numbers : 45
For loop in Python with else
In most programming languages (C/C++, Java, etc), the use of else statements has been restricted
with the if conditional statements. But Python also allows us to use the else condition with for
loops.
Note: The else block just after for/while is executed only when the loop is NOT terminated by a
break statement
• Python3

# Python program to demonstrate

# for-else loop

for i in range(1, 4):

print(i)

else: # Executed because no break in for

print("No Break\n")

Output:
1
2
3
No Break

Python While Loop


Python While Loop is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop in the
program is executed.
Syntax:
while expression:
statement(s)
Flowchart of While Loop :

While loop falls under the category of indefinite iteration. Indefinite iteration means that the
number of times the loop is executed isn’t specified explicitly in advance.
Statements represent all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses indentation
as its method of grouping statements. When a while loop is executed, expr is first evaluated in a
Boolean context and if it is true, the loop body is executed. Then the expr is checked again, if it is
still true then the body is executed again and this continues until the expression becomes false.
Example 1: Python While Loop

• Python3

# Python program to illustrate

# while loop

count = 0

while (count < 3):

count = count + 1

print("Hello Geek")

Output

Hello Geek
Hello Geek
Hello Geek
In the above example, the condition for while will be True as long as the counter variable
(count) is less than 3.
Example 2: Python while loop with list

• Python3

# checks if list still

# contains any element

a = [1, 2, 3, 4]

while a:

print(a.pop())

Output

4
3
2
1
In the above example, we have run a while loop over a list that will run until there is an element
present in the list.
Example 3: Single statement while block
Just like the if block, if the while block consists of a single statement we can declare the entire
loop in a single line. If there are multiple statements in the block that makes up the loop body,
they can be separated by semicolons (;).

• Python3

# Python program to illustrate

# Single statement while block

count = 0

while (count < 5): count += 1; print("Hello Geek")

Output:
Hello Geek
Hello Geek
Hello Geek
Hello Geek
Hello Geek
Example 4: Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Python supports the
following control statements.
Continue Statement
Python Continue Statement returns the control to the beginning of the loop.
Example: Python while loop with continue statement

• Python3

# Prints all letters except 'e' and 's'

i=0

a = 'geeksforgeeks'

while i < len(a):

if a[i] == 'e' or a[i] == 's':

i += 1

continue

print('Current Letter :', a[i])

i += 1

Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k

Formatting output using the String method :


This output is formatted by using string slicing and concatenation operations. The string type
has some methods that help in formatting output in a fancier way. Some methods which help
in formatting an output are str.ljust(), str.rjust(), and str.centre()

• Python3

# Python program to

# format a output using

# string() method

cstr = "I love geeksforgeeks"

# Printing the center aligned

# string with fillchr

print ("Center aligned string with fillchr: ")

print (cstr.center(40, '#'))

# Printing the left aligned

# string with "-" padding

print ("The left aligned string is : ")


print (cstr.ljust(40, '-'))

# Printing the right aligned string

# with "-" padding

print ("The right aligned string is : ")

print (cstr.rjust(40, '-'))

Output:
Center aligned string with fillchr:
##########I love geeksforgeeks##########

The left aligned string is :


I love geeksforgeeks--------------------

The right aligned string is :


--------------------I love geeksforgeeks

Errors and Exceptions in Python


Errors are the problems in a program due to which the program will stop the execution. On the
other hand, exceptions are raised when some internal events occur which changes the normal
flow of the program.
Two types of Error occurs in python.

1. Syntax errors
2. Logical errors (Exceptions)

Syntax errors
When the proper syntax of the language is not followed then a syntax error is thrown.
Example

• Python3
# initialize the amount variable

amount = 10000

# check that You are eligible to

# purchase Dsa Self Paced or not

if(amount>2999)

print("You are eligible to purchase Dsa Self Paced")

Output:

It returns a syntax error message because after the if statement a colon: is missing. We can fix
this by writing the correct syntax.

logical errors(Exception)
When in the runtime an error that occurs after passing the syntax test is called exception or
logical type. For example, when we divide any number by zero then the ZeroDivisionError
exception is raised, or when we import a module that does not exist then ImportError is raised.
Example 1:

• Python3

# initialize the amount variable

marks = 10000
# perform division with 0

a = marks / 0

print(a)

Output:

In the above example the ZeroDivisionError as we are trying to divide a number by 0.


Example 2: When indentation is not correct.

• Python3

if(a<3):

print("gfg")

Output:

Some of the common built-in exceptions are other than above mention exceptions are:

Exception Description

IndexError When the wrong index of a list is retrieved.


Exception Description

AssertionError It occurs when the assert statement fails

AttributeError It occurs when an attribute assignment is failed.

ImportError It occurs when an imported module is not found.

KeyError It occurs when the key of the dictionary is not found.

NameError It occurs when the variable is not defined.

MemoryError It occurs when a program runs out of memory.

TypeError It occurs when a function and operation are applied in an incorrect type.

Error Handling
When an error and an exception are raised then we handle that with the help of the Handling
method.

• Handling Exceptions with Try/Except/Finally


We can handle errors by the Try/Except/Finally method. we write unsafe code in the try,
fall back code in except and final code in finally block.
Example

• Python3

# put unsafe operation in try block

try:

print("code start")

# unsafe operation perform


print(1 / 0)

# if error occur the it goes in except block

except:

print("an error occurs")

# final code in finally block

finally:

print("GeeksForGeeks")

• Output:

code start
an error occurs
GeeksForGeeks

• Raising exceptions for a predefined condition
When we want to code for the limitation of certain conditions then we can raise an
exception.
Example

• Python3

# try for unsafe code

try:

amount = 1999
if amount < 2999:

# raise the ValueError

raise ValueError("please add money in your account")

else:

print("You are eligible to purchase DSA Self Paced course")

# if false then raise the value error

except ValueError as e:

print(e)

• Output:

please add money in your accoun

Computer Programs

Formula Based Simple Programs

1. Write a program to find Simple Interest

p=int(input(“Enter the principle amount”)) r=int(input(“Enter the rate of interest”))


t=int(input(“Enter the time”)) si=(p*r*t)/100
print(“Simple Interest = ”,si)

2. Write a program to find area of a circle

r= float(input(“Enter the radius of circle”))area_of_circle= 22/7*r*r


print(“Area of circle = ”, area_of_circle)

3. Write a program to convert temperature from Celsius to Fahrenheit

C= float(input(“Enter the temperature in celsius”))


F=(C*9/5)+32
print(“The temperature in Fahrenheit is = ”, F)

Condition Based Simple Programs


1. Write a program to check whether a person is eligible for voting or note by checking his
age.

age=int(input(“Enter your age : ”))if age>=18 :


print(“You can vote”)
else :
print(“You cannot vote”)

2. Write a program to find whether a year is leap year or not .


year1= int(input(“Enter any year”))if year1%400 ==0 :
print(“It is a leap year”)
elif year1%4==0 and year1%100 !=0 :print(“It is a leap year”)
else :
print(“It is not a leap year”)

3. Write a program to find the grade of a student based upon his percentage based upon
following conditions.
Percentage >= 80 A+ grade Percentage>= 60 A grade Percentage >= 50 B grade Percentage
>=40 C grade Percentage>=35 D grade Percentage>=0 F grade
Other : invalid percentage entered

percentage= float(input(“Enter your percentage : ”))if percentage>=80 and percentage<=100 :


print(“Your grade is A+”)elif percentage>=60:
print(“Your grade is A”)elif percentage>=50:
print(“Your grade is B”)elif percentage>=40:
print(“Your grade is C”)elif percentage>=35:
print(“Your grade is D”)elif percentage>=0:
print(“Your grade is F”)
else :
print(“You have entered a wrong percentage”)

Q4. Write a program to find the largest number among 3 numbers.


num1=int(input(“Enter 1st number”))num2=int(input(“Enter 2nd number”))num3=int(input(“Enter
3rd number”))
if num1>num2 :
if num1>num3:
print (num1 , “is greatest”)
else
print(num3, “is greatest”)
else :
if num2>num3:
print (num2 , “is greatest”)
else
print(num3, “is greatest”)

Loop Based Simple Programs


Q1. Write a program to print following series : 1,3,5………99
i=1
while i<=100:
print( i )i=i+2

Q2. Write a program to find the sum from 1 to 100

num=1 sum1=0
while num<=100 :
sum1=sum1+numnum=num+1
print(“Sum from 1 to 100 = ” sum1)

Q3. Write a program to find the product from 1 to 100

num=1 product=1
while num<=100 :
product=product*numnum=num+1
print(“ Product from 1 to 100 = ” product)

Q4. Write a program to find the factorial of a number num=int(input(“Enter the number
whose factorial you want to find”))fact=1
i=num while i>=1:
fact=fact*ii=i-1
print(“Factorial of ”, num ,” = ”, fact)

Q5. Write a program to print Fibonacci Series


a=0b=1
num=int(input(“Enter the number of elements of Fibonacci series you want to print”))i=1
while i<=num :
if i==1:
print (a)
elif i==2:
print(b)
else
c=a+b print (c)a=b b=c
Q6. Write a program to check whether a number is prime or not num=int(input(“Enter the
number you want to check for prime number”))factor=0
i=1
while i<=num :
if num%i==0:
factor=factor+1
i=i+1if factor==2:
print(“This number is a prime number”)
else :
print(“This number is not a prime number”)

Q7. Write a program to find the product of given 10 numbers


numbers=[23,2,34,45,21,4,5,6,12,9]
result=1
for s in numbers:
result=result*number
print(“The product of given 10 numbers = “,result)

Q8. Write a program to check whether a number is palindrome (same as its reverse) or not
num=int(input("Enter a number "))num1=0
num2=num while num2>0:
num1=num1*10 num1=num1+(num2%10) num2=num2//10
if num1==num:
print(num ," is a palindrome")
else:
print(num, " is not a palindrome")

Escape characters are characters that are generally used to perform certain tasks and their
usage in code directs the compiler to take a suitable action mapped to that character.
Example :
'\n' --> Leaves a line
'\t' --> Leaves a space

# Python code to demonstrate escape character


# string

ch = "I\nLove\tGeeksforgeeks"

print ("The string after resolving escape character is : ")


print (ch)
Output :
The string after resolving escape character is :
I
Love Geeksforgeeks
But in certain cases it is desired not to resolve escapes, i.e the entire unresolved string has
to be printed. These are achieved by following ways.
Using repr()
This function returns a string in its printable format, i.e doesn’t resolve the escape sequences.

# Python code to demonstrate printing


# escape characters from repr()

# initializing target string


ch = "I\nLove\tGeeksforgeeks"

print ("The string without repr() is : ")


print (ch)

print ("\r")

print ("The string after using repr() is : ")

print (repr(ch))

Output :
The string without repr() is :
I
Love Geeksforgeeks

The string after using repr() is :


'I\nLove\tGeeksforgeeks'
Using “r/R”
Adding “r” or “R” to the target string triggers a repr() to the string internally and stops from
the resolution of escape characters.

# Python code to demonstrate printing


# escape characters from "r" or "R"

# initializing target string


ch = "I\nLove\tGeeksforgeeks"

print ("The string without r / R is : ")


print (ch)

print ("\r")

# using "r" to prevent resolution


ch1 = r"I\nLove\tGeeksforgeeks"

print ("The string after using r is : ")


print (ch1)

print ("\r")

# using "R" to prevent resolution


ch2 = R"I\nLove\tGeeksforgeeks"
print ("The string after using R is : ")
print (ch2)

Output :
The string without r/R is :
I
Love Geeksforgeeks

The string after using r is :


I\nLove\tGeeksforgeeks

The string after using R is :


I\nLove\tGeeksforgeeks

You might also like