unit1 python (1)
unit1 python (1)
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.
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
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:
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”)
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
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
1. Number
Number data type stores Numerical Values. These are of three different types:
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
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
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
Membership Operator
Assignment Operators
Assignment operators are used to assign a value to the variable.
Identity Operator
Operator Precedence :
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)
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 .
i = 10
if (i > 15):
print("10 is less than 15")
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
• Python3
#!/usr/bin/python
i = 20
if (i < 15):
print("i'm in if Block")
else:
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).
# Explicit function
def digitSum(n):
dsum = 0
dsum += int(ele)
return dsum
# Initializing 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
i = 10
if (i == 10):
# First if statement
if (i < 15):
# Nested - if statement
# it is true
if (i < 12):
else:
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
#!/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:
Output:
i is 20
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
print(i)
Output:
Geeks
for
geeks
print("Dictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
Output:
Dictionary Iteration
xyz 123
abc 345
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.
Python continue Statement returns the control to the beginning of the loop.
Example: Python for Loop with Continue Statement
continue
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
# or 's'
break
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
pass
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
• Python3
# Python Program to
# printing a number
for i in range(10):
sum = 0
sum = sum + i
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
# for-else loop
print(i)
print("No Break\n")
Output:
1
2
3
No Break
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
# while loop
count = 0
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
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
count = 0
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
i=0
a = 'geeksforgeeks'
i += 1
continue
i += 1
Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
• Python3
# Python program to
# string() method
Output:
Center aligned string with fillchr:
##########I love geeksforgeeks##########
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
if(amount>2999)
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
marks = 10000
# perform division with 0
a = marks / 0
print(a)
Output:
• Python3
if(a<3):
print("gfg")
Output:
Some of the common built-in exceptions are other than above mention exceptions are:
Exception Description
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.
• Python3
try:
print("code start")
except:
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:
amount = 1999
if amount < 2999:
else:
except ValueError as e:
print(e)
• Output:
Computer Programs
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
num=1 sum1=0
while num<=100 :
sum1=sum1+numnum=num+1
print(“Sum from 1 to 100 = ” sum1)
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)
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
ch = "I\nLove\tGeeksforgeeks"
print ("\r")
print (repr(ch))
Output :
The string without repr() is :
I
Love Geeksforgeeks
print ("\r")
print ("\r")
Output :
The string without r/R is :
I
Love Geeksforgeeks