Class 6 Phython Chapter For Revision
Class 6 Phython Chapter For Revision
INTRODUCTION TO
PYTHON
LEARNING OUTCOMES
By the end of the lesson, the learner will be able to:
o differentiate between low-level and high-level languages O list the basic features of Python O download
and install Python O work with Python O discuss various programming elements of Python including
tokens, data types, variables and assignments O use input and output functions in a program O explain the
use of comments in a program o develop simple programs in Python
Step 1: Start
Step 2: Input a number and store in in Num
Step 3: If Num is divisible by 2, display Num is even
Step 4: If Num is not divisible by 2, display Num
is odd
Step 5: Stop
Algorithms and flowcharts are the initial steps in developing a program. Awell-written algorithm
or flowchart helps in clear understanding the steps involved in solving a problem and subsequently,
results the development of good programs. A program is a well-defined set of instructions that
directs the computer to do a particular task. It instructs the computer what to do and how to do
it. Aprogram is written in a specific language which we call programming language. Python is
also a programming language that you will learn in this chapter. But before that let us learn about
programming languages in detail.
(66
PROGRAMMING LANGUAGES
A programming language (or computer language) is used to write programs for the computer.
Programming languages are broadly classified into two categories: low-level languages and
high-level languages.
Low-Level Languages (LLLs): Low-level languages are nmachine-dependent languages. Programs
written for one machine might not work on other machines. LLLs are of two types: machine
language and asembly language.
Machine language:This is the only language directly understood by computers. Each machine
language instruction is made up of a series of Os and ls called binary digits. Since a computer
understands only binary language, it can execute a program written in machine language
directly without any translation. This makes the program run faster. However, it is difficult to
write programs in machine language.
Assembly language: This language uses symbolic codes instead of binary digits. These symbolic
codes are made by the combination of the letters of English alphabet and are called mnemonics.
Each mnemonic is a predefined name of some operation that tells the computer what to do.
Aprogram written in assembly language Machine language is a first-generation
needs to be translated into machine code
QUICK language, and assembly languages are
by a program called assembler before the FACT second-generation langugaes, developed
computer executes it. in the 1950s.
High-Level Languages (HLLs): High-level languages are third-generation languages that use
letters, words and mathematical symbols. It is quite easier to write and understand a program
written in a high-level language. However, a high-level language program cannot run directly
on the computer. first must be translated into machine language using a language translator
program such as compiler or interpreter. This slows down the processing speed. High-level
language programs are machine-independent. That is, programs written on one machine can
run on different machines without any change. Some examples of HLLs are BASIC, COBOL,
FORTRAN, PASCAL, C, C++, VC++ and Python.
WHAT IS PYTHON?
What Can Python Do?: Besides the features mentioned above, Python has many more uses, which
are as follows.
It can be used for developing desktop-based applications, games, Web applications, etc.
It is great as a server-side scripting language.
It can be used as an alternative to PHP, ASP.NET and Ruby.
It is ideal for complex mathematical and scientific programming as it has a number of libraries
for matrices, algebra, calculus, etc.
" It provides connectivity with all major database systems.
DOWNLOADING AND INSTALLING ython P
PYTHON
Python
Python is available for all major operating About Downioats Documentatio Communty Success Stores Now ents
systems such as Windows, Linux, Mac OS, Download the latest version for Windows
etc. A number of versions of Python have ay
Louking lory wiafletOS ython lur dows, LinsUNI
been released till yet. You can download the Want teg tsi d e d yha? Peas, Duckf nags
Starting Python in Command Line Mode: In Python programming from command line mode,
you can type the code directly into the Python interpreter at the prompt (>>>). The
Python
interpreter immediately returns the output for each command that you
enter. To open Python in command line mode, follow these steps. Onee
up in the command line mode with a cursor blinking at the prompt Phcton
Ptcr
Python 2.10
SageThumb
starting Python in
command line mode
Python in command line mode
Starting Python (IDLE): IDLE (stands for Integrated Development Environment or Integrated
Development and Learning Environment) is the standard and the most popular Python
development environment. It provides graphical user interface to work with Python. It has a
Python Shell window where you can write and run Python programs.
(69
Once Python IDLE has been installed, you can start it by following these NOncte or Windus10
steps.
1. Click the Start button ( #) and scroll down to the letter P in the list of A tt 30o
programs. h n e Lin
hotn
2. Click Python 3.10 in the list of available programs and then click IDLE e
(Python 3.10 64-bit). The Python Shell window opens up with a cursor ython 31e
y nL 4
o pe here to search
Python Shell window
starting Python
You can use Python IDLE in two different ways: in IDLE mode
at the prompt (>>>) in the Python File Edit Shell Debug Options Window Help
Python 3.10.6 (tags/v3.10.61 9c7bibd, Aug 1 2022, 2lt53:49) [MSC v.1932
84 bit (AND64) ) on Wn
Shell window. As you type any "credits" or "l1cense () " or more intornation.
*etle Nosld!")
line and press Enter, the Python Hello World!
>>>
figure beside. This is referred to as
interactive mode of IDLE.
Python, in interactive mode, is good enough
You can create a new file, write Python
to learn, experiment or explore, but its
program (script) in it and then use the QUICK only drawback is that we cannot save the
interpreter to run the script and obtain NOTE statements for further use and we have to
retype all the statements to re-run them.
the output. This is referred to as the
script mode of IDLE.
Creating a Simple Program: IDLE Shell 3.10.6
File Edit Shell Debug Options
To create a simple program in the Ctri+N
2. Type the code for your program creating a new file Python Edit window
in the window.
(70
Observe that the #" symbol in A"untitled
the program code shown in the
Eile Edit Format Run Options Window Help
figure indicates that the first line #My first program in Python
is a comment. Print("Hello World!
A Hide Felders
Cance
Debug ptions
hYehon 3.10.4 (tanslu
win2eTbbd, Aun
ustomed ShifteEs 4 2022,
Be (aDE4) n 2415314) HSC v.1632 44
Python Shel
AR-X
EEane" eredit or 1kcens () toE BOre Anfernatson
Hello Worlat
D A t t r e ceveen 7 and 2 s", -2)
> and 2 is
STARTI
Progran
Hello Mortd Ci/Users/Lenovo/AppData/Local/Ograna/ Python/Python
Output of the
310 /HtyfArst
program
QUICKCHECK CRITICAL THINKING
Tick () the correct statements and cross (×) the other ones.
a. Machine language makes use of mnemonics.
O0000
b. Python can run on different operating systems such as Windows, Mac, Linux, etc.
c. Python is an interpreted language.
d. Python programs cannot be merged with the code written in some other language.
e. Python can be used in either command line mode or IDLE mode.
TOKENS
A token is the smallest individual unit of aprogram. It is defined as a set of characters that logically
belong together. Python tokens include keywords, identifiers, literals, operators and punctuators.
Keywords: Keywords are the predefined words that have special significance in any language.
Every keyword is reserved for aspecific purpose and hence, cannot be used as user-defined names
(identifiers). Apartial list of keywords in the Python programming language is given in the
following table.
False and del from not
None while as elif global
True Or with assert else
For if pass yield break
lambda except import print class
Try exec in raise Continue
finally is return def
Identifiers: Identifiers are names given by a programmer to different parts of a program such as
variables, functions, lists, objects, dictionaries, etc, in order to identify them uniquely. They are
the basic building blocks of a program.
While defining identifiers in Python, programmers must follow the rules given below.
The name of an identifier must be unique in a program.
It must contain only uppercase and lowercase letters, underscore () and digits 0 to 9.
It must start with a letter or an underscore followed by zero or more letters, underscores and
digits 0to 9. No blank spaces are allowed in the name of an identifier.
Python is acase-sensitive language. This means an identifier in uppercase is different from that
in lowercase. For example, nUM, num, Num, and NUM are considered four different identifiers.
You cannot use a keyword as the name of an identifier.
Python does not allow the use of punctuation characters such as $, @, and %in the name of
identifiers.
72
Some valid identifiers are listed here: Numvar NEWVAR chk Pvar P varl23 DISK
The following are some invalid identifiers.
982ds invalid; as it starts with a digit
Num@Var invalid; as it contains the special character @
lambda invalid; as it is a keyword
Literals: Literals, also known as constants, are the identifiers whose values do not change during
program execution. That is, literals have a fixed value. Based on the type of value, Python literals
are classified into the following.
a. String literals b. Numeric literals c. Boolean literals d. Special literal (None)
String Literals: String literals are an ordered sequence of any number of characters enclosed in either
single () or double quotes ( "). For example, 'g, 'K,7, "India", "Rahul and "date" are some valid
string literals. Here it is important to note that the quotes are not part of the string. They only tell the
computer where the string literal begins and ends.
You can also use certain non-graphic characters (which cannot be typed from the keyboard)
such as tab space, new line, carriage return, etc. within the string values. These characters can be
represented by using escape sequences. An escape sequence is nothing but aspecial character that
has a specific function. It is represented by a backslash () followed by one or more characters.
The table alongside lists some of the
escape sequences in Python. Escape sequence Non-graphic character printed by
\n New line character
Python allows you to use two types of t Horizontal Tab (TAB)
strings in your program: single line
\r Carriage Return
and multiline strings. The strings that
terminate in single line can be created
lb ASCII Backspace
in the same way as discussed earlier Backslash ()
(by enclosing in single or double Single quote ()
quotes). In contrast, there are two Double quotes (")
different ways to create strings that If ASCIIFormfeed (FF)
spread across multiple lines (multiline ASCII Vertical Tab (vT)
strings). These ways are as follows.
By addinga backslash () at the end of continuingline. For example,
Strvar = "Welcome \
Back!"
Back!
73
also
The only difference between the above two methods is that a triple quoted multiline string
the multiline
counts the end-of-line (EOL) character (which is ) in the size of string, while
strings with backslash method does not count backslash (\) in the size of string.
Numeric Literals: Numeric literals refer to the numbers consisting of a sequence of digits (with or
literals
without decimal point) that can be either positive or negative. However, by default, numeric
are positive.
In Python, there are four types of numeric literals, as given below.
int: The numeric literals of int type are the signed integers-the positive or negative whole
numbers with no decimal point.
long: The numeric literals of long type are alsosigned integers but with unlimited size. They
are written like integers and followed by letterL (in uppercase or lowercase).
float :The numeric literals of float type are the real numbers, that is, the numbers with a
decimal point that separates the integer and fractional part.
complex: The numeric literals of complex type are the complex numbers of the form a+jb,
where a is the real part of the number and b is the imaginary part.
The integer numeric literals (of type int and long) can be represented by three different number
QUICK systems, namely, decimal (base 10), octal (base 8) and hexadecimal numbers (base 16). The octal
FACT constants are preceded by a 0 (zero) and contain only 0 to 7 digits, while the hexadecimal constants
are preceded by a Ox and contain only 0 to 9 digits and Ato For a to f letters.
Boolean Literals: ABoolean literal is used to represent one of the two Boolean values: True or
False. That is, the value of a Boolean literal can be either True or False.
Special Literal (None): Python provides aspecial literal None which is used to indicate something
that has yet not been created. In other words, it is used to signify the absence of value in asituation.
Operators: Operators are the symbols that define the type of operation (such as addition, subtraction,
and so on) to be performed on the data items used in a program. The data items on which operators
act are known as operands. Based on the number of operands required to work upon, operators are
classified into unary and binary operators.
Unary operators are the operators that need only one operand to act upon. Some of the
unary operators in Python are unary plus (+), unary minus () and logical negation (not).
Binary operators are the operators that need two operands to act upon. The following table
lists some binary operators in Python.
Arithmetic + (addition), - (subtraction), * (multiplication), / (division), **
operators (exponent), % (remainder/modulus), // (loor division)
Relational operators < (less than), > (greater than), <= (less than or equal to), >= (greater
than or equal to), == (equal to), != or <> (not equal to)
(74
Logical operators and (logical AND), or (logical OR)
Bitwise operators &(bitwise AND), | (bitwise OR), ^ (bitwise exclusive OR)
Assignment = (assignment), t= (assign sum), (assign difference), *= (assign
operators product), /= (assign quotient), %= (assign remainder), **= (assign
exponent), //= (assign floor division)
Shift operators << (shift left), >> (shift right)
Identity operators is (is the identity same?), is not (is the identity not same?)
Membership in (whether variable in sequence), not in (whether variable not in
operators sequence)
DATA TYPES
Adata type defines the type of data and the operations that can be performed on it. The figure
shows the various data types available in Python.
Data Types
Boolean
None: This is special data type with single value. It is used to signify the absence of value/false ina
situation. It is represented by None.
Sequences: A sequence is an ordered collection of items, indexed by positive integers. Three types
of sequence data type available in Python are strings, lists and tuples.
Strings: A string is an ordered sequence of letters or characters. In Python, strings are
represented by enclosing them in either single quotes or double quotes, for example, 'a'.
'abc', 'Kevin', "ritu 123", "Her's", etc. There can be a string with no characters in
it, such as . Such a string is known as a blank string.
Lists: A list in Python is a list of values of any data type enclosed within square brackets O
and separated by commas. The individual values in the list are called elements or items and are
indexed. Lists are mutable which means individual elements of a list can be modified.
Examples: [1, 2, 3, 4, 5] ['h' 'e', '1', 1', 'o'] . (89, 75.3, "Saachi"1
Tuples: A tuple, similar to a list, also represents a list of comma-separated values of any data
type. The difference is that the values are enclosed within parentheses () in place of square
brackets. In addition, tuples are immutable which means we cannot change the individual
elements of a tuple once it is assigned whereas in a list, the elements can be changed.
Examples: (1, 2, 3, 4, 5) ('h', 'e', l', 1', 'o') . (89, 75.3, 'Saachi')
76)
QUICK
NOTE
Aset can have any number of items and they may be of different types (integer, real, tuple,
string etc.). But a set cannot have a mutable element, like list, set or dictionary, as its element.
Sets: A set is an unordered collection of items. Every element must be unique (no duplicates) and
must be immutable (which cannot be changed). However, the set itself is mutable. We can add or
remove items from it. A set is created by placing all the items (elements) inside curly braces {},
separated by comma.
Examples: . (1, 2, 3) . (1.0, "Hello", (1, 2, 3) } . {"apple", "banana", "cherry"}
Mappings: A mapping data type is unordered and mutable. Dictionaries fall under nmappings.
Dictionary: A dictionary is an unordered collection of items enclosed within curly braces {} and
separated by comma. Each item in a dictionary is expressed as a key: value pair. While values
can be of any data type and can repeat, keys must be of immutable type (string, number or tuple
with immutable elements) and must be unique. The values in a dictionary can be accessed with
the help of the key.
Examples: (1:'a' ,2: 'b',3: 'e') . 1: 'apple', 2: 'ball'}
.{'name': 'John', l: [2, 4, 3]}
A variable is a name that represents a memory location which stores a value of a specific data type.
The data stored at a particular location can be accessed using the variable name. The name given to
a variable is known as identifier. The value of a variable can be used and changed anytime during the
program execution.
Defining Variables: In Python, it is not required to declare variables before using them in the
program. The Python interpreter automatically detects the type of the variable by the data it
contains. You can create a variable by just assigning to it some value of a particular data type such
as a numeric value, a string, etc. You can assign value to a variable using the assignment operator
(-). For example, consider the following statement.
num = 75
Here, num is a variable and an integer value 75 is assigned to it. Now, consider these statements.
pi = 3.14
Name="Sanaya'
In the first statement, pi is a variable that has been
QUICK The rules for naming variables
assigned a floating-point value 3.14, while in the NOTE are same as those of identifiers.
second statement, Name is a string variable that has
text Sanaya stored in it.
77
Multiple Assignment: Python lets you assign a single value to multiple variables at the same time.
You can even assign different values to multiple variables simultaneously.
Python lets you assign a single value to multiple variables at the same time using a single statement.
For example, the following statement assigns value 20 to three variables x, y and z,
simultaneously.
X = y = z = 20
You can also assign different values to multiple variables in a single statement. For
example, the
following statements assigns values 20, 30 and 40 to three variables x, y and z, respectively, at the
same time.
X, y, z = 20, 30, 40
Note that the above statement assigns values order-wise, that is, the first
value is assigned to the
first variable, the second value to second variable, and so on.
If you need to swap the values of two variables (say x and y), you
can do this using a single
statement as shown here: x, y = y, X
(78)
This statement first displays the message Enter your name: and then waits for the user to enter a value.
We can use the input () function to enter numeric data also. In that case, we typecast (change)
the string of digits entered by the user to an appropriate numeric type using the function. For
example, type the following statement at the prompt >>> in the interactive mode and press the
Enter key.
>>>y=int (input ("Enter your roll no: "))
This statement displays the message Enter your roll no: and then waits for you to enter a value.
As you type a value (say, 17) and press the Enter key, the input (0 function will convert the
entered string (that is, 17) to an integer before assigning it to the variable y.
The print () Function: Theprint () function lets you display a constant, the value of avariable
or the result of an expression. For example, consider the following statement: print (8) displays 8
While entering numeric values using input (0, ensure that the values entered by you be
numeric convertible, otherwise Python will produce an error.
COMMENTS IN PYTHON
Comments are the non-executable statements that are used in a program to increase its readability.
They are used to explain the program code to anyone who views your program.
In Python, you can use either a single line or a multiline comment in a program. A single line
comment starts with a hash '# symbol. For example, the statement given below is a single line
comment.
#This is a single line comment.
If you want to add a comment in your program that expands to more than one line, enclose the
comment within triple quotes (""" no). For example, consider the statement given below.
nThis
1s a
79
Example 2: A Python program to compute the simple interest
"Simp_Intrst-py -D/Exploring IT- Revision/Class 6/Python Pr. IDLE Shll 3.10.6
Eile Edit
Fgrmat Bun ptions Window Help Edit Shell
Eile
#Program to compute the simple interest Debug Qptions Window Help
Pyehon a
- Lnt (Lnput ("Enter 3149) tHSC . 1 e t 9 e 7 b 4 b d , Aug 1 2022, 2116
principal: "))
- int (inpue ("Enter tate Type "help". "copyr1ghe",
of "credicg" or "l1cense () tor
- Ant (1npus ("Enter time in 1nterest: ")) more Antormation.
years: "))
S (PR"I)/100 -RESTART: D:/Exploring IT
Print ("Simple Interest:", S) Revision/Clasa 6/ Python
Programs /51mp Intrat.pY
PEAnctpal: 7000
zesti 4
Enter tine sn veara:
SAmpie Interest: 1400,0
temp_c ((temp_ t-32) *5) /9 49) (HSC v.1932 64 bit (AMD61) ) on vin32
Print (temp_f, " Fahrenheit - ". temp_c, Celsius") "copyr1ght", "creditg" or "license () tor
nOre inforratic
Example 5: APython program to accept two numbers and swap (interchange) their values
ÀSwap.py - D:\Exploring IT- Revision\Class 6Python Pr.. X è IDLE Shell 3.10.6 X
Eile Edit Fgrmat Bun Qptions Window Help Eile Edit Shell Debug Qptions Window Help
#Program to sap the values ot two numbers Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21
numl-1nt (input ("Enter first number: ")) :53:49) (MSC v.1932 64 bit (AMD64) ) on win32
num2=1nt (1nput ("Enter second number: ")) Type "help", "copyright", "credits" or "l1cense () "
tempnuml Or mOre intornation.
80)
Example 6: A Python program to perform different operations on strings
IDLE Shell 3.10.6 X
File Edit Shell Debug Options Window Help
Python 3.10.6 (tags/v3.10.6: 9cTb4bd, Aug 1 2022, 21:5
3:49) (HSC v.1932 64 bit (AMD64) ] on win32
Type "help", "copyright", "credits" or "license () " tor
str_opr.py-DAExploring IT - Revision\ Class 6\Python Programsls. mOre information.
Fie Edit Fomat Run Options Window Help RESTART: D:\Exploring IT - Revision\Class 6\Pytho
#Fzogran co pertorm, opezations on stzings a Programs\str opr.py
Strinput("Entex a String: ")
Enter a string: Python
prAnt ("")
", str)
Given string! Python
print ("Last chazactez of the string: ", str[-l]) First character of the string:
print ("Length of string: ",1en (stz) ) Last character of the string:
princ ("String Dtarcing tzcm 3rd to Sth character: ,stz (2:5]) Length of string:6
print ("String 9tarting trom 2nd character: ",stx [l:]) String starting fzom 3xd to 5th character: eho
pEint ("5tring 1n revere order: ", str [tt-1)) Stxing scarcing from 2nd character: ython
PEnE ("atring atter concatenation:", str + #orld")l String in reverse oxder: nohtyP
String aftex atenation: Python World
>>>
Example 7: A Python programn to read and print the average of three numbers
è avg.py- DAExploring IT-Revision\ Class 6\Python Progra... IDLE Shell 3.10.6
Eile Fdit grmat Bun Qptions indow Heip File Edit Shel Debug Qptions Window Help
Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21
#Program to tind the averaçe of three numbers
numl-Lioat (1input ("Enter the first number: "))
:53:49) (MSC v.1932 64 bit (AMD64)) on win32
Type "help", "copyright", "credits" or "1icense () "
num2=loat econd number: "))
(nputsnumber:
num3=float (input ("Enter
avg (numl+num2+num3)/3
the third "))
Or mOre information.
RESTART: D:\Exploring IT - Revision\Class 6\P
print("Average o", numl, num2, "and", num3, ":", avg)
ython Programs\avg.py
Enter the first number: 25
Enter the second nmbex
53
Enter Che
Average of 25.0 78.0 and 53.0 : 52 .0
(81
Example 9: APython program to calculate the surface area and volume of a sphere
X
spherepy -D/Exploring IT -Revision/Class 6/Pyt. -
è IDLE Shell 3.10.6
Eile Edit Fgmat Bun Qptions Window Heip Eile Edit Shel! Debug Qptions Window Help
w*program to calculate the surface area and Python 3.10.6 (tags/v3.10.6:9cTb4bd, Aug 11 2022,
volue of a aphere#mm 21153149) (MSC V.1932
TYpe "help", "copyrighe", MD64))
ored:
win32
m1icense ()
rad=tloat (input ("Enter che radius of sphere: ") or more information.
pi=3.14 RESTART: D:/Exploring IT- Revision/Class 6
sur area=4*pi rad rad
vol-4.0/3.0*p1*zrad" *3 /Python Programs/spheePy
print (" Surface area of spehere:", sur area) Entex the zadius of sphere: 5
Surface area O 5Penese. 314.0
print ("volume ot sphere:", vol) Volume of sphere: 523.3333333333334
|>>>||
program for Example 9 output for Example9
Example 10: APython program to accept two numbers and swap their values without using a
third variable
IDLE Shell 3.10.6 X
"swapping,py -DAExploring IT- Revision\Class 6Pyth.
ile Edit Fgrmat Bun Qptions Window Help Eile Edit Shel Debug Qptions Window Help
Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 2
*program to 5wap the values of two numbers 1:53:49) (HSC v.1932 64 bit (AMD64)) on win32
without using the third variable"**
Iype "help Hcopyr1ght", "Credits" or "license () "
for more afornation.
numl=int (input ("Enter first nunber: "))
num2=int (input ("Enter second number: ")) ==RESTART : D:\Exploring IT - Revision\Clas9 6\Py
numl, num2-num2, num1
Print ("After swapping, the numbers are: ", numl, num2) thon Programs\svapping.py
Enter first nurbez
Enter second aurber:
|After sWapping, the numbers are: 39 86
>>>
QUICK RECAP
A
well-defined set of instructions that directs the computer do a task is called a program.
Python is apowerful programming language, developed by Guido Van Rossum in the late 1980s.
You can use Python in two modes: command line mode and IDLE mode.
IDLE has a Python Shell window where you can write and run Python programs.
You can use Python IDLE in two different ways: interactive mode and script mode.
Atoken is the smallest individual unit of a program. It is a set of characters that logically belong
together. Python tokens include keywords, identifiers, literals, operators and punctuators.
Adata type defines the type of data and the operations that can be performed on it. Various
data types available in Python are numbers (integer, floating-point and complex numbers),
None, sequences (strings, tuple and list), sets and mappings (dictionary).
Avariable is a name that represents a memory location which stores a value of a specific data
type. The data stored at a particular location can be accessed using the variable name.
Python provides input () function to obtain input from the user and print () statement to
display the output.
Comments are the non-executable statements that are used in a program to improve its
readability. They are used to explain the program code to anyone who views your program.
82