0% found this document useful (0 votes)
4 views145 pages

Python (Basics, If-Else, Looping) 2022

The document provides an overview of programming languages, specifically focusing on Python, which is described as a high-level, interpreted, and object-oriented language. It covers Python's history, features, character sets, tokens, data types, and practical applications in various industries. Additionally, it explains the structure of identifiers, variables, and the different types of data that can be stored in Python.

Uploaded by

thestore.hall0
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)
4 views145 pages

Python (Basics, If-Else, Looping) 2022

The document provides an overview of programming languages, specifically focusing on Python, which is described as a high-level, interpreted, and object-oriented language. It covers Python's history, features, character sets, tokens, data types, and practical applications in various industries. Additionally, it explains the structure of identifiers, variables, and the different types of data that can be stored in Python.

Uploaded by

thestore.hall0
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/ 145

Amit Kumar Pandey, PGT-CS, K V Aliganj

What is programming Language?


A programming language is a computer
language that is used by programmers
(developers) to communicate with computers.

What is a Program?
It is a set of instructions written in any specific
language ( C, C++, Java, Python) to perform a
specific task.

Amit Kumar Pandey, PGT-CS, K V Aliganj


• Python is a computer programming language
often used to build websites and software,
automate tasks, and conduct data analysis.
Python is a general-purpose language, meaning it
can be used to create a variety of different
programs and isn't specialized for any specific
problems.

• Python is a general-purpose interpreted,


interactive, object-oriented, and high-level
programming language. It was created by Guido
van Rossum during 1985- 1990. Python source
code is also available under the GNU General
Public License (GPL).
Amit Kumar Pandey, PGT-CS, K V Aliganj
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 now maintained by a core development
team at the institute, although Guido van Rossum still
holds a vital role in directing its progress.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Python is a high-level, interpreted, interactive and object-oriented
scripting language. Python is designed to be highly readable. It uses
English keywords frequently where as other languages use punctuation,
and it has fewer syntactical constructions than other languages.

Python is Interpreted − Python is processed at runtime by the


interpreter. You do not need to compile your program before executing it.
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.
Python is a Beginner's Language − 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.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Python Features
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.
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.

Amit Kumar Pandey, PGT-CS, K V Aliganj


The language is used by companies in
real revenue generating products,
such as:
• In operations of Google search engine, youtube, etc.
• Bit Torrent peer to peer file sharing is written using
Python
• Intel, Cisco, HP, IBM, etc use Python for hardware
testing.
• i–Robot uses Python to develop commercial Robot.
• NASA and others use Python for their scientific
programming task.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Getting Python
The most up-to-date and current source code, binaries,
documentation, news, etc., is available on the official
website of Python https://www.python.org/.

You can download Python documentation


from https://www.python.org/doc/. The
documentation is available in HTML, PDF, and
PostScript formats.
aliganj.kvs.ac.in

Amit Kumar Pandey, PGT-CS, K V Aliganj


Python Character set
Character set is a set of valid characters that a language
can recognize. Python has following character sets:

1. Letters: A-Z, a-z


2. Digits: 0-9
3. Special Symbols: +,- , /,*,**,\,(),[],{} , ’ , ” , _
4. White spaces: blank space, tabs, new line
5. Other characters: All ASCII and Unicode characters

Amit Kumar Pandey, PGT-CS, K V Aliganj


Tokens
The smallest individual unit of a program is
known as Token. Python has following Tokens:
1. Keywords
2. Identifiers/Names/variables/object
3. Literals/constants
4. Operators
5. Punctuators

Amit Kumar Pandey, PGT-CS, K V Aliganj


1-Keywords
• A Keyword is a special word having special
meaning reserved by programming language.
• Keywords are the words that convey a special
meaning to the language
interpreters/compilers.
• Python contains following keywords: False,
None,True,and,break,class,continue, def, elif,
else,for,if, import,not,or while

Amit Kumar Pandey, PGT-CS, K V Aliganj


2- Identifiers(variables)
• Identifiers are fundamental building blocks of
program and are used to store different values
during different phase of program.
• Following are the rules to form valid Identifier
1. The first character must be a letter or _
2. Upper and lowercase characters are different
3. Digits 0 -9 can be used except first character
4. It must not be a keyword.
5. It can not contain any special character except_
Amit Kumar Pandey, PGT-CS, K V Aliganj
• Following are valid identifiers:
Myname, date5_7_2018, a2B3c4, _akp

Following are invalid identifiers:


My-name, date 5_7_2018, 2a3B4c, -akp

Amit Kumar Pandey, PGT-CS, K V Aliganj


Variables and Types
• When we create a program, we often like to store
values so that it can be used later. We use objects to
capture data, which then can be manipulated by
computer to provide information.
• By now we know that object/ variable is a name
which refers to a value.
Every object has:
A. An Identity- can be known using id (object)
B. A type – can be checked using type (object) and
C. A value

Amit Kumar Pandey, PGT-CS, K V Aliganj


A. Identity of the object: It is the object's
address in memory and does not change
once it has been created.
(We would be referring to objects as variable for
now)
B. Type (i.e data type): It is a set of values, and
the allowable operations on those
C. values/Constant. It can be one of the
following:

Amit Kumar Pandey, PGT-CS, K V Aliganj


DATA TYPES
Data type in Python specifies the type of data we are
going to store in any variable, the amount of memory it
will take and type of operation we can perform on a
variable. Data can be of many types e.g. character,
integer, real, string etc.
Python supports following data types:
• Numbers ( int, float, complex)
• String
• List
• Tuple
• Dictionary
Amit Kumar Pandey, PGT-CS, K V Aliganj
1. Number

Number data type stores Numerical Values. This data


type is immutable i.e. value of its object cannot be
changed (we will talk about this aspect later). These
are of three different types:
a) Integer & Long(removed in Python 3.6 ver)
b) Float/floating point
c) Complex
Range of an integer in Python can be unlimited range
subject to available memory.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Integers are the whole numbers consisting of + or –
sign with decimal digits like 100000, -99, 0, 17. While
writing a large integer value, don’t use commas to
separate digits. Also integers should not have leading
zeros.
>>> a = 10
>>> type(a) # type ( ) is used to check data type of value
<type 'int'>

>>>c=10
>>>c = c * 5669
>>> type(c)
<type ‘int'>

Amit Kumar Pandey, PGT-CS, K V Aliganj


• Integers contain Boolean Type which is a
unique data type, consisting of two constants,
True & False. A Boolean True value is Non-
Zero, Non-Null and Non-empty.
Example
>>> flag = True
>>> type(flag)
<class 'bool'>

Amit Kumar Pandey, PGT-CS, K V Aliganj


Floating Point: Numbers with fractions or
decimal point are called floating point
numbers.
A floating point number consist of sign (+,-)
sequence of decimals digits and a dot such as
0.0, -21.9, 0.98333328, 15.2963.
• These numbers can also be used to represent
a number in engineering/ scientific notation.

-2.0X 105 will be represented as -2.0e5


2.0X10-5 will be 2.0e-5

Amit Kumar Pandey, PGT-CS, K V Aliganj


Complex: Complex number in python is made up of
two floating point values, one each for real and
imaginary part.
For accessing different parts of variable (object) x;
we will use x.real and x.image. 1+0j denotes zero
imaginary part.

Example
>>> x = 1+0j
>>> print (x.real,x.imag)
1.0 0.0
Example
>>> y = 9-5j
>>> print (y.real, y.imag)
9.0 -5.0
Amit Kumar Pandey, PGT-CS, K V Aliganj
2.None
This is special data type with single value. It is used to
signify the absence of value/false in a situation. It is
represented by None.
None means there is no useful information.
Example:
>>>a=10
>>>b=None
>>>print(a)
10
>>>print(b)
None
Amit Kumar Pandey, PGT-CS, K V Aliganj
3.Sequence
• A sequence is an ordered collection of items,
indexed by positive integers.
• It is combination of mutable and non
mutable data types.
• Three types of sequence data type available
in Python are
a. Strings
b. Lists
c. Tuples.
Amit Kumar Pandey, PGT-CS, K V Aliganj
a.String
String: is an ordered sequence of letters/characters. They are
enclosed in single quotes (‘ab’) or double (“ab”).
The quotes are not part of string. They only tell the computer
where the string constant begins and ends.
They can have any character or sign, including space in them.
These are immutable data types.
Example
>>> a = 'Raj‘
>>>print(a)
Raj

Amit Kumar Pandey, PGT-CS, K V Aliganj


String types in Python
(i)Single line string
Ex.
>>>a=‘hello’
>>>print(a)
hello

(ii) Multiline string


(a) By using backslash
Ex.
>>>a=‘Python \
Language’
>>>print(a)
Python Language

Amit Kumar Pandey, PGT-CS, K V Aliganj


(b) By using triple quotation marks
Ex.
>>>a=‘’’hello
…there’’’
>>>print(a)
hello
…there

>>>a=“””hello
…there”””
>>>print(a)
hello
…there

Amit Kumar Pandey, PGT-CS, K V Aliganj


Size of string(len() function)
• Size of the string is the count of characters in
string.
Ex.
‘abc’- size is 3
‘duzone’- size is 6
>>>a=‘abc’
>>>len(a)
3

Amit Kumar Pandey, PGT-CS, K V Aliganj


Escape sequences
• Python allows you to have certain non-graphic
characters in string values.
• Nongraphic characters are those characters
that can not be typed directly from keyboard
e.g. back space, tabs, return etc.
• Those non graphic characters cab be
represented by a backslash(\) followed by one
or more characters.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Escape Characters
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to
insert.
An example of an illegal character is a double quote inside a string that is
surrounded by double quotes:

Example
You will get an error if you use double quotes inside a string that is
surrounded by double quotes:

txt = "We are the so-called "Vikings" from the north.“


the escape character allows you to use double quotes when you normally
would not be allowed:

txt = "We are the so-called \"Vikings\" from the north."

Amit Kumar Pandey, PGT-CS, K V Aliganj


Examples
Code Result
\' Single Quote
\\ printBackslash
single backslash
\n New Line

\t Tab

Amit Kumar Pandey, PGT-CS, K V Aliganj


Size of string…..
• If your string literal has an escape sequence contained in it,
then make sure to count the escape sequence as one
character.
• Example:
“\ab”- size is 2 (\a is a escape sequence hence counted as 1)
“Ram\’s bat”- size is 9(\’ is counted as 1)

>>>a= “Ram\’s bat”


>>>print(a)
Ram’s bat
>>>len(a)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Size of string…
For multiline strings created with triple quotes

While calculating the size, the EOL(end of line) character at the end of line is
also counted in the size.
Example:
>>>a=‘’’x
…y
…z’’’
>>>len(a)
11
>>>print(a)
x
…y
…z

Amit Kumar Pandey, PGT-CS, K V Aliganj


Types of String

1: Normal ASCII String:This type of string type holds


string of zero or more ASCII characters.
Example: ‘ram’ , “her’s” , ‘ a “Good”boy’

2: Unicode string: This type of string can hold unicode


characters.
Example: u”ram” , u”मानव”

>>>b=u"रामलाल"
>>> print(b)
रामलाल

Amit Kumar Pandey, PGT-CS, K V Aliganj


To get memory size of integer and float variable
Size of any variable-object can be find out using
command sys.getsizeof()
>>> import sys
>>>a=10
>>>sys.getsizeof(a)
14
>>>a=123456
>>>sys.getsizeof(a)
16
• Integer upto 5 digits occupy 14 bytes in memory and
after that 16 bytes.
• Float occupy 16 bytes in memory
Amit Kumar Pandey, PGT-CS, K V Aliganj
b.List
It is an ordered set of values enclosed in square brackets [].
Values in the list can be modified, i.e. it is mutable.
Let‟s look at some example of simple list:

• i) >>>L1 = [1, 2, 3, 4] # list of 4 integer elements.


• ii) >>>L2 = [“Delhi”, “Chennai”, “Mumbai”] #list of 3 string elements.
• iii) >>>L3 = [ ] # empty list i.e. list with no element
• iv) >>>L4 = [“abc”, 10, 20] # list with different types of elements

Note: We will study List in details in coming Chapters.

Amit Kumar Pandey, PGT-CS, K V Aliganj


c. Tuple
• Tuples are represented as list of Comma
separated values of any data type with in
parenthesis. Tuples are non-mutable
Following are some tuples:
• P=(1,2,3,4)
• P1=(2,6,1)
• S=(‘a’, ‘e’, ‘i’, ‘o’, ‘u’)

Note: We will study List in details in coming Chapters.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Dictionary
• The dictionary is an unordered set of comma
separated key:value pairs, with in {} with
unique values. These are Mutable.
>>>vowels={‘a’:1, ‘e’:2, ‘i’:3, ‘o’:4, ‘u’:5}
>>>vowel[‘a’]
>>>1
Note: Dictionary shall be covered in details.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Input/Output
Printing data
• print() function does two things: it convert the object
to string and puts the characters of those strings on
the standard output.
• Examples:
>>> n1=10
>>> n2=20
>>> s=n1+n2
>>> print(s)
>>>print(“The Sum is”, s)
>>>print(s, “Is the sum of”,n1,
Amit Kumar “and”,n2)
Pandey, PGT-CS, K V Aliganj
• Other formats of print()
print using concatenation operator(+)
Example:
>>>a=“hima”
>>>b=“wari”
>>>print(a+b)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Input() Function
• This function read input from standard input
during run time. Using this function you can
input the string values not numbers.
• Example
>>>x=input(“Enter name:”)
Enter name:ab
>>>print(x)
ab
Amit Kumar Pandey, PGT-CS, K V Aliganj
• Inputting Numeric values using input()
function.
n1=int(input(“Enter first number”))
n2=int(input(“Enter second number”))
n3=n1+n2
print(“Sum of”,n1,”and”,n2,”is”,n3)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Numeric conversion
• int(x)
• Float(x)
Example:
>>>n1=int(“20”)
>>>n2=int(“40”)
>>>print(n1+n2)
60

Amit Kumar Pandey, PGT-CS, K V Aliganj


Assignments
1.Write a program to enter length and breadth
of a rectangle and print its area.
2. Write a program to enter radius of circle and
print its area.
3. Write a program to enter principle, rate and
time and calculate simple interest.
4. Write a program to enter two numbers and
print their sum, difference, multiplication and
division.
5. Write a program to enter the sides of a square
and print the area and perimeter.
Amit Kumar Pandey, PGT-CS, K V Aliganj
Mutable & Immutable Types
The Python data types can be classified into two
Mutable and Immutable.
Lets dive deeper into the details of it…
Since everything in Python is an Object, every variable
holds an object instance. When an object is
initiated, it is assigned a unique object id.
An object whose internal state(contents) can be
changed is mutable. On the other hand,
immutable doesn't allow any change in the
object’s internal state(contents) once it has been
created.

Amit Kumar Pandey, PGT-CS, K V Aliganj


1. Immutable types: Those that can never
change their values.
Ex.
Integer
Float
Boolean
String
Tuple

Amit Kumar Pandey, PGT-CS, K V Aliganj


• In Pyhton, variable names are just the
reference to value-object i.e data value. The
variable name do not store values themselves.
x=7
Pyhton internally makes variable
x 7 Names reference a value

Amit Kumar Pandey, PGT-CS, K V Aliganj


a=5 a
b=a b
5
c=5 c
Now
a=10 10
a
c=7 b 5
7
b=c c

Amit Kumar Pandey, PGT-CS, K V Aliganj


>>>x=5
>>>id(5)
1594024784
>>>id(x)
1594024784

Here variable x is currently referencing location


1594024784(which is also the memory location of 5).
Recall that variable is not a storage location in
python, rather a label pointing to a value object)

Amit Kumar Pandey, PGT-CS, K V Aliganj


>>> a=5
>>> id(a)
1525408592
>>> id(5)
1525408592
>>> b=a
>>> id(b)
1525408592
>>> c=b
>>> id(c)
1525408592

Amit Kumar Pandey, PGT-CS, K V Aliganj


• Same way the objects of following value types
are also immutable:
1.Floating point numbers
2. Booleans
3. String
4. Tuples
Note: Immutable follows reference

Amit Kumar Pandey, PGT-CS, K V Aliganj


2. Mutable Types:
The mutable types are those whose values can
be changed in a place. Lists and Dictionaries.
To change a member of a list, you may write:
Lis=[4,5,6]
Lis[1]=40
It will make the list namely Lis as [4,40,6]
Note: mutable follows values

Amit Kumar Pandey, PGT-CS, K V Aliganj


>>> m=[1,2,3]
>>> n=m
>>> id(m)
34182048
>>> id(n)
34182048
>>> m.pop()
3
>>> m
[1, 2]
>>> id(m)
34182048
>>> id(n)
34182048
>>>

Amit Kumar Pandey, PGT-CS, K V Aliganj


Operators
• The symbols that trigger the
operation/action on data, are called
Operators, and the data on which operation
is being carried out are referred to as
Operands.
1. Arithmetic operators
2. Relational operators
3. Logical operators

Amit Kumar Pandey, PGT-CS, K V Aliganj


1. Arithmetic Operators
• Arithmetic operators are used to perform arithmetic
calculations.
Following are the basic operators:
+ Addition
- Subtraction
* Multiplication
/ Division
// floor division
% Remainder (modulus)
** Exponentiation

Amit Kumar Pandey, PGT-CS, K V Aliganj


Arithmetic operators can further be divided into
following two types based on number of operands:
A. Unary Operators: The operators require one
operand. Unary + and Unary –
For example,
If x=10 then +x means 10 (Unary +)
If x=-4 then –x means 4 (Unary -)
If x=-4 then +x means -4

Amit Kumar Pandey, PGT-CS, K V Aliganj


B. Binary Operators: Operators that act upon two operands.

i. Addition
ii. Subtraction
iii. Multiplication
iv. Division

v. Floor Division :The floor division is the division in which only


whole part of the result is given in the output and fraction
part is truncated.
For example,
>>>a=15.9
>>>b=3
>>>print(a//b)
5.0

Amit Kumar Pandey, PGT-CS, K V Aliganj


• Floor division for negative numbers rounds
down(towards –infinity).
>>>a=-22
>>>b=3
>>>print(a//b)
-8
If num & deno both are negative then it will work normal.
>>> a=-25
>>> b=-4
>>> a//b
6
Amit Kumar Pandey, PGT-CS, K V Aliganj
vi. Modulus: It produces the remainder of division
For example,
19%6=1
7.2%3=1.2
6%2.5=1.0

Modulus for negative number in Python is calculated according


to following rules:
(a//b)*b+(a%b)=a
>>> a=-24
For example: >>> b=7
>>>a=-16 >>> print(a % b)
>>>b=3 4
>>>print(a%b)
2
Amit Kumar Pandey, PGT-CS, K V Aliganj
a=-16
b=3
(a//b)*b+(a%b)=a
(-16//3)*3+(a%b)=-16
(-6)*3+(a%b)=-16
(a%b)=-16+18
(a%b)=2

Amit Kumar Pandey, PGT-CS, K V Aliganj


vii. Exponentiation: The exponentiation
operator performs exponentiation(power)
calculations.
For example,
4**3 evaluates to 64
>>>x=49.0
>>>print(x**0.5)
7.0

Amit Kumar Pandey, PGT-CS, K V Aliganj


Example
Enter total no. of days and convert it into months and days.
days =int(input ("Enter days: "))
months = days//30
days = days % 30
print(months,"Months",days,"Days")
---------------------------------------------------
total=int(input("Enter Total Number of Days"))
months=total//30
days=total%30
weeks=days//7
days=days%7
print("Months=",months,"weeks=",weeks,"Days=",days)
Amit Kumar Pandey, PGT-CS, K V Aliganj
Write a program to enter basic salary of an
employee and print total salary if DA is
38% of Basic salary and HRA is 16% of Basic
Salary.

Basic=int(input("Enter the Basic Salary:"))


DA = (Basic*38)/100
HRA=(Basic*16)/100
Gross=Basic+DA+HRA
print('Total salary is :-',Gross)

Amit Kumar Pandey, PGT-CS, K V Aliganj


2. Relational Operators
• The relational operators determine the
relation among different operand. If the
comparison is true the expression results in
true else results in false.
• Following are the seven relational operators
< less than, <= less than or equal to, == equal to
> Greater than, >= greater than or equal to,
!= not equal to
Amit Kumar Pandey, PGT-CS, K V Aliganj
For example,
>>>x=5
>>>y=10
>>>print(x>y)
False
>>>print(x<y)
True
z=x>y
>>>print(z)
False

Amit Kumar Pandey, PGT-CS, K V Aliganj


Relational operators with Arithmetic operators
“The relational operators have a lower
precedence than the arithmetic operators.”
That means the expression
x+8>y-2 Corresponds to (x+8)>(y-2)

Amit Kumar Pandey, PGT-CS, K V Aliganj


3.Logical Operators
Python provides three logical operators to combine existing
expressions. These are OR, AND, NOT.
The three logical operators works on their corresponding truth
values.

Amit Kumar Pandey, PGT-CS, K V Aliganj


For example,
• (3==3) or (5==8) result into True
• 15>8 or 5<22 result into True
• 4>3 and 7>1 result in True
• not 5 result into False
• Not (5>7) result into True

Some important points :


(i) When or operator has its operands as numbers or strings or
list then or operator works on following principle
“In an expression x or y, if first operand has false, then return
second operand y as result, otherwise return x.”

>>>x=‘hello’
>>>y=‘hello’
>>>z=x or y
>>> print(z)
hello Amit Kumar Pandey, PGT-CS, K V Aliganj
(ii) The or operator will test the second operand only if the first
operand is false, otherwise ignore it; even if the second
operand is logically wrong.
For example,
20>10 or “a”+1>1 result in True

Amit Kumar Pandey, PGT-CS, K V Aliganj


Operator Precedence
Operator Description Highest

() Parenthesis
** Exponentiation
+,-(Unary) Positive, negative
*,/,//,% Mul, Div, Floor Div, Mod
+,- Addition, Subtraction
<,<=,>,>=,<>,!=, Relational
==
not Boolean NOT
and Boolean AND
Lowest
or Boolean
Amit OR K V Aliganj
Kumar Pandey, PGT-CS,
EXPRESSIONS
• An expression in Python is any valid
combination of operators and atoms.
• An expression is composed of one or more
operations.
“Atom”is something that has a value. Identifiers,
literals, strings etc. are all atoms. Atoms are
the most basic elements of expressions. The
simplest atoms are identifiers or literals.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Types of expressions
1.Arithmetic Expressions: These involves operands and
arithmetic operators.
Example: x/y, a*b, 7j-(-3+2.1j)
2. Relational Expressions: An expression consists of
variable of any data type and relational operators.
Example: x>y, y==z, a==b<>c
3. Logical Expressions: An expression consists of
variable of any data type and relational operators.
Example: x and y, a or b, not z or not y

Amit Kumar Pandey, PGT-CS, K V Aliganj


4. String expression: Python also provides two string operators +
and *.
+ concatenation operator
>>> a= "and"
>>> b="this"
>>> c=a+b
>>> print(c)
andthis
-------------------------------------------------------------------------------------
* Replication operator

>>> x=“AKP"
>>> y=x*2
>>> print(y)
AKPAKP

Amit Kumar Pandey, PGT-CS, K V Aliganj


Calculation with complex numbers
>>> a=5+2j
>>> b=3-4j
>>> c=a-b
>>> print(c)
(2+6j)
>>>

Amit Kumar Pandey, PGT-CS, K V Aliganj


Evaluating mixed Arithmetic
Expressions
When a description of an arithmetic operator below
uses the phrase “the numeric arguments are
converted to a common type,” this means that the
operator implementation for built-in types works as
follows:
• If either argument is a complex number, the other is
converted to complex;
• otherwise, if either argument is a floating point
number, the other is converted to floating point;
• otherwise, both must be integers and no conversion
is necessary.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Type Conversion:
The process of converting the value of one data
type (integer, string, float, etc.) to another
data type is called type conversion. Python
has two types of type conversion.
• Implicit Type Conversion
• Explicit Type Conversion

Amit Kumar Pandey, PGT-CS, K V Aliganj


Implicit Type Conversion:
• In Implicit type conversion, Python
automatically converts one data type to
another data type. This process doesn't need
any user involvement.
• Let's see an example where Python promotes
conversion of lower datatype (integer) to
higher data type (float) to avoid data loss.

Amit Kumar Pandey, PGT-CS, K V Aliganj


num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>

Amit Kumar Pandey, PGT-CS, K V Aliganj


Explicit Type Conversion:
• In Explicit Type Conversion, users convert the
data type of an object to required data type.
We use the predefined functions
like int(), float(), str(), etc to perform explicit
type conversion.
• This type conversion is also called typecasting
because the user casts (change) the data type
of the objects.
• Syntax : (required_datatype)(expression)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Example 3: Addition of string and integer using
explicit conversion
a= <class 'int'>
a = 123 str= <class 'str'>
str after Type Casting: <class 'int'>
str = "456" Sum of str & a: 579
Data type of the sum: <class 'int'>
print("a=",type(a))
print("str=",type(str))
str = int(str)
print("str after Type Casting:",type(str))
sum = a+str
print("Sum of str & a:",sum)
print("Data type of the sum:",type(sum))
Amit Kumar Pandey, PGT-CS, K V Aliganj
Key Points to Remember:
• Type Conversion is the conversion of object from
one data type to another data type.
• Implicit Type Conversion is automatically
performed by the Python interpreter.
• Python avoids the loss of data in Implicit Type
Conversion.
• Explicit Type Conversion is also called Type Casting,
the data types of object are converted using
predefined function by user.
• In Type Casting loss of data may occur as we
enforce the object to specific data type.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Other features
Multiple variable initialization
>>>a,b=1,2
>>>print(a,b)
12
>>>a,b=a+1,a+2
>>>print(a,b)
23

Amit Kumar Pandey, PGT-CS, K V Aliganj


>>>x,y=5,10
>>>a,b=x,y
>>>print(a,b)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Conditional Constructs
Statements: Statements are the instructions
given to the computer to perform any kind
of action. Python statements can belong to
one of following three types:
1. Empty statements
2. Simple/Single statements
3. Compound statements

Amit Kumar Pandey, PGT-CS, K V Aliganj


1. Empty statements: A statement which does nothing.
In python empty statement is pass.
Whenever Python encounters a pass statement, Python
does nothing and moves to next statement in the
flow of control

Example:
a=int(input("Enter the number"))
if a>=10 :
pass
else :
print("single digit number")

Amit Kumar Pandey, PGT-CS, K V Aliganj


2. Simple Statement: Any single executable statement
in Python.
Example:
a=input("Enter Your Name")
print("Hello",a)

3. Compound Statement: A group of statements


executes as a unit.
Syntax:
<compound statement header> :
<indented body containing multiple simple and/or
compound statements>

Amit Kumar Pandey, PGT-CS, K V Aliganj


A compound statement has:
1. A header line which begin with key word
and ends with colon.
2. Body consist of one or more python
statement.
Example
num=int(input("Enter a single digit number"))
if num<10 : # header line
print(“……How obedient") #body

Amit Kumar Pandey, PGT-CS, K V Aliganj


Selection Construct
• In order to write useful programs, we almost
always need the ability to check conditions
and change the behaviour of the program
accordingly. Selection statements, sometimes
also referred to as conditional statements,
give us this ability.
• The simplest form of selection is the if
statement. This is sometimes referred to
as binary selection since there are two
possible paths of execution.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Selection: if statement
Syntax:
if condition:
if_body
--------------------
if age < 18:
print("Cannot vote")

Amit Kumar Pandey, PGT-CS, K V Aliganj


• In the previous example there has only been
one statement appearing in the if body. Of
course it is possible to have more than one
statement there;
for example:
if choice == 1:
count += 1
print("Thank you for using this program.")
print("Always print this.") # this is outside the if

Note: Always leave four blank space to


include statement with if/else condition.
Amit Kumar Pandey, PGT-CS, K V Aliganj
The else clause

An optional part of an if statement is


the else clause. It allows us to specify an
alternative instruction (or set of instructions)
to be executed if the condition is not met
if condition:
<if_body >
else:
<else_body >
Amit Kumar Pandey, PGT-CS, K V Aliganj
if x == 0:
x += 1
else:
x -= 1
----------------------------
num=int(print(“Enter number”))
if num%2==0 :
print(“Even number”)
else :
print(“Odd number”)
Amit Kumar Pandey, PGT-CS, K V Aliganj
Amit Kumar Pandey, PGT-CS, K V Aliganj
Nested if statements

• In some cases you may want one decision to


depend on the result of an earlier decision.
• For example, you might only have to choose
which shop to visit if you decide that you are
going to do your shopping, or what to have for
dinner after you have made a decision that
you are hungry enough for dinner.

Amit Kumar Pandey, PGT-CS, K V Aliganj


clas=int(input("Enter Class"))
stream=input("Enter Stream")
if clas==11:
if stream=="science":
print("Welcome to science")
print("Welcome to Vidyalaya")

Amit Kumar Pandey, PGT-CS, K V Aliganj


Amit Kumar Pandey, PGT-CS, K V Aliganj
Amit Kumar Pandey, PGT-CS, K V Aliganj
Nesting of if-else
#Program to find the largest between three numbers.

x=int(input("Enter first number"))


y=int(input("Enter second number"))
z=int(input("Enter Third number"))
if x>y:
if x>z:
print(x)
else:
print(z)
else:
if y>z:
print(y)
else:
print(z)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Using elif
x=int(input("Enter first number"))
y=int(input("Enter second number"))
z=int(input("Enter Third number"))
if x>y:
if x>z:
print(x)
else:
print(z)
elif y>z:
print(y)
else:
print(z)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Amit Kumar Pandey, PGT-CS, K V Aliganj
Amit Kumar Pandey, PGT-CS, K V Aliganj
Amit Kumar Pandey, PGT-CS, K V Aliganj
Assignment
1.Write a program to enter a number and check whether it is
even or odd.
2. Write a program to enter a number and check whether it is
positive, negative or zero.
3. Write a program to enter two numbers and print largest
between them.
4. Write a program to enter three numbers and print largest
between them.
5. Write a program to enter a character and check whether it is
vowel or not.
6. Write a program to enter marks of three subjects and print
percentage and grades(>=75-A, <75 >=60-B, <60-C)
7. Enter a number and check whether it is buzz number or not?(a
number is buzz if it ends withPandey,
Amit Kumar 7 or divisible
PGT-CS, K V Aliganj by 7)
9. Write a program to enter total run scored and
print whether it is century/half century/none.
10.Write a program that reads two numbers and
an arithmetic operator and displays the
computed result.
11.Write a program to enter three numbers and
arrange them in ascending order.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Error

Amit Kumar Pandey, PGT-CS, K V Aliganj


Amit Kumar Pandey, PGT-CS, K V Aliganj
Amit Kumar Pandey, PGT-CS, K V Aliganj
Amit Kumar Pandey, PGT-CS, K V Aliganj
Amit Kumar Pandey, PGT-CS, K V Aliganj
Amit Kumar Pandey, PGT-CS, K V Aliganj
Looping in Python

Amit Kumar Pandey, PGT-CS, K V Aliganj


Program Logic Development Tools

Algorithm: It is a step-by-step procedure to solve a given problem.


Flowchart: It is a graphical representation of steps to solve a given
problem.
Flowchart: It is a graphical representation of flow of control of program.
Pseudocode: It is an informal way of describing the steps of a program’s
solution without using any strict programming language syntax.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Algorithm

• Example: algorithm to multiply 2 numbers and print the result:

• Step 1: Start
• Step 2: Get the knowledge of input. Here we need 3 variables; a and b will be the user
input and c will hold the result.
• Step 3: Declare a, b, c variables.
• Step 4: Take input for a and b variable from the user.
• Step 5: Know the problem and find the solution using operators, data structures and logic

• We need to multiply a and b variables so we use * operator and assign the result to c.
• That is c <- a * b

• Step 6: Check how to give output, Here we need to print the output. So write print c
• Step 7: End

Amit Kumar Pandey, PGT-CS, K V Aliganj


Pseudocode

Example
A. start
B. Input number(n) to print table
C. Let count=1
D. Display n * I
E. Add 1 to count
F. if count==10:
A. Stop
G. else:
A. Repeat from Step C
H. Stop

Amit Kumar Pandey, PGT-CS, K V Aliganj


Looping
Looping is also called a
repetition structure. Python
allows a procedure or block of
statements to be repeated as
many times as long as the
processor could support.
Loop causes a section of your
program to be repeated a
certain number of times.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Flow Chart

Amit Kumar Pandey, PGT-CS, K V Aliganj


Types of Looping Statements

Python provides two kinds of loops:


1- Counting Loop: The loops that repeat a certain number of times.
for loop.
2- Conditional loop: The loop that repeat until a certain condition is
true. While loop

Every loop consists of initialization, testing and


incrementation / decrementation.

Amit Kumar Pandey, PGT-CS, K V Aliganj


1- while loop
2- for loop
3- nested loop

while expression/condition:
program statement(s)
increment/decrement
else: #optional
program statement(s)

Amit Kumar Pandey, PGT-CS, K V Aliganj


a=10
while a!=0 :
print(a)
a=a-1
# it will print 10 to 1
----------------------------------
n=10
i=1
while i<n :
print("*"*i)
i=i+1
Predict output?

Amit Kumar Pandey, PGT-CS, K V Aliganj


else statement with while

a=5
while a<10:
print(a ,”is less than”,10)
a=a+1
else:
print(a ,”is not less than”,10)

Amit Kumar Pandey, PGT-CS, K V Aliganj


for loop

1- Using <in>
2- Using <range>

Amit Kumar Pandey, PGT-CS, K V Aliganj


Python “in” operator
Basically, the in operator in Python checks whether a specified value is
a constituent element of a sequence like string, array, list, or tuple etc.
When used in a condition, the statement returns a Boolean result
evaluating into either True or False. When the specified value is found
inside the sequence, the statement returns True. Whereas when it is
not found, we get a False.
>>>5 in [1,2,3,4,5] True
>>> 5 in [1,2,3,4] False
>>>‟p‟ in “apple” True
>>>‟national in “international” True
--------------------------------------
ch=input('Enter a character')
if ch in('a','e','i','o','u'):
print('VOWEL')
else:
print('CONSONENT')
Amit Kumar Pandey, PGT-CS, K V Aliganj
Program to check whether any word is a part of sentence or not

line = input("Enter any statement")


word = input("Enter any word")
if word in line:
print("Yes ", word, "is a part of ",line)
else:
print("No", word ," is not part of ",line)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Python “not in” operator

The not in operator in Python works exactly the opposite way as the in
operator works. It also checks the presence of a specified value inside
a given sequence but it’s return values are totally opposite to that of
the in operator.

When used in a condition with the specified value present inside the
sequence, the statement returns False. Whereas when it is not, we get
a True.

Amit Kumar Pandey, PGT-CS, K V Aliganj


for loop
for loop in python is used to create a loop to process items of any sequence
like List, Tuple, Dictionary, String using in operator .
It can also be used to create loop of fixed number of steps like 5 times, 10
times, n times etc using range() function.

for iterating_var in sequence :


statements
else:
statements
Example: Printing sequence values
for name in "ABCD":
print(name)
--------------------------
Example: Printing list values
a=[0,1,2,3,4,5]
for i in a:
print(i)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Amit Kumar Pandey, PGT-CS, K V Aliganj
for loop
1- To print the table of any number.

n=int(input(“Enter the number”))


for a in(1,2,3,4,5,6,7,8,9,10):
print(n*a)

1- To print the square of numbers in a list.

for a in[1,2,3,4,5]:
print(a*a)

Amit Kumar Pandey, PGT-CS, K V Aliganj


• Let us understand how for loop works for
List/String/Tuple
• For loop starts, it will pick values one by one from
Tup and assign it to x.

Tup=(22,33,44,55,66)
for x in Tup:
print(x)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Using range() function
• A sequence of numbers can be generated using range() function.
• It remembers start, stop, step size and generates the next number
on the go . It is mostly used in for loop.
• The arguments must be plain integers.
range([start,] stop[, step])
Here,
• Start/initial value and step are optional
• Default value of start is 0.
• Stop is the last number of range where the range will end.
• Step is the increment.

If step is positive then value will be printed up to stop-1


If step is negative then value will be printed up to stop+1

Amit Kumar Pandey, PGT-CS, K V Aliganj


Example:
for i in range(10):
print(i)
(Default value of start is 0 and
step is +1)
----------------------------
x=5
for i in range(10):
print(i*5)
-----------------------
for i in range(10,2,-2):
print(i)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Command Output Loop Description
for i in range(5,10): 56789 5 is the start, 9 is the stop
print(i) and step is default 1

for i in range(0,10,3): 0369 0 is start, 9 is stop and


print(i) step is 3

for i in range(-10,-100,-30): -10 -40 -70 -10 is start, -100 is stop


print(i) and step is -30

for i in range(15, -1,-2): 15 13 11 9 7 5 3 1 15 is start, -1 is stop and


print(i) step is -2

for i in range(11,3,-1): 11 10 9 8 7 6 5 4 11 is start, 3 is stop and


print(i) step is -1

Amit Kumar Pandey, PGT-CS, K V Aliganj


#To enter a number and print its table
n=int(input("Enter Number"))
for i in range(1,11,1):
print(i*n)

#To enter a number and print its table in reverse order.


n=int(input("Enter Number"))
for i in range(10,0,-1):
print(i*n)

Amit Kumar Pandey, PGT-CS, K V Aliganj


else with for loop

for i in range(10,15):
print(i)
else:
print(“End”)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Let‟s look at the equivalence of the two
looping construct:

While For
i= initial value for i in range (initial value, limit, step):
while ( i <limit): statement(s)
statement(s)

i+=step

Amit Kumar Pandey, PGT-CS, K V Aliganj


Nested Loop

• Python allows to use one loop inside another loop.


• Both for and while can be nested.
Syntax:
for iterating_var in sequence: Outer Loop
statement(s)
for iterating_var in sequence: Inner Loop
statement(s)

Amit Kumar Pandey, PGT-CS, K V Aliganj


Break and Continue in Loops
break statement
When a break statement executes inside a loop, control
flow "breaks" out of the loop immediately:
i=0
while i < 7:
print(i)
if i == 4:
print("Breaking from loop")
break
i += 1
The loop condition will not be evaluated after the break
statement is executed. Note that break statements are
only allowed inside loops, syntactically.

Amit Kumar Pandey, PGT-CS, K V Aliganj


break statements can also be used inside for loops, the
other looping construct provided by Python:
for i in (0, 1, 2, 3, 4):
print(i)
if i == 2:
break
Executing this loop now prints:
0
1
2
Note that 3 and 4 are not printed since the loop has
ended.

Amit Kumar Pandey, PGT-CS, K V Aliganj


continue statement
A continue statement will skip to the next iteration of the loop
bypassing the rest of the current block but
continuing the loop. As with break, continue can only appear inside
loops:
for i in (0, 1, 2, 3, 4, 5):
if i == 2 or i == 4:
continue
print(i)
0
1
3
5
Note that 2 and 4 aren't printed, this is because continue goes to the
next iteration instead of continuing on to print(i) when i == 2 or i == 4.

Amit Kumar Pandey, PGT-CS, K V Aliganj


Assignment
• Write a program to enter a number and print its table
• Write a program to enter a number and print the sum of each digit of the
number.
• Write a program to print all the odd numbers up to a limit entered by user.
• Write a program to enter a number and print the reverse if it.
• Write a program to enter a number and print its Factorial.
• Program to find the sum of all number divisible by 7 between 1 to 100
• Write program to enter a number and Print whether it is Prime No. or not.
• Write a program to enter a number and print whether it is Armstrong Number
or not.
• Write a program to enter a number and check whether it is Palindrome
Number or not.
• Write a program to enter a number and check whether it is Perfect Number or
not.
• Write a program to enter x, n and print xn .
• Write a program to generate Fibonacci Series

Amit Kumar Pandey, PGT-CS, K V Aliganj


Nesting of Loop
Python programming language allows to use one loop inside another
loop. Following section shows few examples to illustrate the concept.
Using for loop-
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming
language is as follows −
while expression:
while expression:
statement(s)
statement(s)

Amit Kumar Pandey, PGT-CS, K V Aliganj


• The following program uses a nested for loop to find the prime numbers
from 2 to 100 −
i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " is prime"
i = i + 1

print "Good bye!"

Amit Kumar Pandey, PGT-CS, K V Aliganj


To print the triangle of numbers

n=int(input("enter the value of n::"))


for i in range(1,n,1):
for j in range(1,i+1,1):
print("",j,end="")
print('\n')
Output: if the value of n entered by user is 6-
1

12

123

1234

12345

Amit Kumar Pandey, PGT-CS, K V Aliganj


To print the triangle of numbers

n=int(input("enter the value of n::"))


for i in range(1,n,1):
for k in range(1,n-i,1):
print(" ",end="")
for j in range(1,i+1,1):
print(“ ",j,end="")
print('\n')
Output:
1

12

123

1234

Amit Kumar Pandey, PGT-CS, K V Aliganj


To print brick of Numbers
n=int(input("enter the value of n::"))
for i in range(1,n+1,1): 1
for k in range(1,n+1-i,1):
print(" ",end=" ") 1 2
for j in range(1,i+1,1):
print(" ",j,end=" ") 1 2 3
print('\n')
1 2 3 4
for i in range(n-1,0,-1):
1 2 3
for k in range(1,n+1-i,1):
print(" ",end=" ") 1 2
for j in range(1,i+1,1):
print(" ",j,end=" ") 1
print('\n')

Amit Kumar Pandey, PGT-CS, K V Aliganj


To print the triangle of alphabets
n=int(input("enter the value of n::"))
for i in range(1,n,1):
ch='A'
for j in range(1,i+1,1):
print("",ch,end="")
ch=chr(ord(ch) + 1) #type casting of character into ASCII
print('\n')
Output:
A

AB

ABC

ABCD

Amit Kumar Pandey, PGT-CS, K V Aliganj


What will be the output?
i=6
while i >= 0:
for j in range (1, i):
print (j,end="")
print('\n')
i=i-1

Amit Kumar Pandey, PGT-CS, K V Aliganj

You might also like