[go: up one dir, main page]

0% found this document useful (0 votes)
246 views208 pages

Python PDF

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)
246 views208 pages

Python PDF

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/ 208

INT-102

Computer Organization

©LPU CSE101 C Programming


What is a Computer?
• Computer
– Device capable of performing computations and making
logical decisions (hardware)
– Computers process data under the control of sets of
instructions called computer programs (software)
• Hardware
– Various devices comprising a computer, such as central
processing unit (CPU), memory, motherboard and hard
disks as well as peripheral devices (keyboard, screen,
mouse)
• Software
– Programs that run on a computer

©LPU CSE101 C Programming


What is a Computer?

©LPU CSE101 C Programming


Operating System
• Operating systems
A collection of programs that manages
resources of a computer, such as
- processors
- memory
- input/output devices
– Perform basic tasks
– Manage transitions between jobs
– Increased throughput
• Multiprogramming
– Many jobs or tasks sharing a computer’s resources
– “Simultaneous” operation of many jobs.

©LPU CSE101 C Programming


Machine Languages, Assembly
Languages, and High Level Languages
The lowest-level programming
language Machine languages are
the only languages understood
by computers. While easily
understood by computers,
machine languages are almost
impossible for humans to use
because they consist entirely of
numbers(0 and 1). Programmers,
therefore, use either a high-level
programming language or
an assembly language.

©LPU CSE101 C Programming


Machine Languages, Assembly
Languages, and High Level Languages
An Assembly language contains
the same instructions as a
machine language, but the
instructions
and variables have names instead
of being just numbers.
Programs written in high-level
languages are translated into
assembly language or machine
language by a compiler.
Assembly language programs are
translated into machine language
by a program called an
©LPU CSE101 C Programming
assembler.
Machine Languages
Machine language
• Machine code or machine language is a set
of instructions executed directly by
a computer's central processing unit(CPU).
• Only language computer directly understands
• Consist of 0s and 1s
• Cumbersome for human.
• Slow, tedious and error prone

©LPU CSE101 C Programming


Machine Language Example

©LPU CSE101 C Programming


Assembly Languages
Assembly language
• English-like abbreviations representing elementary
computer operations
• Clearer to humans
• Program is in alphanumeric symbols
• Translator programs (assemblers).
• Convert to machine language (Example: LOAD,ADD)
• Usage of computer increases, but user had to use
many instructions to accomplish even a simple task

©LPU CSE101 C Programming


Assembly Language Example

©LPU CSE101 C Programming


High-level Languages
High-level languages
• Similar to everyday English, use common
mathematical notations
• Single statements accomplish substantial tasks
– Assembly language requires many instructions to
accomplish simple tasks
• Translator programs (compilers)
– Convert to machine language
• Interpreter programs
– Directly execute high-level language programs
©LPU CSE101 C Programming
High-level Languages
• Fortran
• C
• C++
• Java
• Python

©LPU CSE101 C Programming


Course Id :INT 102
Course parameters

• L- T- P : 0-0-4
• Marks Weightage:
– Attendance: 05
– Continuous Assessment (CA): 45
– End Term Examination (All Subjective): 50
Books

Text Books:
1. Programming and Problem Solving Using PYTHON by Ashok Namdev
Kamathane
2. INTRODUCTION TO PROGRAMMING USING PYTHON by Y. DANIEL
LIANG, PEARSON
Reference Book
1. INTRODUCTION TO COMPUTATION AND PROGRAMMING USING
PYTHON by JOHN V. GUTTAG, PHI Learning Pvt Ltd
Programming ..??
Algorithms v/s programming

Algorithm: how to systematically perform a task


Write down as a sequence of steps

Programming language : describes the steps


What is a step?
Daily routine
Let us look around our daily routine…
• Let us see where all we do programming everyday
• Simple things we do to start the day

This too has a set procedure. One follows particular


steps to accomplish the task.

So there is ONE program you know which is there in you…


Daily routine
• There is a set procedure Start

Pick Brush

• Each step is defined Rinse Brush

• The occurrence is ordered Apply Paste

Brush

• Jump is NOT permitted Rinse Mouth

• A step cannot be skipped Rinse Brush

Stop
Daily routine
• Let us explore more as the day goes by…

Going for a morning 0900 AM Class Going for a movie at 0900 AM

It is all about WHICH program is loaded WHEN


Daily routine
• The flow changes
Start

Go!!!

Where
Class To Movie
Go?

Stop Stop
So what does this mean?
• Take ANY activity of the day…
• It will have a set procedure
• It has to be done in a designate way
• If not done the specified way will yield wrong results
• Success in doing it depends on how closer one is to the
prescribed method

• This clearly shows that everything has a


Logic, logic and logic
What next?
• If there is logic in anything and everything
• There has to be ways to represent logic
• There has to be modes to modify and re-
represent logic
• There should be methodology to implement and
re-design logic
• And for all this…
What next?
• There has to be logic machine to
assimilate, understand, solve, store,
retrieve and represent logic

• There has to be a LANGUAGE to


communicate with the logic
machine
Which Programming Language ??
What is Python?

• Python is an open source, object-oriented, high-level powerful


programming language.
• Developed by Guido van Rossum in the early 1990s. Named after
Monty Python
• Python runs on many Unix variants, on the Mac, and on Windows
2000 and later.
Your Future ….!!!
Let’s Find Out ….!!

Write a Program using any language you


know to print “ HELLO WORLD “.
Python Is Easy to Use

• C++ Program :
#include <iostream>
int main()
{
cout << "Hello World" << endl;
return 0;
}
C Program

#include <stdio.h>
int main()
{
printf(“Hello, World!\n”);
}
Java Program :

public class Hello


{
public static void main(String argv[])
{
System.out.println(“Hello, World!”);
}
}
Python Program :

• print ( "Hello World")


SALIENT FEATURES

• Simple- Python is a simple language. Reading a good Python program


feels almost like reading English. It allows you to concentrate on the
solution to the problem rather than the syntax i.e. the language itself.

• Easy to Learn-Python is extremely easy to get started with. Python


has an extraordinarily simple syntax.
• Open source : Python is publicly available open source software, any
one can use source code that doesn't cost anything.
• Portable :
High level languages are portable, which means they are able to run
across all major hardware and software platforms with few or no
change in source code. Python is portable and can be used on Linux,
Windows, Macintosh, Solaris, FreeBSD, OS/2, Amiga, AROS, AS/400
and many more.
• Object-Oriented : Python is a full-featured object-oriented
programming language, with features such as classes, inheritance,
objects, and overloading.
• Python is Interactive :
Python has an interactive console where you get a Python prompt
(command line) and interact with the interpreter directly to write and
test your programs. This is useful for mathematical programming.
• Interpreted : Python programs are interpreted, takes source code as
input, and then compiles (to portable byte-code) each statement and
executes it immediately.
• Extendable : Python is often referred to as a “glue” language,
meaning that it is capable to work in mixed-language environment.
The Python interpreter is easily extended and can add a new built-in
function or modules written in C/C++/Java code.
• Libraries : Databases, web services, networking, numerical packages,
graphical user interfaces, 3D graphics, others.
• Supports :Support from online Python community
VERSIONS OF PYTHON
• Python 1.0 - January 1994
– Python 1.5 - December 31, 1997
– Python 1.6 - September 5, 2000
• Python 2.0 - October 16, 2000
– Python 2.1 - April 17, 2001
– Python 2.2 - December 21, 2001
– Python 2.3 - July 29, 2003
– Python 2.4 - November 30, 2004
– Python 2.5 - September 19, 2006
– Python 2.6 - October 1, 2008
– Python 2.7 - July 3, 2010
VERSIONS OF PYTHON

• Python 3.0 - December 3, 2008


– Python 3.1 - June 27, 2009
– Python 3.2 - February 20, 2011
– Python 3.3 - September 29, 2012
– Python 3.4 - March 16, 2014
– Python 3.5 - September 13, 2015
– Python 3.6- December 23,2016
– Python 3.7- June 27,2018
DOWNLOADING PYTHON
VERSION (3.2.1)
Competitive Programming is a sport. Its like
Olympics of the programming.
• Makes you a desirable candidate to major companies:Participation
in the ACM International Collegiate Programming Contest (ACM
ICPC) is a great opportunity to be seen by Apple, Facebook, Google,
IBM and many other authorities in the IT sphere.
• Makes you faster and more focused:In the competition, you must
solve problems in stressful situations and do it up against a deadline
or you will lose. Taking part in competitive programming teaches you
how to be more focused on the task and not only complete it quickly,
but accurately. These skills are highly beneficial for any job, not just in
coding.
Companies

And many more……………


Challenges

• ACM – ICPC
• Google Code Jam
• Topcoder Open
• Google foo bar challenge
• Facebook Hacker cup
UNIT 1

• Introduction : python programming language, introduction to


program and debugging, formal and natural language
• Variables, Expression, and Statements : Values, variables, Variables
name and keywords, statements, operators and operand, order of
operations, operations on string, composition and comments
• Conditionals and Iteration : modulus operator, boolean expressions,
logic operators, conditional, alternative execution, nested
conditionals and return statements, while statements, encapsulation
and generalization
UNIT 2

• Functions and recursion : function calls, type conversion and


coercion, math functions, adding new function, parameters and
argument, recursion and its use
• String and Regular Expressions : string a compound data type, length,
string traversal, string slices, comparision, find function, looping and
counting
UNIT 3

Lists : list values, length, membership, operations, slices, deletion,


accessing elements, list and for loops, list parameters and nested list
Tuples and Dictionaries : mutability and tuples, tuple assignment, tuple
as return values, random numbers and list of random numbers,
counting and many buckets, dictionaries operations and methods,
sparse matrices, aliasing and coping
Files and exceptions : text files, writing variables, directories, pickling,
exceptions, glossary
UNIT 4

• Creating and Manipulating Numerical Data: Arrays, Creating Arrays,


Basic Data Types, Indexing and Slicing, Copies and Views, Numerical
Operations on Array
UNIT 5

Classes and objects : creating classes, creating instance objects,


accessing attributes, overview of OOP terminology

Object oriented programming terminology : Class Inheritance,


Overriding Methods, Data Hiding, Function Overloading
UNIT 6

Divide and Conquer technique : introduction to divide and conquer


technique, Binary search, Quick Sort, Merge Sort

Graph optimization technique : introduction to graph optimization


technique, Depth first Search, Breadth first Search, Problem solving
using graph optimization techniques
INT102
Topics to be Covered
• History of Python

• Introduction to Python programming language

• Introduction to programs and debugging

• Formal and natural language


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 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
History of Python
VERSIONS OF PYTHON
• Python 1.0 - January 1994
• Python 1.5 - December 31, 1997
• Python 1.6 - September 5, 2000
• Python 2.0 - October 16, 2000
• Python 2.1 - April 17, 2001
• Python 2.2 - December 21, 2001
• Python 2.3 - July 29, 2003
• Python 2.4 - November 30, 2004
• Python 2.5 - September 19, 2006
• Python 2.6 - October 1, 2008
• Python 2.7 - July 3, 2010
History of Python
• Python 3.0 - December 3, 2008
• Python 3.1 - June 27, 2009
• Python 3.2 - February 20, 2011
• Python 3.3 - September 29, 2012
• Python 3.4 - March 16, 2014
• Python 3.5 - September 13, 2015
• Python 3.6- December 23,2016
• Python 3.7- June 27,2018
Introduction of Python programming language
• Python is a powerful high-level, object-oriented programming
language created by Guido van Rossum.
• It has simple easy-to-use syntax, making it the perfect language for
someone trying to learn computer programming for the first time.
• Python is a general-purpose language. It has wide range of
applications from Web development to scientific and mathematical
computing to desktop graphical user Interfaces .
• The syntax of the language is clean and length of the code is relatively
short. It's fun to work in Python because it allows you to think about
the problem rather than focusing on the syntax.
Introduction of Python programming language
Basic Features of Python
• 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.

• Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.

• Easy-to-maintain − Python's source code is fairly easy-to-maintain.

• A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
Introduction of Python programming language
• Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
• Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
• Databases − Python provides interfaces to all major commercial databases.
• GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
• Scalable − Python provides a better structure and support for large programs
Introduction to programs and debugging
•Sequence of instructions that specify how to perform a computation.
•Basic instructions in almost every program:
•Input: Get data from keyboard, or file or some other device.
•Output: Display data on the screen or send data to a file or other device.
•Math: Perform basic mathematical operations like addition and
multiplication.
•Conditional Execution: Check for certain conditions and execute the
appropriate sequence of statements.
•Repetition: Perform some action repeatedly , usually with some variation
Introduction to programs and debugging
What is Debugging?
• Debugging is the routine process of locating and removing computer program
bugs, errors or abnormalities, which is methodically handled by software
programmers via debugging tools. Debugging checks, detects and corrects errors
or bugs to allow proper program operation according to set specifications

• It is a systematic process of spotting and fixing the number of bugs, or defects, in


a piece of software so that the software is behaving as expected.
Introduction to programs and debugging
Types of Errors to be Debug
Errors also known as bugs in the world of programming may occur unwillingly
which may prevent the program to compile and run correctly as per the
expectation of the programmer. Basically there are three types of errors in
programming:
1 Runtime Errors
2 Compile Errors
3 Logical Errors
Runtime Errors- runtime errors are those errors that occur during the execution of
a program and generally occur due to some illegal operation performed in the
program.

e.g. print(radius)

In this example, we forget to define the radius variable. Python knows what you
want it to do, but since no radius has been defined, an error occurs.

Other Examples of some illegal operations that may produce runtime errors are:
Dividing a number by zero
Trying to open a file which is not created
Lack of free memory space
Compile Errors- Compile errors are those errors that occur at the time of
compilation of the program. Compile errors may be further classified as Syntax
Error, Semantic Errors.
Syntax errors:
• As we do more and more programming, we will naturally encounter a lot of errors
(or bugs).
• Causing, understanding, and fixing errors is an important part of programming.
• Python will do its best to run anything that you tell it to run, but if it can't
understand what you're asking, then it won't run the program.
• All the same, Python will try to tell you a little bit of information about what went
wrong, in order to help you try to fix it.
Syntax Errors- When the rules of the c programming language are not followed,
the compiler will show syntax errors.
For example, consider the statement,

print “Gee golly”

In this example, we forget to use the parenthesis that are required by print(...).
Python does not understand what you are trying to do. It will give error.
• A syntax error happens when Python can't understand what you are saying.
A run-time error happens when Python understands what you are saying, but
runs into trouble when following your instructions.

• In English, a syntax error would be like the sentence


Please cat dog monkey

• The grammar of this sentence does not make sense. From the perspective of
English grammar, it is missing a verb (action).
• In English, a run-time error would be like the sentence

Please eat the piano.

• The sentence makes sense from a grammatical perspective — there is a verb and
noun in the right place — so you know what you are being asked to do. But, you
will encounter problems once you start trying to eat the piano.
• This is called a run-time error because it occurs after the program starts running.
Semantic Errors (Logical) -Semantic errors are reported by the compiler when the
statements written in the c program are not meaningful to the compiler.

For example, consider the statement, b+c=a; In the above statement we are trying
to assign value of a in the value obtained by summation of b and c which has no
meaning in programming. The correct statement will be a=b+c;
Logical Errors-Logical errors are the errors in the output of the program. The
presence of logical errors leads to undesired or incorrect output and are caused due
to error in the logic applied in the program to produce the desired output.
• Also, logical errors could not be detected by the compiler, and thus, programmers
has to check the entire coding of a program line by line
• Your program might run without crashing (no syntax or run-time errors), but still
do the wrong thing. For example, perhaps you want a program to calculate
the average of two numbers: the average of x and y is defined as
Why doesn't this program work?
but the program prints 5.0 instead! The error this time has to do with the
"order of operations" in arithmetic. When you write x + y / 2, this has
the same mathematical meaning as x + (y/2) =3 + (4/2) = 3 + 2 =5 .

To fix the problem, the third line of our program should be written
as average = (x + y) / 2, which makes clear to Python that we really
want the value , where we add first and divide afterwards.

Logic errors can be difficult to spot, especially in a longer program, but


as we get better at writing code you will also get better at avoiding logic
errors.
Task 1:
Fix the syntax error in the following program, so that it prints out the sum of all the
numbers from 1 to 10. You can change at most one character.

print(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 +)
Task 2: Hello Joe
Fix the run-time error in the following program, so that it prints out Hello on the
first line and Joe on the second line. You can change at most two characters

print("Hello")
username = Joe
print(username)
Formal and natural language
• Natural Languages are the languages that people speak, such as English,
Spanish, French. They were not designed by people; they evolved naturally.

• Formal Languages are languages that are designed by people for specific
applications.

• Programming languages are formal languages that have been designed to


express computations.

• Formal languages tend to have strict rules about syntax. For example, 3+3=6
is a syntactically correct mathematical statement, but 3=+6$ is not

• Parsing is a process to figure out what the structure of the sentence is.
Difference between Natural and Formal Languages
Ambiguity:
Natural languages are full of ambiguity.
Formal languages are designed to be nearly or completely unambiguous.
Redundancy: Natural languages are more redundant as compared to formal
languages.
Literalness: Natural languages are full of idiom and metaphor. Formal languages
mean exactly what they say.
Variables, Keywords, Expressions,
Statements
Topics to be Covered

• Value and Variables


• Keywords
• Expressions
• Statements
• Operators and order of operations
Value and Variable
• Value is a one of the fundamental thing, that a program manipulates.
• Variable is a name that refers to a value that maybe changed in the
program.
• The assignment statement creates new variables and gives them
values:
• >>> message = “Hi, How are you?"
• >>> m = 15
• >>> pi = 3.1415
Identifiers
• Identifiers are the names that identify the elements such as variables and functions
in a program. All identifiers must obey some rules
1. An identifier is a sequence of characters that consists of letters, digits and
underscores(_).
2. An identifier must start with a letter or an underscore. It cannot start with a
digit.
3. An identifier cannot be a keyword. Keywords, also called reserved words, have
special meanings in Python.
E.g. import is a keyword, which tells the python interpreter to import a module
to the program.
Rules for naming an Identifier
1. An identifier name is any combination of alphabets, digits or
underscores.

2. The first character in the identifier name must be an alphabet or


underscore. It cannot start with a digit.

3. No blanks or special symbol other than an underscore can be used in an


identifier name.

4. Keywords are not allowed to be used as identifiers.


Some Identifiers
Mechanical; both are different
mechanical;
FORMULA1;
engine_1;

Wrong identifiers name


1_engine;
break;
@car-roof;
Variable
• Variables are the names that reference values stored in memory.
• Variable names must be meaningful.
• It contains both numbers and letters, but they have to begin with a letter.
• Case sensitive.
• The underscore (_) character can appear in a name.
• Eg.
– >>>76trombones = "big parade“ >>> more$ = 1000000
– SyntaxError: invalid syntax SyntaxError: invalid syntax
– >>> class = "Computer Programming 102“
>>> radius=10.5
– SyntaxError: invalid syntax Valid variable
Keywords
• Keywords, also called reserved words, have special meanings in Python

• Keywords define the language’s rules and structure and they can’t be
used as variable names.

• Python3.7 has 35 keywords.


List of Python Keywords
and def False if not return

await nonlocal raise as

assert True finally import or try

break elif for in pass while

class else from is async yield

continue except global lambda raise None


Keywords
Python in its language defines an inbuilt module “keyword” which
handles certain operations related to keywords. A function
“iskeyword()” checks if a string is keyword or not. Returns true if a
string is keyword, else returns false.

>>> import keyword


>>> keyword.iskeyword("true")
False
print(keyword.kwlist) to know list of keywords
Statements
• A statement is an instruction that the Python interpreter can execute.
• When you type a statement on the command line, Python executes it and displays the
result, if there is one.
• A script usually contains a sequence of statements. If there is more than one
statement, the results appear one at a time as the statements execute.
• The statement for assigning a value to a variable is called an assignment statement.
• In Python, the equal sign(=) is used as the assignment operator.
• Syntax: variable=expression
Evaluating Expressions
• An expression is a combination of values, variables, and operators.
• If you type an expression on the command line, the interpreter evaluates it and
displays the result:
– >>> 1 + 1
– 2
• A value all by itself is considered an expression, and so is a variable.
>>> 17 >>> x=2
17 >>>x
2
Simultaneous Assignments
Python also supports simultaneous assignments like this:
var1,var2…………..,varn=exp1,exp2…………….,expn
>>> a,b,c=4,5,6
>>> a
4
>>> b
5
>>> c
6
Example code
Write a python code to swap two numbers.
>>>X=1
>>>Y=3
>>>Temp=X
>>>X=Y
>>>Y=Temp X=1 before Y=3

Can be written as: after


X=3 Y=1
>>>X=1
>>>Y=3
>>>X,Y=Y,X
Example
What is the maximum possible value of an integer in Python ?
In Python, value of an integer is not restricted by the number of bits
and can expand to the limit of the available memory.
>>> x=10000000000000000000000000000
>>> x
10000000000000000000000000000
Python2 vs. Python3
As a side note, in Python 3, there is only one type “int” for all type of
integers. In Python 2.7. there are two separate types “int” (which is 32
bit) and “long int” that is same as “int” of Python 3.x, i.e., can store
arbitrarily large numbers.
• x = 10
• print(type(x))
• x = 10000000000000000000000000000000000000000000
• print(type(x))
Python2 vs. Python3

Output in Python 2.7 :


<type 'int'>
<type 'long'>
Output in Python 3 :
<type 'int'>
<type 'int'>
Operators and Operands
• Operators are special symbols that represent computations like
addition and multiplication.
• The values the operator uses are called operands
• When both of the operands are integers, the result must also be an
integer, and by convention, integer division always rounds down.
• +, -, *, /, %, **,//
• ** is used for exponential.
• / is also used for float division
• // is used to integer division
Example
>>>10%3
1
>>>2**3
8
>>> 2/3
0.6666666666666666
>>> 2.0/3
0.6666666666666666
>>> 2.0/3.0
0.6666666666666666
Example
>>> 10/3
3.33333
>>> 10//3
3
>>> 2//3
0
>>> 2.0//3
0.0
>>> 2.0//10.0
0.0
Order of Operations
• When more than one operator appears in an expression, the order of evaluation depends on the rules
of precedence.
– Parentheses have the highest precedence and can be used to force an expression to evaluate in the
order you want.

– Exponentiation has the next highest precedence.

– Multiplication ,Float Division, Integer Division and remainder have the same precedence, which
is higher than Addition and Subtraction, which also have the same precedence.

– Operators with the same precedence are evaluated from left to right.
Task 1: determine the final values of all variables at the end of the program.

first = 2
second = 3
third = first * second
second = third - first
first = first + second + third
third = second * first
Task 2: What is the value of x after these commands execute?

x = 10
x=x+x
x=x-5
Operations on Strings
• the + operator represents concatenation.
• For Example:
– fruit = "banana"
– bakedGood = " nut bread“
– print (fruit + bakedGood)
• The * operator also works on strings; it performs repetition.
• For eg:
– "Fun"*3 is "FunFunFun"
Comments
• It is a good idea to add notes to your programs to explain in natural
language what the program is doing. These notes are called comments.
• they are marked with the # symbol:
•For eg:
# compute the speed when distance and time is given
speed= distance/time
Questions ??
Solved Exercise

Q1. There are 5280 feet in a mile. Write a Python statement that
calculates and prints the number of feet in 13 miles

Python Code:
>>> feetInMiles=5280 #storing value in variable
>>> feetIn13Miles=feetInMiles*13 #calculating feet and storing in variable
>>> feetIn13Miles #type variable to check the result
68640 #result
Solved Exercise
Q2. Write a Python statement that calculates and prints the number of
seconds in 7 hours, 21 minutes and 37 seconds.
>>> hrs=7 #storing value in variable1
>>> mins=21 #storing value in variable2
>>> sec=37 #storing value in variable3
>>> TotalSec=(hrs*60*60)+(mins*60)+sec #calculation statement
>>> TotalSec # type variable to check the result
26497 #result
Practice Programs
Q3. Write a Python statement that calculates and prints the area in
inches of a rectangle with length and breadth as 4 and 7 inches.
Q4. The circumference of a circle is 2πr where r is the radius of the
circle. Write a Python statement that calculates and prints the
circumference in inches of a circle whose radius is 8 inches. Assume that
the constant π=3.14.
Q5. Write a single Python statement that combines the three strings
"My name is", "Joe" and "Warren” into one larger string "My name is
Joe Warren." and prints the result.
Q6. Find the area of triangle using python code.
INT102
STRINGS
COMPOUND DATA TYPE
• Strings are qualitatively different from Integer and Float type.
• Characters which collectively form a String is a Compound Data Type.
For Eg.
fruit = “apple”
letter = fruit[1]
print (letter)
Output : p // (index value starts from 0 as in C & C++)
LENGTH OF STRINGS
• The inbuilt function to find the length of a string is ‘len()’.
For Eg.
fruit = “mango”
len(fruit)
Output : 5
• To get the last letter we might try
length = len(fruit)
last = fruit[length] #ERROR
( because there is no character at 5th place)
LENGTH OF STRINGS (to be continued…..)

• Right Method to do this is :


length = len(fruit)
last = fruit[length-1]
• Another way to get the elements from last is :
fruit[-1] # yields the last letter
fruit[-2] # yields the second last letter
TRAVERSAL USING WHILE LOOP
• Processing one character at one time.
For Eg.
index = 0
while index < len(fruit):
letter = fruit[index]
print (letter)
index = index + 1
(Take care of the indentation)
TRAVERSAL USING FOR LOOP
• For loop provides us a privilege to access the characters without using
index.
For Eg.
fruit=“apple”
for char in fruit:
print (char)
(Each time through the loop a character is assigned to the
variable char)
TRAVERSAL USING FOR LOOP (to be continued…..)

ABECEDARIAN SERIES – Print using for loop


• A series or list in which the elements appear in alphabetical order.
For Eg. In Robert McCloskey’s book Make way for Duckings the
names of the ducklings were Jack, Kack, Lack, Mack, Nack,
Ouack, Pack, Quack
• To print them in order the code is :
prefixes = “JKLMNOPQ”
suffix = “ack”
STRING SLICES
• A segment of a string is called a slice, i.e. a character.
• The syntax to select a slice from a string is a[n:m], where a contains
strings, n is the starting index and m is the end index.
• Includes the first index and excluding the last index.
Eg:
s= “Peter, Paul, and Mary”
print s =[0:5] # Peter
print s =[7:11] # Paul
print s =[17:21] # Mary
STRING SLICES (to be continued…..)

fruit = “banana”
fruit[ : 3] #ban
fruit[ 3 :] #ana
fruit[:] ?
s=“Hello, world”
STRING COMPARISON
• Equality Comparison
if word ==“banana!”
• Other Comparisons
if word < “banana”:
print ”Your word,”+ word + “,comes before banana.”
elif word > “banana”:
print ”Your word,”+ word + “,comes after banana.”
STRING COMPARISON (to be continued…..)

• > and < comparison operations are useful for putting words in
alphabetical order:
• Uppercase letters ,numerals and special symbol comes before
Lowercase letters in Python.

• Need to maintain a standard format of the strings.


STRINGS ARE IMMUTABLE
• An existing string cannot be modified.
For Eg :
greeting = "Hello, world!“
greeting[0+ = ’J’ # ERROR!
print greeting
Output : Hello, world
STRINGS ARE IMMUTABLE (to be continued….)

• The Solution of the problem is


greeting = "Hello, world!“
newGreeting = ’J’ + greeting*1:+
print newGreeting
Output : Jello, World

• The original string remains intact.


Creation of Find Function in Strings
• Find function is used to find the index of a particular character inside
the string, else it returns void.
• It is opposite to that of the [] operator.
def find(str, ch):
index = 0
while index < len(str):
if str[index] == ch:
return index
index = index + 1
return -1
LOOPING AND COUNTING
• For and while loops can be used for looping and counting.
• The following code counts the no of times a appears in the string.
fruit = “grapes"
count = 0
for char in fruit:
if char == ’a’:
count = count + 1
print (count)
Output : 1
STRING MODULE
• String module is a package which contains useful functions for
manipulating strings.
• To use the string module we need to import it first by using the
following line of code i.e.
import string
• Find Function : This inbuilt function finds the index of the character
in the string.
fruit = “guava”
fruit.find(“a”)
Output : 2
STRING MODULE (to be continued….)

• Find Function :
Try out
string=“banana”
string.find(”na”) #2
string.find(”na”,3) #4, (starts from index 3)
string.find(”b”,1,6) #-1, (checks between 1 to
2 excluding 2 index)
CHARACTER CLASSIFICATION
• Character Classification is a recognition of character (lowercase or
uppercase) or it’s a digit.
• String module provides several constants that are useful for these
purposes.
• string.lowercase contains all the letters that the system considers to
be lowercase.
• string.uppercase contains all the letters that the system considers to
be uppercase.
import string
print string.ascii_lowercase
print string.ascii_uppercase
print string.digits
Three ways to recognize lowercase

Method 1 :
def isLower(ch):
return string.ascii_lowercase.find(ch) != -1
Method 2 :
def isLower(ch):
return ch in string.ascii_lowercase
Method 3 :
def isLower(ch):
return ’a’ <= ch <= ’z’
String Operations
String concatenation
• X=‘3’
• Y=‘2’
• Z=X+Y
• Print(Z) #output: 32

• fnm=‘Raj’
• lnm=‘ Kumar’
• Fullnm=fnm+lnm
• Print(Fullnm) #output: Raj Kumar
Comments in python
• # Comment line
• ‘’’ Comment paragraph
inside comment para ‘’’
INT102
Conditionals
and
Iterations
The modulus operator

• The modulus operator works on integers (and integer expressions)


and yields the remainder when the first operand is divided by the
second.
• In Python, the modulus operator is a percent sign (%).
Example
• The syntax is the same as for other operators:
>>> quotient = 7 / 3
>>> print (quotient)
2
>>> remainder = 7 % 3
>>> print (remainder)
1
• So 7 divided by 3 is 2 with 1 left over.
Uses

• Check whether one number is divisible by another if x % y is zero,


then x is divisible by y.
• you can extract the right-most digit or digits from a number.
• For example,
x % 10 yields the right-most digit of x (in base 10). Similarly x % 100
yields the last two digits.
Boolean expressions

• A Boolean expression is an expression that is either true or false.


• One way to write a Boolean expression is to use the operator ==,
which compares two values and produces a Boolean value:
>>> 5 == 5
True
>>> 5 == 6
False
• True and False are special values that are built into Python.
Boolean expressions examples

• import random
• n1=random.randint(1,9)
• n2=random.randint(1,9)
• ans=eval(input("What is "+str(n1)+" + "+str(n2)+" "))
• print("Your ans is ",n1+n2==ans)
• Print(int(true))
Displays 1
• Print(int(false))
Displays 0
• Print(bool(0))
Displays false
• Print(bool(4))
Displays true
Comparison Operators

• x != y # x is not equal to y
• x>y # x is greater than y
• x<y # x is less than y
• x >= y # x is greater than or equal to y
• x <= y # x is less than or equal to y
NOTE: “= is an assignment operator and == is a comparison operator”.
Also, there is no such thing as =< or =>.
Logical operators

• There are three logical operators:


 and,
 or
 not
• For example, x > 0 and x < 10 is true only if x is greater than 0 and less
than 10.
• n%2 == 0 or n%3 == 0
• not(x > y) is true if (x > y) is false, that is, if x is less than or equal to y.
Logical operators example

• Print(bool(5>0 and 4>0))


• Displays true
• Print(bool(5>0 and 4<0))
• Displays false
• Print(bool(5>0 or 4>0))
• Displays true
• Print(bool(5>0 or 4<0))
• Displays true
Logical operators example

• X=true
• Y=false
• Print(“x and y is”,x and y) #output: false
• Print(“x or y is”,x or y) #output: true
• Print(“not x is”,not x) #output: false


Identity operators

• Identity operators compare the memory locations of two objects.


There are two Identity operators as explained below
Bitwise Operators
Membership Operators
Continue…

• Any nonzero number is interpreted as “true."


>>> x = 5
>>> x and 1
1
>>> y = 0
>>> y and 1
0
Keyboard Input
• input(): built in function to get data from keyboard.
• Takes data in the form of string.
• Eg:
>>> input1 = input ()
What are you waiting for?
>>> print input1
What are you waiting for?
• Before calling input, it is a good idea to print a message telling the user
what to input. This message is called a prompt.
• A prompt can be supplied as an argument to input.
• Eg:
>>> name = input ("What...is your name? ")
What...is your name? Arthur, King of the Britons!
>>> print name
Arthur, King of the Britons!
• If we expect the response to be an integer, then type conversion needs
to be done.
• Eg:
prompt = "What is the airspeed velocity of an unladen swallow?"
speed =int(input(prompt))
Conditional Execution

• To write useful programs we need the ability to check conditions and


change the behaviour of the program accordingly.
• Different conditional statements in python are:
– IF
– IF ---Else (Alternative Execution)
– IF--- ELIF---- ELSE (Chained Conditionals)
– Nested Conditionals
If Condition
• If x > 0:
print "x is positive“
• The Boolean expression after the if statement is called the condition. If
it is true, then the indented statement gets executed. If not, nothing
happens.
• Structure of If
– HEADER:
FIRST STATEMENT
...
LAST STATEMENT
If Condition
• There is no limit on the number of statements that can appear in the
body of an if statement, but there has to be at least one.
If Condition example

• If a > 0:
print (“a is positive”)
Alternative Execution
• A second form of the if statement is alternative execution, in which
there are two possibilities and the condition determines which one gets
executed.
• Eg:
if x%2 == 0:
print (x, "is even“)
else:
print (x, "is odd“)
• The alternatives are called branches.
If else Condition example

• r=eval(input("Enter input "))


• if(r<0):
• print("Wrong input")
• else:
• print("true value")

Continue….

• Since the condition must be true or false, exactly one of the


alternatives will be executed. The alternatives are called branches,
because they are branches in the flow of execution.
Chained Conditionals
• Sometimes there are more than two possibilities and we need more
than two branches.
if x < y:
print (x, "is less than", y)
elif x > y:
print (x, "is greater than", y)
else:
print (x, "and", y, "are equal“)
NOTE: There is no limit of the number of elif statements, but the last
branch has to be an else statement
Nested conditionals
• One conditional can also be nested within another.
if x == y:
print (x, "and", y, "are equal“)
else:
if x < y:
print (x, "is less than", y)
else:
print( x, "is greater than", y)
if 0 < x and x < 10:
print ("x is a positive single digit.“)

• Python provides an alternative syntax that is similar to mathematical


notation:
if 0 < x < 10:
print ("x is a positive single digit.“)
Wrapping of IF-ELSE into one function.
• Function is a block of code that performs a specific function.
• In python, function is defined by keyword “def”.
• For example:
x=eval(input(“enter value of x”))
def printParity(x):
if x%2 == 0:
print (x, "is even“)
else:
print (x, "is odd“)
• For any value of x, printParity displays an appropriate message. When you call it,
you can provide any integer expression as an argument.
Example

>>> printParity(17)
17 is odd
>>> y = 17
>>> printParity(y+1)
18 is even
Example
Calling of function depending upon input enter by user:
Example:
if choice == 'A':
functionA()
elif choice == 'B':
functionB()
elif choice == 'C':
functionC()
else:
print "Invalid choice."
Avoid Nested If

• For example, We can rewrite the following code using a single


conditional:
if 0 < x:
if x < 10:
print "x is a positive single digit.“
Better way:
if 0 < x and x < 10:
print "x is a positive single digit."
The Return Statement

• The return statement allows you to terminate the execution of a


function before you reach the end.
• Example
def evenodd(x):
if x%2:
return(True)
else:
return(False)
evenodd(x)
Task1: WAP to prompt a user to read the marks of three subjects.
Calculate the total marks and percentage of the marks and display the
message according to the range of percentage given in table:

Percentage Message
Per>=90 Distinction
Per>=80 && per<90 First class
Per>=70&& per<80 Second class
Per>=60&&per<70 Pass
Per<60 Fail
ITERATION
Doing the Same Thing Multiple Times

• It’s possible to do something repeatedly by just writing it all out


• Print ‘hello’ 5 times
>>> print('Hello!')
Hello
>>> print('Hello!')
Count n Hello
times >>> print('Hello!')
Hello
>>> print('Hello!')
Hello
Statements >>> print('Hello!')
Hello
Iteration and Loops
• A loop repeats a sequence of statements
• A definite loop repeats a sequence of statements a predictable number
of times

>>> for x in range(5): print('Hello!')


...
Hello
Count n Hello
times Hello
Hello
Hello
Statements
The for Loop
• Python’s for loop can be used to iterate a definite number of times
for <variable> in range(<number of times>): <statement>
• Use this syntax when you have only one statement to repeat
for <variable> in range(<number of times>):
<statement-1>
<statement-2>

<statement-n> >>> for x in range(3):
... print('Hello!')
... print('goodbye')
•Use indentation to format two or ...
Hello!
more statements below the loop goodbye
Hello!
header goodbye
Hello!
goodbye
Using the Loop Variable
• The loop variable picks up the next value in a sequence on each pass
through the loop
• The expression range(n) generates a sequence of ints from 0
through n - 1
loop variable

>>> for x in range(5): print(x)


...
0
1
2
3
4
>>> list(range(5)) # Show as a list
[0, 1, 2, 3, 4]
Counting from 1 through n

• The expression range(low, high) generates a sequence of ints from low


through high - 1

>>> for x in range(1, 6): print(x)


...
1
2
3
4
5
Counting from n through 1

• The expression range(high, low, step) generates a sequence of ints


from high through low+1.

>>> for x in range(6, 1, -1): print(x)


...
6
5
4
3
2
Skipping Steps in a Sequence

• The expression range(low, high, step) generates a sequence of ints


starting with low and counting by step until high - 1 is reached or
exceeded
>>> for x in range(1, 6, 2): print(x)
...
1
3
5
>>> list(range(1, 6, 2)) # Show as a list
[1, 3, 5]
While Loop
A for loop is used when a program knows it needs to repeat a block of
code for a certain number of times.
A while loop is used when a program needs to loop until a particular
condition occurs.
Flow of Execution for WHILE Statement
Looping Until User Wants To Quit
Range Function
• Range returns an immutable sequence objects of integers between
the given start integer to the stop integer.
• range() constructor has two forms of definition:
– range(stop)
– range(start, stop, step)
• start - integer starting from which the sequence of integers is to be returned
• integer before which the sequence of integers is to be returned.
The range of integers end at stop - 1.
– step (Optional) - integer value which determines the increment between each integer in
the sequence
Nested Loops

• Python programming language allows the usage of one loop inside


another loop.
• A final note on loop nesting is that you can put any type of loop inside
any other type of loop. For example a for loop can be inside a while
loop or vice versa.
Example
for i in range(1,11):
for j in range(1,11):
k = i*j
print (k, end=' ')
print()
• The print() function inner loop has end=' ' which appends a space
instead of default newline. Hence, the numbers will appear in one
row.
• Last print() will be executed at the end of inner for loop.
Exercise
1. Write a password guessing program to keep track of how many
times the user has entered the password wrong. If it is more than 3
times, print "You have been denied access." and terminate the
program. If the password is correct, print "You have successfully
logged in." and terminate the program.
2. Write a program that asks for two numbers. If the sum of the
numbers is greater than 100, print "That is a big number" and
terminate the program otherwise print sum.
3. Write a Python program that accepts a word from the user and
reverse it.
4. Write a python program to find those numbers which are divisible
by 7 and multiples of 5, between 1500 and 2700.
5. Write a Python program to get the Fibonacci series between 0 to 50.
6. Write a Python program which iterates the integers from 1 to 50. For multiples of
three print "Fizz" instead of the number and for the multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz“
7. Write a Python program to check whether an alphabet is a vowel or consonant.
8. Write a Python program to check a triangle is equilateral, isosceles or scalene.
Note :An equilateral triangle is a triangle in which all three sides are equal.
A scalene triangle is a triangle that has three unequal sides.
An isosceles triangle is a triangle with (at least) two equal sides.
Loop Control
Statements

Break and
Continue
Break
 It terminates the current loop and resumes
execution at the next statement, just like the
traditional break statement in C.
 The most common use for break is when some
external condition is triggered requiring a hasty
exit from a loop. The break statement can be used
in both while and for loops.
 If you are using nested loops, the break statement
stops the execution of the innermost loop and start
executing the next line of code after the block.
Flow chart of break statement
The break Statement
 The keyword break allows the programmer to terminate the
loop.
 When the break statement is encountered inside a loop, the
loop is immediately terminated.
Working of break in while and for loop
while test-Boolean-expression:

body of while

if condition:

break

body of while

Statement(s)
Working of break in while loop

for var in sequence:


body of for
if condition:
break
body of for
Working of break in for loop
statement(s)
Example 1
for letter in “Python”:
if letter == 'h':
break
print (“Current Letter :”, letter)
Example 2
var = 10
while var > 0:
print (“Current variable value :”, var)
var = var -1
if var == 5:
break
print "Good bye!"
Continue statement
 Causes the loop to skip the remainder of its body
and immediately retest its condition prior to
reiterating.
Continue statement
 Itreturns the control to the beginning of the while
loop.. The continue statement rejects all the
remaining statements in the current iteration of the
loop and moves the control back to the top of the
loop.
 The continue statement can be used in
both while and for loops.
Flow Diagram
Working of continue in while and for
loop
while test-Boolean-expression:

body of while

if condition:

continue

body of while

Statement(s)
Working of continue in while loop

for var in sequence:


body of for
if condition:
continue
Working of continue in for loop
body of for
statement(s)
Example1
for letter in “Python”:
if letter == 'h':
continue
print (“Current Letter :”, letter)
Example 2
var = 10
while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :', var )
print ("Good bye!“)
Conclusion
 The break statement is used to terminate
from the loop.

 Where as continue statement is used to


skip the current iteration and continues
with the next iteration.

You might also like