KEMBAR78
Class 6 Phython Chapter For Revision | PDF | Data Type | Boolean Data Type
0% found this document useful (0 votes)
101 views17 pages

Class 6 Phython Chapter For Revision

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)
101 views17 pages

Class 6 Phython Chapter For Revision

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

(SHARE) 6

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

OUICK CONMECT CRITICAL THINKING CROSS CURRICUL AR SKILLS


You have already learnt about algorithms. Given
below is an algorithm to check whether a number
is even or odd. Draw a flowchart for the same in
the given space.
Algorithm to check whether a number is even or
odd

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?

Python is a powerful and popular high-level programming language, developed by a Dutch


programmer Guido Van Rossum in the late 1980s. In Python, you can develop simple programs
for solving mathematical problems as well as large web-based applications, games, and 3D
applications.
Python can run on different operating systems Python was created as a successor of
QUICK the language ABC (All Basic Code) and
such as Windows, Mac, Linux, etc. It has a simple FACT
released publicly in 1991.
English-like syntax and highly readable code
that makes it an excellent choice for coding for
beginners. It is easy to learn and does not require prior knowledge of any programming language.
Features of Python: The following are some features of Python that have made it so popular.
" Easy to learn and use: Python is suitable for new programmers as it uses simple English words
and has a simple syntax.
An interpreted language: Python uses an interpreter that processes the Python programs line
by line at runtime. The interpreter takes the source code and then translates each statement to
portable byte-code and executes it immediately. This makes the process of debugging easier.
Free and open source: Python is available on the Internet for free and you can download it
from the oficial website of Python. It is an open-source program, which means the source
code of Python is also available. Anyone can read its source code, copy it, make changes and
use pieces of it in new programs.
Interactive: Itprovides an interactive shell that allows you to directly interact with the interpreter
to write and test your programs.
Extensible: The code written in some other language such as C, C+t, CORBA and Java can be
merged with Python programs and run to give scripting capabilities to that program.
Object-oriented language: Other than functional and structured programming methods,
Python also supports object-oriented programming (0OP) approach that encapsulates code
within objects. It provides a simple yet powerful way of implementing OOP, especially in
comparison to languages such as C++ or Java.

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

desired version from the Python website Loking a Pythin 3 S b spc

https:/www.python.org/downloads/ and then


downloading Python for Windows
68
install it on your computer. At the time PvthoÍn L104 (64-b) Setup
X

of writing this book, the latest version of Setup Progress


Python for Windows is Python 3.10.6,
which was released on 4 October, 2021. Instaling

Python 3.10.6 Core lnterpreter (64-bit)


Click the Download Python 3.10.6button
to start downloading. Once the download
is completed, the setup file python
3.10.6.exe is saved on your computer. python
To install Python, double-click on this windowS Cancel

file and follow the installing Python


instructions.
WORKING WITH PYTHON
Once Python has been installed, you can use it in two modes:
Command line mode IDLE mode

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

NOnetiate fur Wirdeos 1C


1. Click the Start button ( and scroll down to the letter P in the list of
programs.
PCesith Check
2. Click Python 3.10 and then click Python 3.10 (64-bit). Python opens Phone Link

up in the command line mode with a cursor blinking at the prompt Phcton

Ptcr

Python 2.10

Python A10 (64-bi) DE Pyten 30 64bi


X
vtho
hon 3.1e.6_(tags/v3.10.6:9c 7b4bd, Aug 2022, 21:53:49) (NSC v.1912 64 bit (A064)) on vin32 .
Type "heip , "copyright", "credits" or "license for more information on Mamaals (b4-bt)
A n 110 Mode Dos (G4 t
D

Ok Hea Total Secty

SageThumb

ype here to search

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

blinking at the prompt >>>. Pyhon 110 Mau 54


IDLE Shell 3.10.6 X

Eile Edit Shel Debug Qptions Window Help 6


Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) (MSC v.l932 Ouik Heal Total Secnty
4 bit (AMD64)) on win32
£or more 1nformation.
Type "help", "copyri1ght", "credits" or "license () "
1 Sagelhumbs

o pe here to search
Python Shell window
starting Python
You can use Python IDLE in two different ways: in IDLE mode

You can type commands directly DLE Shell 3.10.6


X

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!

interpreter will execute it and


>>9+7

pzint (" D12lerence betveen 15 and , 15-8)


>>> D1Llerence
display its result as shown in the between 15 and 1s

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

Python script mode, follow these


New File
Open... WCtde0
Open Module... Alt+M

steps. Recent Files

1. In the Python Shell window,


Module Browser Alt+C
Path Browser
click the File menu and then Save Ctres
Ctd-Shit-s
click New File to create a new Save As.
Save Copy As.. Alt-Shift-S

file. A new Python Edit window Print Window Ctrl-P

opens up, Close Window At-F4


Exit IDLE Ctd-Q

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!

Saving the Program: After writing


the program, you should save it for future reference.
To save the program, follow these steps. QUICK You can also press Ctrl + N
1, Click the File menu and then click Save. Or, you can TIP to create a new file.

press Ctrl + S keys. The Save As dialog box appears.


2. Type a suitable name with the extension .py in the File name text box.
untitle
Seve Aa
Fomat Bun Dpticns Windew Help
Python Python)10
Open.
Search Python10
Open Module A-M Organite New folder
E
Recent Files
Narme
Module Browter AltC Date modfied
Quick access
Path Brewer DLLS VV2022 1041 PM
Desktop Fle folder
Save Dee
Dewnleads Vw2022 1041 PM File folde
Save As Ctrt-Sht$ incude VV2022 1040 PM
AL Decumants Fle folder
Save Copy As Alt ShtS VV2022 t041 PM File folder
Pituees
Print Wndow CtrleP VV2022 1041 PM File folder
Chapter 4 Ferm Scriets VV2022 1042 PM
Clese Window Alt-F4 File folder
at DLE
Chaptr 6lntrod VV2022 1041 PM
Ctri Q File folder
lools Vw2022 1041 P%M
Fle folder
Images

Fle pame MyfintPogrampl


Seve as bpe Python fles

A Hide Felders
Cance

3. Click the Save button.


Running the Python Program: After you have
execute it. To run a Python program, click the Runwritten and saved a program, the next step is to
Run Module. The program will run menu in the Python Shell window and then
and the output will be click
You can also run a program by displayed the Python Shell window.
in
pressing the F5 key.
MyfirtProgrampy-UserMenova/AppData/LocaVPrograms/Pythe
Ele Edit Format
2y Eizst prog
Bun Options ndow Help
DLE Shal
Fe L Shel
104

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!"

By enclosing the multiline string in triple quotes. For example,


Strvar = Welcome

Back!

How are you?'""

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)

Punctuators: Punctuators, also known The combination of values (constants),


as separators, are the tokens that serve variables and operators formn an expression,
QUICK
different purposes based on the context MOTE which generates a single value. For example,
in which they are used. Some punctuators x+5 is an expression. The expression values
can also act as operands for operators.
are used as operators, some are used to
demarcate aportion of theprogram, and so on. Some common punctuators of Python are: () (}

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

Numbers None Sequences Sets Mappings

Integer Floating Complex String Tuple List Dictionary


Point

Boolean

Let us learn about these data types.


Numbers: The number data types are used to store numeric values. The data types in Python
which can store numbers are as follows. Python supports integers, floating-point numbers and
complex numbers.
Integers: They are the whole numbers (positive or negative) with no decimal point. In Python,
the data types, int, long and bool are used to store integers.
75
int: This data type is used to store signed integer values, for example, 82, -356, etc. It uses 4
bytes (32 bits) to store a value. The range of an integer in Python can be from -2147483648
to 2147483647.
long: This data type is used to store long integers, for example, 5436723L, 78634467238L,
etc. A long integer has unlimited range subject to available memory. When we want a value
to be treated as very long integer value, we append 'L' to the value. Such values are treated
as long integers by Python.
bool: It is a unique data type, consisting of two constants, True and False. A Boolean True
value means a non-zero, non-null and non-empty, while a Boolean False means a zero value.
Floating-point numbers: These are the numbers with fractions or decimal point. In Python,
the floatdata type is used to hold floating-point numbers, for example, 0.7, 1.35, -1.67, etc.
A floating-point number is accurate up to 15 decimal places.
Complex number: It is of the form A+Bj where Ais the real part, Bis the imaginary part
and j represents v(-1). The complex data type used to store a complex number in Python
is made up of two floating-point values, one each
Even though the value 1.0
for real and imaginary part. For accessing different QUICK is integer, the value 1.0 is a
parts of a complex number (say, x), we will use NOTE
floating-point number.
x.real and x. image.

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]}

VARIABLES AND ASSIGNMENTS

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

QUICK CHECK CRITICAL THINKING


1. Which of the following is a valid identifier name? Circle it.
num@var 9dob class address p.var

2. Circle the incorrect statement from the


following statements.
Roll no=21 name= Ruby' X, y=y, x Age=l2

INPUT AND OUTPUT


A program needs to interact with the user to accomplish the desired task.
This is accomplished
through input-output facility. Input means getting data entered by the user and output
means
presenting result to the user. Python provides input () function to obtain input from the user
and
print () function to display the output. Let us learn about these functions.
The input () Function: The input ofunction reads a single line
of text from the keyboard
and returns it as a string. To understand, type the
the interactive mode and press the Enter key. following statement at the prompt >>> in
>>>x=input ()
The cursor blinks and waits for you type a value. Type the
value and press the Enter key. Whatever
you type, the input () function converts it into a string and then
assigns it to the variable on the
left-hand side (x in our case).
The input () function can also display a message and then
wait for the input. For example, type
the following statement at the prompt >>> in the
interactive mode and press the Enter key.
>>>x=input ("Enter your name: ")

(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

multiline comment. """

SOME SIMPLE PYTHON PROGRAMS

Let us write some simple programs in Python.


Example 1: A Python program to add, subtract, multiply and divide two numbers
Arith_Oper.py -D/Exploring IT -Revision/Class Python Pro D X IDLE Shel 3.10.6
File Fdit Format Bun Qptions Window Help File Edit Shell Debug Options Window Help
#Progran to add, subtract, multiply and divide two nunbers
45
Python 3.10.6 (tags/v3. 10.6:9c7b4bd, Aug 1 2022, 2115
3:49) [HSC v.1932 64 bit (AMD64) ) on vin32
Type "help", "copyright", "creditg" or "11cense () " tor
print ( Sum", a+b) mOre ntormation.
print ("Di Clerence ", -b)
print ("Product ", a*b) RESTART: D:/Exploring II - Revision/Class 6/python
Print ("Quotient ", a/b) Program/ht
AELth_Oper.p
Sum 54
DLrlerence 3¬
Product 405
Quotient 5.0

program for Example 1 output for Example 1

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

program for Example 2 output for Example 2


Example 3: A Python program to convert number of days into hours, minutes and seconds
A Timepy - D/Exploring IT - Revision/Class
6/Python Prograns.. DLE Shell 3.10.6
Ele Edit
Fgrmat Run Options Window Help
File Edit Shel! Debug Options Window Help
Progran to convert days Lnto hours, minutes and seconds Python 3.10
Ant (input ("Enter n0. 0t days: ")) 3:49) rMe
0.:9e7b4bd, Aug 1 2022. 21+s
(AHD64)1 on win32
h60 Type "help, "copyright", "credits" or "l1cense () tor
0 mOre information.
print (d, days are equal to:")
print (h, " hours or ", , " ninutes or ", s, "seconds") RESTART: D:/Exploring IT - Revision/Class 6/Pyt
hon Pzograms/Tine.PY
Enter no. of daya: 4
4 ays are equal to:
96 hours or 5760 mánutes or 345600 econds
>>>

program for Example 3 output for Example 3


Example 4: A Python program to convert temperature in Fahrenheit to temperature in Celsius
Temperaturepy -D/Exploring IT -Revision/Class 6/Python Pr. X
DLE Shell3.10.6
Eile Edit Fgrmat Bun Qptions ndow Help
File Edit Shell Debug ptions Window Help
#Program to convert temperature in Fahrenheit to Cels1us
temp t loat (1nput ("Enter temperature in Fahrenheiti ")) Python 3.10.6 (tags/v3.10.6 1 9c7b4bd, Aug 1 2022, 21:53

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

RESTART : Di/Exploring 1T - Revision/Class 6/Python P


zograms/Temperature.py
Enter tempezature in Fahrenheit: 98
98.0 Fahrenheit - 36.6666é6666666664 Celaius
>>>|
program for Example 4 output for Example 4

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.

num2 temp RESTART : D:\Exploring II - Revision\ Class 6\P


print ("After swapping, the nunbers are: ", numl, num2) ython Proqrams\svap.py m
Enter tirst number: 53
Enter second number: 45
After Swapping, the numbers are: 45 53

program for Example 5 output for Example 5

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

program for Example 6 output for Example 6

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

program for Example 7 output for Example 7

Example 8: A Python program to calculate the square root of a number


squarerootpy - DAExploring IT -Revision\Class 6L.. IDLE Shell 3.10.6 D
Eile Edit She Debug Qptions Window Help
Eile Edit Fgrmat Bun Qptions oindow Help Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 2
#Program to caloulate the square root of a number 1:53:49) (MSC v.1932 64 bit (AMD64) ) on win 32
num=loat (1nput ("Enter a positive number: "))
Type "help", "copyrighe", "credits" or "license ()
num sqrt"num0.5 tor nore information.
print ("Square root Of", num, ": " aum sqrt)
-- RESIART: D:\Exploring IT - Revision\ Class 6\Pyth
on Prograns\square_rOOt.py
Enter a positive nunber: 625
Square root ot 625.0 : 25.0
>>

program for Example 8 output for Example 8

(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
>>>

program for Example 10 output for Example 10

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

You might also like