Python PDF
Python PDF
Computer Organization
• 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
Pick Brush
Brush
Stop
Daily routine
• Let us explore more as the day goes by…
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
• 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 :
• ACM – ICPC
• Google Code Jam
• Topcoder Open
• Google foo bar challenge
• Facebook Hacker cup
UNIT 1
• Python is Interactive − You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
• 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.
• 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
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,
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.
• 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
• 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.
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.
• 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
• Keywords define the language’s rules and structure and they can’t be
used as variable names.
– 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…..)
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.
• 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
• 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
• 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
• 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
>>> 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
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
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
body of while
if condition:
continue
body of while
Statement(s)
Working of continue in while loop