Python 18 Sept 24 09 14 00
Python 18 Sept 24 09 14 00
Advantages:
Easy to use.
Expressive language.
Interpreted language:
Its completeness
Cross platform language.
Disadvantages:
• Not the fastest language
Lesser librariess than c++, PERL, JAVA
In
Not easily convertible
Python Shell.
Interactive
Command
Command
Mode
is
is
typed in front of
previous commands and if still, we could not edit we need to type everything again.
Script Mode
The saved instructions can be used again in future. It is much preferred over interactive
mode by experts in the program
The script mode is suitable for large programs.
Editing your script is easier in script mode.
1
Q1. What is Python?
Python is most praised for its elegant syntaxand readable code. It is based on or
CPython: this is the default, and what you should be using if you have no idea.
q3.What is Spyder?
editing, interactive testing, debuggingof the programs and introspection features. ...
2
CHARACTER SET
Character Set: Set of valid characters recognized by a language. Python has the
Letters
A-Z, a-z
0-9
> Digits
> Special symbols space +-* **\()[]{}/=
/ = ==<,>.""",
&#<=>=@_(underscore)
Whitespaces Blank space, tabs (), carriage return (J), newline, formfed.
Other characters Python can processall ASCII and Unicode characters as part of
data or literals.
An English Sentence
The lexical
types
(1
units
of tokens
1 1111
or tokens
an English sentence - here two
in
are used: words and punctuationcharacters
1/
A Python Program
age = 15<
contribution = 710.754 A floating-point value or floating point literal
d. ldentifiers e. Punctuators
3
Keywords :These are the words which have some special purpose to the Python interpreter. For eg.:
True, False, None, and,or not. As Python is case sensitive, keywords must be written exactly as given
in Table 3.1.
as elif if
yield
ldentifiers:These are the names given to the different parts of a program. For eg.:to a variable,
list, dictionary etc. The rules for forming ldentifiers are asfollows:
anywhere in name.
ldentifiers are case sensitive.Name, name
It cannot be a keyword or reserved word given in Table 3.1.
They are unlimited in length. However, it is preferred to keep it short and meaningful.
a. String literal
b. Numeric literal
C. Boolean literal
d. None
Escape sequence: These are non-graphic characters that cannot be typed directly from
the keyboard e.g.: backspace, tabs, carriage return etc. These non-graphic characters
can be represented by using the escape sequence. An escape sequenceis represented
Integer: These are whole numbers without any fractional part. It may contain (+),(-) sign.
4
Floating point literals: These are numbers with fractional part. .Commas cannot come in these
literals. It may contain (+),(-) sign. It should have atleast one digit with the fractional point.
d. None: It means absenceof a value or the end of a list. Python does not display anything
Operators: The symbols that trigger someaction on the data are called operators. The different type
of operators are
a. Arithmetic operators c. Relational operators
a. Arithmetic operators: Python supports arithmetic operators (Table 3.3) to perform the four basic
1*" operator repeats the item on left side of the operator if first operand is a string and second
Operators (+)and (*) work in similar manner for other sequence data types like list and tuples.
b. Relational operators: They compare two values. They are >, <, >,<=, I=, ==, Conside the given
Python variables num1 = 10, num2 = 0, num3 = 10, str1 ="Good,str2 ="Afternoon"for the following
examples in Table 3.4:
0 (numeric value).
0.1 +0.1+0.1 == 0.3 is not true in python because of internal rounding error.
c. Assignment operator: Assignment operator assigns or changes the value of the variable on its left.
It is represented as '=. For e.g.: a =7 It means the value 7 has been assigned to variable 'a'.
6
Augmented Assignmentoperator:
%=, //=, and **=,
b.
there are other assignment
num1 + num2
operators like , +=,*=, E,
d. Logical operator: There are three logical operators (Table 3.6) supported by Python. These
operators (and, or, not) are to be written in lower case only. The logical operator evaluates to either
7
Membership Operators: Membership operator (Table 3.7) is used to check if a value is a member of
the given sequenceor not.
Associativity:It is the order in which an expression having multiple operators of same precedence
is evaluated. All operators are left associative except exponentiation which has right associativity.
A Parenthesis can be used to override the precedence of operators. The expression within () is
Operator Prêcdedence
i. ()
R = 3**8
= 6561
CTY
ii.
ii. %,ll
v. +,
V. >,6,>=,<=,==,!=
vi.
vii.
Not
And
VIDAV
vii. Or
of is more
1
AMBALA
Python evaluate the following expression:
* than that of +
20 + 30 * 40
= 1220
Example 3.6: How will Python evaluate the following expression: (20 + 30) * 40
Solution: Using parenthesis(),we have forced precedence of + to be more than that of *
- (20+30)* 40 # Step 1
Datatypes: Every value belongs to a specific data type in Python. Data type identifies the type of data
which a variable can hold and the operations that can be performed on those data. Figure 3.6 enlists
Boolean List
Tuples
Numbers
String
List
Dictionary
HAR SCHOOR
CITY
Number: This datatype store numeric values in Python. Core datatypes in Python are
a. Integers
i. Integers
ii. Booleans
MBA
b. Floating point numbers
a. Integer:
Integers :Theyare whole numbers without any fractional part. It can be +ve or -ve.
Length is available by the memory available. For e.g.: +78,-45
Boolean: It has twO values: True or false. True represents 1(numeric value) & boolean
False represents 0 (numeric value).For e.g.:
print(bool(0)) print(bool(1)
b. Floating point numbers:These are numbers with fractional part. .Commas cannot come in these
numbers. It may contain (+),(-) sign. It should have atleast one digit with the fractional point.
Example 3.1
Variables of simple data types like integer, float, boolean etc. hold single value. But such variables are
not useful to hold multiple data values, for example, names of the months in a year, names of
students in a class, names and numbers in a phone book or the list of artifacts in a museum. For this,
Python provides sequencedata types like Strings, Lists, Tuples, and mapping data type Dictionaries.
Sequence:A Python sequenceis an ordered collection of items, where each item is indexed by an
integer value. Three types of sequencedata types available in Python are Strings, Lists and Tuples. A
They can be accessed by using the index. Each character has a two way index: forward index &
backward index.
If we have a string say, 'COMPUTER.
Forward Direction
2 3 4 5 6 7
Indexing
C M P T E R
-7 -6 -5 4 -3 -2 -1
Backward Direction
Indexing
Name ='Rohit
print(Name[0])
print(Namei4)
will
will
print R
print
B
t
print(Name[5]) will give an error
Name[o]= M
Name = "Mohit"
Variables: Variable is an identifier whose value can change. For example variable age can have
different value for different person. These are named locations that refer to a value & whose
value can be processed during program run. In Python, we can use an assignment statement to
10
Characteristics of a variable
it.
Name = "Rohit" print(x) error
i.
ii.
print(name) X= 20
print(y) print(x) will return 20
whose value can change. For examplevariable age can have different value for different person
immutable
15 16 17 18 19 20
Memory
Locations
201 202 203 204 205 206
Age RA 00
Age = 15 variable age point to memory location201
But,
Age = 16
if
Python variable
This is
we write now
variable age point to memory location202
do not have fixed location. Its location changes every time you change the value.
called immutable type variable.Mutable means that in the same memory address new value
TY
can be stored as & when you want.
Multiple Assignments
a = b= c= 10 a= 11, b= 210, c=130
X,y,Z = 1,2,3
X,X =5,6
Y.y= x+ 10, x +16
print(x,y) Output:6 22
Dynamic typing: A variable pointing to a value of certaintype, can be made to point to a value
of differenttype.
x=10
i.
y= x/2 output: 5.0
x= "day"
y=x/2 error
Dynamictyping causes error as shown above.Be cautious while using it because Python does
11
Python Program:
La-10
Statements >Expression
b=20-a
print(a,b)
Indentation
Comment: These are the additional readable information to clarify the source code.
Function: A function refers to a set of statements or instructions grouped undera name that perform
specified tasks. For repeated or routine tasks, we define a function. A function is defined once and can
be reused at multiple places in a program by simply writing the function name, i.e., by calling that
function.
Python has many predefined functions called built-in functions like print(), input(), int(), float().
PRINTFunction
SEP Argument:It inserts a separator character between the items being printed in a
line. By default, a blank space is inserted between the items. For e.g.: in the statement
>>> My@first@python@program.
END Argument: By default, a newline character is appended at the end of the line.
print("My"" first","python","program.")
But if want both the sentences in continuity. Iwill change the value of end argument.
I
print("My","first","python","program.",end = ")
print("Writing in script mode") will give the output
12
An empty print() function prints a blank line.
INPUTO Eunction:
Datatype conversion functions: Use the functions int() & float() to convert the value to
print(Name,age) Rohit 13
print(age+1) 14
When you are using int() function enter integer type value only and for float() function
enter float type value only, else error will come .For e.g.:
Age = int( input("Enter your age:") Enter your age: 13.5 (ERROR)
Debugging: The process of identifying and removing logical and runtime errors is called
errors
debugging. We need to debug a program so that is can run successfully and generate the desired
output.
Due to errors, a program may not execute or may generate wrong output.:
i) Syntax errors
incorrect indentation
empty block
Logical Errors: A logical error/bug (called semantic error) does not stop execution but the program
behaves incorrectly and produces undesired /wrong output. Since the program interprets successfully
even when logical errors are present in it, it is sometimes dificult to identify these errors.
13
For example, if we wish to find the average of two numbers 10 and 12 and we write the code as 10+
12/2, it would run successfully and produce the result 16, which is wrong. The correct code to find
the average should have been (10 + 12) /2 to get the output as 11. Here are some examples of
Runtime Error: A runtimne error causes abnormal termination of program while it is executing.
Runtime error is when the statement is correct syntactically, but the interpreter cannot execute it.
For example, we have a statement having division operation in the program. By mistake, if the
denominator value is zero then it will give a runtime error like "division by zero". Some examples of
Python runtime errors:
SCHÒE
CITY
CHARU
MDAV
AMBALA
14
CONDITIONAL & ITERATIVE STATEMENTS
a. Empty statement: It does nothing. Simply moves to the next statement in the flow of control. It is
used when a statement is not required by the logic of the program but syntax of the language
requires
it.
For e.g.:
pass
Whenever Python encounters a pass statement, it does nothing and moves to the next statement
in
if a > b:
StatementControl Flow
Control Statements: They control the flow of control in a program. Theyare of three types:
False
Condition?
The exit
condition
True
Statement 1
Statement 1
3
Statemnent
AMP
The Sequence Construct The Iteration Construct
b. Selection: They test the condition & selectively execute the code depending on the
outcome of the test condition. This construct is also called decision construct.
15
The Selection Construct
One course-of-action
True
Condition ? Statement 1 Statement
2
False
Statement 1
Anotne
Statement 2
cOurse-of-action
IF Statement: It's a compound statement & its syntax is as follows:
if <cond>:
statement
True, the statements in the body of the loop areexecuted, otherwise ignored.
Other forms of IF statement
f<cond>. b. if <cond>:
statement(s) statement(s)
else: elif <cond>
When
statement(s)
statement(s)
appear, the Python interpreter executes code inside one block that
is selected based on the condition. Number of elif is dependenton the number of conditions to be
checked. If the first condition is false, then the next condition is checked, and so on. If one of the
conditions is true, then the corresponding indented block executes, and the ifstatement terminates.
After that, the statements outside the if..else are executed or the program terminates if there are no
further statements.
Characteristcs of if..else
• The and
if...else elif statements control the program flow.
• The statement
if in programmingis used for decision making.
• The statement
if is evaluated on the basis of the specified condition(s).
• The else block can be attached with the if statement & it is executed if the condition is
false.
16
PYTHON ASSIGNMENT1
OL
Q8. Define the following terms with examples.
TT
Q9. Write the rules for naming the identifiers. Give examples.
Q10. How many type of tokens are there in Python 2Name & explain them.
Ql1. In how many ways can you give the comment. Give one example of each.
Q12. What are literals ? Give two examples for each of the following:
i. Integer literal String literal iii. Boolean literal iv. Float literal
ii.
Q13. How nany type of literals are there in Python ? Name & explain them.
Q14. Name the built-in literals of Python.
Q17. What
Q18. Name
Q19.
is None
different
Differentiate
literal in Python.
Q21. What is the operator associativity of *** and the rest of operators.
ASSIGNMENT-2
Q3. How many integer types are supported by Python. Name them
Q4. What is the numeric value of Boolean True & False.
Q5. What are the advantages & disadvantages of floating point numbers.
Q6. How many precision digits are there in floating point numbers.
Q7. How
Q8. What
Q10. Explain
are string stored
is the use
with an
in
example how
Python?
of sequencedatatype?
string datatype
them.
CA
Q13. What is dynamic typing?
Q16. What is the datatype of the value returned by the inpu() & print() functions?
Q17. Explain the puposeof SEP and END argumentsof the print() function.
Q18. Which two functions are used to convert string type data to integer & float type data.
Q20. How many type of errors are there? Name & explain them with examples.
AMB
1
ASSIGNMENT 3
ii.
ii. print(c*2, c + d, end= " ") iv. print(a>b) v. print(c<d)
vi. print(a>b or c<d) vi. print(a>b and c<d) vii. print(not(a>b) or c>d)
ix. print(cl= d) X. print(0.1+0.3+0.2 = 0.6) xi. print(bool(0))
xi. print(bool(1))
i.
03.If x,y =1,2
i. = Y,X+y
x,y X=y ii. a,b =1,4 iv. a = "PYTHON"
ii.
print(x.y) y= x+y b,a =a,b print(a[2])
Q4. What is the difference between the two statements and i.:
i.
a =6 ii. a == b
i.
Q5. If L1 = (1,4,7,9], then what will be the output forthe following expressions:
5 in L1 ii. 5 not in L1 ii. 6 in L1 iv. 6 not in L1
CITY
i.
Q6. Neha for the following code entered the value 500.50
a = int(input("Enter your fees:")
She got an error. Why?
Q7. Neha wrote following code:
= int(input("Enterthe salary:")
a= a+ 500
print(a)
c.
d.
e.
c= input(float("Enter
print(c)
print(d)
d=a+b
temperature:")
MBALA
Q9. Why you should not use the equality operator(==)operator to determine whether objects of
type float are equal?
1. Which of the following Boolean expressions is not logically equivalent to the other three?
a) not(-6<0 or-6>10) b) -6>=0 and -6<=10
c) not(-6<10 or-6==10) d) not(-6>10 or-6==10)
Python?
a)4.7-1.5 b)7.9*6.3 c)1.7%2 d) 3.4 + 4.6
a) (1,3) b) (0,3)
of the following
c) (1,0)
Python expression?
d) (3,1)
CIT
7. What will be the value of the following Python expression?
LA
print(float(4+int(2.39)%2)
a) 5.0 b) 5 c) 4.0 d) 4
MBA
a = 4+2**5//10
print(a)
a) 3 b) 7 c) 77 d) 0
a)True b) False
2
Sequence Control Assignment1
Q3. Explain the following control statements with the help of a diagram.
a. Sequence b. Selection
OOL
4. check year is
7. WAP to input any character and check whether it is alphabet, digit or special character
11. WAP to input marks of five subjects Physics, Chemistry, Biology, Mathematicsand Computer.
• Percentage >= : B
BA
80% Grade
Percentage>=70% :Grade C
60%: Grade D
Percentage >=
12. WAP to input basic salary of an employee and calculate its Gross salary according to following:
If BasicSalary <= 10000 then HRA = 20%, DA =80%
•
13. The current year and the year in which the employee joined the organization are entered
through the keyboard. If the number of years for which the employee has served the organization
is greater than 3 then a bonus of Rs. 2500/- is given to the employee otherwise no bonus.
14. Given the length and breadth of a rectangle, write a program to find whether the area of the
rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5and
breadth =4 is greater than its perimeter
1
Q15. Tell whether a number is divisible by5 or 11 or both.
Q16 Write a program to calculate the salary as per the following table
Year of
100
>= 10 Graduate 9000
Q18: WAP that calculates the total discount on a shopping cart based on the following
conditions:
2
Q19. WAP that determines whether a person is eligible for a gym membership or not:
Q20. WAP that determines the ticket price fora concert based on the attendee's age &
membership status:
10OH
• if they are not a member,the ticket price is $30.
Q21. WAP that calculates the insurance premium for a car based on the following conditions:
• if the driver has had no accidents in the last 3 years, the premium is $2000.
• if the driver has had 1-2 accidents, the premium is $2500.
• if the driver has had more than 2accidents, the premium is $3000.
if the driver is 25 years old or older:
if the driver has had no accidents in the last 3years, the premium is $1500.
if the driver has had 1-2 accidents, the premium is $2000.
MAM
if the driver hashad more than 2accidents, the premium is $2500.