0% found this document useful (0 votes)
30 views

Python

Uploaded by

proylinux
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Python

Uploaded by

proylinux
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

17 Introduction to Python

LEARNING OUTCOMES
to:
he student will be able
. know about Python and its features.
, install Python and identify the components of Python window.
work with Interactive mode and Script mode.
l use different data types, print and input functions.

7.1 showS a recipe to make tomato


-ave you ever tried making pasta on your own? Figure
recipe isa set of instructions
asta. It solves the problem of "how to make tomato pasta?" The
n what do, how to do, and when do it. The set of instructions uses the ingredients
(input) to make tomato pasta (output).

Recipe for Tomato Pasta


Instructions to make Tomato Pasta:
List of required ingredients:
1. Boil water in a large pan.
500 ml water 2. Add some pasta to the boiling water.
150 gram pasta 3. Simmer for 10 minutes.
4. Strain and cool.
spoon olive oil
5. Add olive oil in a pan.
ilarge chopped onion 6. Add the onions and fry gently.
500 gram chopped tomatoes 7. Stir in the tomatoes and the hummus.
100 grarn humus 8. Leave it to simmer for 5 minutes.
9. Add the pasta and mix it. Serve while hot.

Tomato Pasta
Fiqure 7.1: Making

the recipe is the


input. Simmering, straining, and stirring
Adding the required ingredients tothe product that
all
you get after processing is the output,
e ingredients is procesS, and
the
Which is the pasta.
the work done on a computer, you
three stages. To get
Lienterkewithese, rawa data
Computer also works in
operates on this data (process), and the desired result
(input), a computer
S obtained (output).
Process Output
Input

Kios Cyber Quest 87


To get the desired output from the computer, you give some instructions to it. A set of
instructions called the programs. In simple words, a program is a sequence of instructions
that specifies how to perform a computation. These programs help a computer to perform:
wide range of tasks.

There are some specific computer languages, which are used to write programs. Some of the
popular examples of programming languages are Python, C, C++, LISP, Pascal, Java, PHP, etc.
In this chapter. you will learn the basics of the
Python programming language.
Python
Python is a simple programming language. It is used to write codes for
the computer programs. Python was created by
Guido van Rossum
when he was working at Centrum Wiskunde &
which isa National Research Institute for
Informatica (CWI),
Science in Netherlands. The language wasMathematics
and Computer
released in 1991. Guido van Rossum
Features of Python
Some of the features that make Python so
popular are as follows:
It is an easy to learn
It is a platform
general-purpose high-level programming language.
independent programming language, which means it can be used on
machine and in any operating system. any
It has a simple syntax.

Python is a case-sensitive
language.
It is an
interpreted language.
It is free to use and even
free for commercial redistribution.
Applications of Python Programming
Python is a popular and
easy-to-learn language. It can be used to do the
Build a website following:
Program robots Develop games
Develop artificial intelligence based Perform scientific computations
applications
Installing
Python can be
Python
easily installed on your
To download computer by
following the given steps:
Python, visit the site:
Python button under
www.pytversion
'Download the latest hon.org/downlo
forads and click
Windows', will You
on the
Download
get an .exe file.
88
puthon

Let's Recall
ython 37.4 Ahigh-level language is a
computer language that
uses letters, numbers,
and speclal symbols for
coding. It is a user-friendly
and interactlve type of
language. For example,
C++, Python, Java, etc.

Figure 7.2: Downloading Python


& Double-click on the .exe file. Click on Run or
Install Now the
dialog box, to start the installation. Keep following the instructions
to install Python.
NOTE
we have used Python 3.7.4 in this chapter. To get the same version, go
to the https: //www.python.org/downloads/ site's home page and look
for the Python 3.7.4 release under the section "Looking for a specific
release? Select the Download option. A new window will appear. In the
'Files' section, choose the setup file as per your system configuration. To
get the .exe file, right-click on the zipped folder and choose Extract files/
Extract Here from the context menu. To begin the installation, double Let's Know More
click on the .exe file and select the Run or Install Now option. Syntax refers to the rules
to be followed while
writing a program in any
language.
) Getting Started with Python
following two
ATter installing Python, you can start with any of the
modes:

? Interactive mode
* Script mode
the in Interactive
Ine Interactive mode is the default mode. To launch
> IDLE (Python 3.7).
vde, click on Start > Scroll down to Python 3.7
Figure 7.3.
The IDLE Screen appears as shown in

gs/v3.7.4:e09359112e, Jul 8 2019, 19:29


Python 3.7.4 (tags/ bit untel )) on win32
22) (MSC v.1916 32 "1icense ()" tor m
"copyright ", "credits" or
YPe "help", Let's Know More
|ore information.| f orsa
PySoy a 30 game engine
|>>> the rapid development
of Python-based games.
Shell Window
Python 3.7.4
Figure 7.3:

89
Components of IDLE Python
Just like any other application window, the IDLE Python screen has the following components:
Title Bar
Menu Bar

Fyt hon 3.7.4 (t ags/v3.7.4:e09359112e, Jul 8 2019, 19:29


MSC V. 1916 32 bit (Intel)) on win32
Command
romt YFe "help", "copyright", "credits" or "license () " for m
ore informat ion.
Status Bar

n 2 Cet T2
Figure 7.4: Components of Python Window

Title Bar
This is the area that displays the name of the application and the
document. It also contains
command buttons, like Minimize, Maximize/ Restore, and Close.
Menu Bar
The menu bar consists of various menus with
different options. The menus of the Python
window are File, Edit, Shell, Debug, Options,
Window, and Help. File Menu

The File Menu Fde (d Shel Debug Ogtens


New File

This menu is used to work with the options related to the Open. CttO

fle. It includes sub-options, like currently used Recert Files


Module Beeser A
A-M

opening a new file, opening an existing Pth Erewser

file, viewing recently used files, saving the Cuies


files, closing the files, and Seve As Ctrt-Shs

exiting the application. Sve Cogy A


Print Widow
ARShs
CtrtP
Close
The Edit Menu Ctrte Q
Figure 7.5: File Menu
This menu is generally used to edit the file in use. You Edit Shell Debug Options Window Hel
can
cut, copy, or paste the selected text. You can Undd Edit Menu Ctrt-Z
also search for a Redo
Ctrt-Shift-Z
particular text or phrase, and even replace it with some Cut
text.
other Copy
Ctrl-X
Ctrt-C
Paste Ctrl-V
Select All Ctrl- A
The Help Menu
Figure 7.6: Edit Menu
To get help related to any
topic of Python, press the F1 key or click on HelpHelp Menu)
the Help menu. About IDLE

Command Prompt IDLE Help


Python Docs F1
The command prompt is denoted by '>>>, This Tutle Demo
the area where you Figure 7.7: Help Menu
type a code.

90
StatusBar
bar tells yOu the
The Status current status of your control or cursor on Let's Recall
the window,
You can prass the F1 key
to use Python Help

) Working in Interactive Mode


in the Interactive mode of Python, the
-ine. giving the output.
instructions are executed, line-

this mode, the commands are typed next to the


Python Commnand
arNmpt (>>>). For example, if you type 3+6 next to the
Python prompt,
will give you the result as 9.
-.work in the
interactive mode, follow the process given:
Let's Know More

ATiNyZOAE
Visit the lab and
follow the given steps to get familiar with the Interactive
The Python Integrated
Development ano
Learning Environment
mode. (IDLE) executes

.Click on Start > Python 3-7 > IDLE (Python 3-7), It will open the Python instructions, one ine at
a time.
Shell window (interactive mode) where you will see the Python
prompt
(>>).
Type the commands next to Python prompt one-by-one as shown in figure
given below, and press Enter. Python will immediately give the output for
each of them.

591126, Jul 2019, 19:29:22) (HSC


Tr "he lp", "copyight", "credits" or "license() toE Bore intorn
#tica.

elcee to ytho

12.7#
Let's Know More

Fale
12+70

python
Python is an interpreted
NOTE language. It means the
Python interpreter reads
Ihe Interactive mode is useful for testing code where you type the the text line-byline and
imands, one at a time, and get the result or error immediately. converts the command
(source code) into
machine language (object
Printing a Message code). After processing
the interpreter again
converts the machine
print( )function ís Used to display the output of arny command on code into human readable
the screen. It can also be used to print the specified messages. form (output)

Kips | Cyber
Quest 91
For example:
World" ) will display Hello World

hthn 1..4 (tagn /v1. 1,4:e09139112e. Jul 8 z019, 19:29:22) IMSC V. 1916 32 bit
EYEight . ctedit3 or |icense () " or more infotmatio.

Norld

Figure 7.8: Using print() Function


ynon is a case-sensitive programing language. It means that Python
differentiates between
capital and small letters. For example, Print (P capital) and print (p small) are two
different
things for Python, where print is a valid command in Python, while Print is just a word
not a command. and

YOu can also pass more than one argument to the


print () function. In such a case, the
arguments are separated by commas, shown in Figure 7.9.

Python 3.7.4
(taqs/v3.7.4:e09359112e, Jul
(Intel)) on win32 8 2019, 19:29:22) [MSC v. 1916 32 bit
TyEe "help. "copyright", "credits" or
"license ()" for more information.
Pvtho
print('Python 15 a high level
anguage',1t has easy syntax')
high level language It has easy syntax
int (1
"10+56=, 10+56)
10-56= 66
D>> print
('10*9-50+302/10=,
10*8-50+30*2/10- 36.0 10*8-50+30*2/10)
>> print ('5 plus5,5+5, 'and 5 into 5 =.
5 plus 5 - 10 and 5 into 5 55)
25

Figure 7.9: Separated Arguments by Commas


Using IDLE as a Calculator
To evaluate an arithmetic expression, it is
PyenVA9
2nde y
not necessary to use the print() function. Python
4
If you type an arithmetic expression at the (Intel)) on win32
Type "help
(tags/v3.7.4:e09359l12e, Jul 8 2o19, 19: 29:2
Python command prompt and press the >>> I0+20lp"COPYright", "credits" or license () for O
30
Enter key, the interpreter automatically >>> 45/6

evaluates it and shows the result. In this >>> 67//8


A
P22 45*78.7
case, the interpreter acts as a simple D941.5
calculator. The expressions are evaluated
using operators, like +, ", 1, etc. The
basic BODMAS rules are followed for Fiqure7.10: IDLE as a Calculator
performing calculations.
9
Cyber Quest | KiPs
In IDLE, you can press Alt +P to
repeat the previous command
Practice Time
Tpethe folloowing
table given below: expressions, one by-one, next to the
Python prompt and note down the output inthe
SNo.
Expression Result
23*98
2.
(100+58),/3
2 Write the statement next to the
. thon works in two modes: Python prompt usingtthe print() function to get the following output:
. Interpreter is a Interactive mode and Script mode.
language processor.

) Variables in Python
vou need to store some food for
future use, what will you require? Well, you will
container to store the food. Similarly, when you are need a
working with the values in Python, you
require some storage location to hold the values for later use.
Named storage locations in the
computer memory, which are used to store data are called
variables. Avariable can store only
one data value at a time. When a new
value is stored in a variable, its previous value gets
Dverwritten.

Assigning Values to Variables


Values are assigned to variables using the assignment operator (=). For example, the
statement
-25 assigns the value 25 to the variable x.

UOServe the following codes to understand the use of the assignment operators:
Variable Description
a=10 #Value 10 is assigned to the variable a.
b=20 # Value 20 is assigned to the variable
b.

(-a+b #The numbers are added and the value is assigned to the variable c, i.e., 30 is assigned
to the variable c.
the variable a. So, now the value of the variable a is
# Value 20 (30-10) is assigned to
a-c-10 20, and not 10.

Kios Cyber Quest 93


Rules to Write the Variable Names
There are certain rules in Python that have to be followed to form valid variable names. The
rules for valid identifier (variable name) are:

Avariable name must start with an alphabet (capital or small) or an undersSCore (_ ).


Avariable name can consist of letters, digits, and underscore. No other character is
allowed.
A keyword cannot be used as a variable name.
A variable name can be of any length.
Variable names are case-sensitive (e.g., Age and age are different variable names).
Examples of some valid variable names are:
Class, emp code, totsalary, minvalue, bal_ fee, agel980, a45r
Examples of some invalid variable names are:
Invalid Variable Name Reason
Employee code Space is not allowed in a variable name.
10code Variable name cannot start with a digit.
A.B.C. Ltd (.) is not allowed in a variable name.
ABCeltd Special characters are not allowed in a variable name.
else 'else' is a keyword in Python, so it cannot be used as a variable name.

NOTE,
If a variable is being used without assigning a value, i.e., if the variable is not defined, it gives an
error.

The following code gives an error because the variable x is used in the print() function without
being defined.
Python 3.7 (64-bit)
rhon ..2(t8gs/v).7.219aJffco492, Dec 23 2018, 23109:25) (MSC V. 1916 b1t
e help, copyright. credits" or "license for more information.

st recent call last):


E:1 stdin,, 1ine 1, in enodule»
eetrror: nne x' is not defined

Figure 7.11:Undefined Variable Error

94 Cyber Quest | Kips


)Working in Script Mode
The Interactive mode is preferred for small programs, where only a few commands are to
be executed. This is because the output in the Interactive mode is compressed between the
statements and may create confusion while writing long programs.
For writing lengthy programs in Python, the Script mode is used. Using this mode, you can
create and edit Python programs. In this mode, you can also save your files so that they can
be used later. The complete script is written in an editor.

Creating Module/ Script/ Program File


To start with the Script mode for creating a module or program, follow the given steps:
Open IDLE Python Shell, i.e., the Interactive mode.
Click on File > New File in IDLE Python Shell as shown in Figure 7.12.
'progl.py-c/User/Dinesty Desktop/Tools7 Pytho/B7/progl.py 02A
Fse She Deus Optens Wndo Halp Ele Edit Fgrmat Bun Qptions Window Help
v3.7.4:e09359112e
a=10
CeO win32
A-M Eight", "credits" |b=20
Fie c=a+b
Med Br A print ("the sum of the numbers is:", c)
P
SerCagy A A-S-5

Prn CadP

Figure 7.13: Editor Window


Figure 7.12: Creating New File

In the new window that opens, type the Pythor

Commands you want to save as a program as Orgae

shown in Figure 7.13. Quid ettest


Dettop
OLLE

Click on File > Save, and save the file L


Ptn

with the name prog1.py' where .py is the Songt

extension for Python files.


Toeh

Running Module/Script/Program File


After the Python program hle is created, you can
steps:
run the program by rolowing the given Figure 7.14: Saving a Fille
Shell.
Open IDLE Python
Click on File > Open. (if the file is already opened, you can directly followthe next step).
Run Module or press F5 key.
Click on Run >
commands.
execute all the
It will

95
e output wilU be generated us the Pvthon Shell window.

CCh BehDeàtop Teel 7PythovB/pregl py C


Optiens Window Help
Femat Run
Sthon Shell
a-10
Chexk Medule Alt. X
b-20
Run Medule
ca+b RunCustomied ShiftFS
print ("the s is"

Figure 7.15: Run Module

Oosee the difference between the Scriot mode and the Interactive mode as shown in
Figure 7.16.
Pthon 374 Shelt
Dinh Dekp/Teeh7 Pythen.D
t Foat Bun Eile Edit Shel Rebug Qptions Window Help
Options Windcw Help
a-l0 Python 3.7.4 (tags/v3.7.4:e0935
b=20 19:29:22) [MSC V.1916 32 bit (I
Type "help", "copyright", "cred
pEAnt ("the sun of the nunbers is:", c) for more information.
>>>

* * * = RESTART: C:/Users/Dine.
Python/B7/progl.py =
the sum of-the numbers is: 30
Script Mode Interactive Mode
Figure 7.16: Program Output in Interactive Mode

Practice Time
1. Write a program to print the general
details about your school in five lines.
2. Write a program to calculate the sum of two
given numbers.

Data Types
Suppose, you have planned a holiday trip duing
for vour family members. The first vacations, and you have to book tickets
action that you need to take is to fill a
reservation done, where you need to give your form to get the
iournev, name, age, etc. Here, every piece of required details, like train number, date of
name is a string type, age is a data that you enter is of a
numeric type, and date of journey is of specific tVpe: as your
have to specify in a program, what kind of date type,
values will be stored in a specific Similarly, you
Basic Data Types in Python variable.
In Pvthon, a
data type represents the
memory can be of many types. Pyhontype has
of data
stored in a variable, The data
stored "
of value, For various standard
example, a student s marks are stored as a data types based on the type
address is stored as alphanumeric
characters. numeric value. whereas. his or no

96

Kips
he basic data types used in Python are mentioned here:
Let's Know More
int (integer): It represents integral numbers (numbers without any
A variable is a named
iractional part). 1here are three types of integers in Python: memory location that
stores the data and whose
Integer type Description value may change during
progra execution.
Integer (int) It stores values in the range of - 2147483648 to
2147483647.
Long integers (long int) It supports the values that lie beyond the range
of integers.
Soolean (bool) It represents logical values in the form of True
or False. In Boolean, Orepresents Fallse and 1 Let's Know More
represents True. reserved
ywordS are the
Key
of a programming
fractional language. They cannot be
float: It represents floating point values (numbers with used as variable names.
as well.
part). The fractional part of a floating point number may be 0
Examples of floating point numbers are 3.14, 48.6, 18.0, etc.
of characters enclosed
str (string): A string data type represents strings
").
within single or double quotation marks (' Or"
Examples of strings are 'Hello', "Myname", 218, 'Peace', etc.
are:
Some examples of data types in Python
Value Data Type
15 int

7.9 float
Computer Application str

7>3 bool
Let's Know More
Acompiler is a language
a variable by
You can assign a multiline string to processor that converts
a program written in
quotes ("
using three high-level language into
For example: machine language, and
vice versa. just like an
of data stored
as"A data type represents the type interpreter but in one go.
memory can be of
in a variable. The data stored in
many types.

Using input() Function


function is used
to accept the value for a variable from the Let's Know More
The input()
input integer and float values,you can use int() or float() along Ascript is a program that
user. To you type in Python.
function.
with the input()
97
Ouest
Program 1:
[MSC V.1916
Ae0siseLL 2e # 2019, 19:29:22)
1.7.4 itag* /y1,1. informat ion.
" tor more
or "li cense ()
2 i t (tntelh1 on win)2
Tight, credita"
**a ngat (enter the tirst value :")
enteg the firat value: 200
3** input (enter the second value:")
enter the second value: 300
Function
Figure 7.17: Using input()
function takes one string argument. This means tnat wnatever value ie
rynon, the input()
Deing entered by the user, it will be taken as a string argumen..

Program 2:
Python 3.7 (64-bit
V.1916 64 bit
s2.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) MSC
on.
Type "help, coovright. "credits" or "license" for rore informati
aingut (enter the fist value:")
t t r the second value:")
enter the second value:300
rint (c)
bona0o

Figure 7.18: Printing a String

Observe in the above program, when you add the two numbers, you do not get the sum. Rather
the numbers are joined together and are printed as a string.
Program 3:

Ele h Debug ptions Windew Help

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) (MSC v.1916


32 bit (Intel) ] on win32
Type "help", "copyright", "credits" or "license () " for more intormat ion .
>>> ainput ("enter the first value:")
enter the first value: 200
>> b=input ("enter the second value:")
enter the secCond value: 300
>> print (a Pb)
zaceback (B00t recent call ast):
Tile "<pyshell #2>", line l, in cmodule>
print la "b)
Yelrror: can't multiply sequence by non-int of type str:

Figure 7.19: Type Value Error

In this program, when you try to multiply these two values, you get an error. This is because
the strings values cannot be multiplied together.
To work with the values provided by the user, Python provides a method as inthe
discusse0
given example:
Program4:

thr33AShet
fe dt She bug Ortens Wde He
Fython 3.7.4
32 bit (tags/v3.7.4:e09359l12e,
(Intel)| on win32
Jul 8 2019, 19129:22) (MSC v.1914
"help". *copytight", "credits" or license ()" (or more informat ion
int (input ("Enter the
Enter the first number: 100 first nunber:)
>> bint (input ("Enter the
Snter the second number: 300second number:")
>> pint ("The sum of
The sun of the
the nunbers is:", a+b)
nurbers is: 400

Figure 7.20: Sum of Numbers

Observe, when you use int() function, the values are converted to integers and are added.
Program 5:
ECUeDnh Dektog Toels 2Pheni1
le lát Fomat Bun ens ndow Hele
anint (input ("Enter the value of a:")) Python J.7.4 (tags /v).7.4:e09359112e, Jul 8 2019, 13
(Intell
TYpe "he) lp,
on winJ2
"copyright", "credits" or "license () td
beint tin
D1nt (1nput ("Enter the value of b: "))
nrint (Value of a after swaping:" a) RESTART : Ct/Users/Dinesh/besktop/Tools 7
Enter the value of at 45
print ("Valua ofb after swaping:",b) zalue of a after swaping: 25
Value of b after swaping: 45

Figure 7.21: Swapping Two Numbers Output

Program 6:
taltos PtherEl4

Python J.7.4 (ta:/v).7.4:e09339112e, Jul 2019, 19129122)


5-1nt (input ("Ente: the side of the square:"))
t rrkabt. credits or 1icense t tor nore
C:/Usets/Dinesh/ Desktop/Tools 7 ython/s
pEint ("he parameter of the squate is:", p)
pIint (The area of the square is:", ar) The paraneter ef the 0 t20
rhe area of the square is1 900

Square
Figure 7.22: Area and Perimeter of a Output

Practice Time
1. Create a program to calculate 5% discount on the total purchase of stationery.
kilometres.
2. Create a program in Python to convert miles into
1Mile = 1.6 kilometres
to CelsiuE
3. Create a program to convert temperature from Fahrenheit
celsius =(Fahrenheit -32) x5/9

Using print() Function


function is Used to print a message or value.
3 The print()
It converts the message or an oDject into a string before writing it on the screen.
parameters.
. It can have multiple
It Supports multiple escape sequences to format the output, for example, \n' (new line),
1t' (tab space), and 1r (carriage return).

Quest
Kips | Cyber 99
Using separators with print0 function
Using (.) operator: When you use, operator as a separator among the values, the values s.
displayed with a space between them,
Program 7:

u Wdo e Debg Ctians ndo tele


a-10 Python 3.7.4 (tags/v3.7.4 :e093
(Intel) ) on win32

-100
Type "he lp", "copyr 1ght", "cret
PEnt la, b, e) mmmmmmm mmn RESTART: C:/Users/D!
|10 20 100
>>>

Figure 723: Using Comma Operator Output

Using tab space (1t): When you use 1t' escape sequence as a separator among the values,
the
values are displayed with a tab space between them.

Program 8:

OmDneh Deatp/Toe PP.hen 374 Shel


Fm upbons ndo Belp Fle Edt Shel! Rebug Options Window belp
Python 3.7.4 (tags /v3.7.4 :e0935
32 bit (Intel)) on win32
Type "help", "copyright", "cred
FEint (a, "\t", b, "\t", c)
RESTART: C:/Users/Di
10 20 100
>>>
Figure 7 24: Using t Escape Sequence
Output

Using newline character (\n'): A newline character in


Python is used to end a line and start
a new line. In Python, the new line
character can be used with the input() function and with
the print() functíon. The \n' is a
newline character used in Python.
Program 9:

5oy-CDineh stopToo Pen 1745ht


Ee Fymat e Lat She Debg
Bun hons ndow Help ons ndoa bel
Python 3.7.4
a-10
b=20
(Intel)) on win32 (tags/v3.7.41e093591 1:
TYpe "help", *copyright. "credits*
c-100
Print (a, "\n",b, "\n", c) 10
RESTART: C:/Users/Dinest
20
I00

Fiqure 7.25: Using n' Escape Sequenco


Output
Let us consider another example.
Suppose, you want to make a program to accept the
age, and marks of a student. For this, names
add the following code in the Python
Script file:
100
Cyber Quest | Kips
Program 10:

nameinput ("enter your name1" ython ).1,4 tage/v).,1, 4ie09591124,


agenput ("enter your age t") 2 bit (ntel) on vinl2
classinput (enter your class :") Type "he lp", "eopyright", "ecedits
print your name is:, name)
print (your age is1, age) **STARTI Ct/06eE6/p
print (*your class : ", class) input
enter your namei Aft IhaEna Gn the sarne line
onter your age: 17
enter your class:
Figure 7.26: Program without Output
Escape Sequence

NOw, in the Python script file, add In' with the input and print
function:
Program 11:

Dase- Lnput ("enter Python ).7.4 (tas/).1,4te093591120, Jul


2ge=input ("enter vour sos 32 bit (Intel) ] n win)2
type "help", *copyight", *credits" t *14
Classinput ("enter your class:\n")
print ("your name is:\n", name) RESTART: C/tsers/Dinesh/bezkts
print ("your age is: \n", age)
print (" your class : \n", Class) enter ycur name: Input
on the next line
17
enter your class:

Figure 7.27: Program with Output


Escape Sequence

In the above output window, in order to give a better understanding, the text and values are
placed one after another.

RECAP
+ Pvthon is a high-level language, used to write codes for the comnputer programs.
. Pthon was created by Guido van Rossum when he was working at Centrum Wiskunde
and Informatica (CW).
The Interactive mode is useful for testing the code where you type the commands one
at a time and get the result or error immediately.
The Script mode is Used Tor writing lengthy programs in Python.
Named storage locations in the computer memory, which are used to store data are
called variables.
The print() function Is Used to display the output of any command on the screen.
+ Python has various standard data types based on the types of values stored in the
variables.
is used
input() function accept the value for a variable from the user.
+ The

Kips | Cyber Quest 101


Drain
developer
A. Fill in the blanks.
1 Python was created by
2. The key is pressed to execute a Python program.
3 In the interactive mode of Python, the instructions are executed
4. A 1s the name of the memory lOcation that stores the data.
5. Python cannot be used as a variable name.

Hints
" Variable " Guido van Rossum " F5 " Line-by-line " Keywords

B. Write T for True and F for False.


1.

2.
OO000O
T0 evaluate an arithmetic expression, it is not necessary to use the print() function.
Avariable name can consists of letters, digits, and underscore.
3. In Python, data types represent the type of data stored in a variable.
4. In Python, only one type of data can be stored in memory.
the user.
5. The print() function is used to accept the value of a variable from
together.
6. The string values cannot be multiplied
C. Application-based questions.
display the names of fruits separated
1. Kritika's computer teacher has given her an assignmentt to
she use with the print() function?
with a tab space in Python. Which separator should

quick
is working on his mathematics project work. He has to perform some
2. Amnan
should he use?
calculations. Which node of Python programming

D. Select the correct


option.
not supported in Python?
1. Which of the following data types is
b. float C. int
a. char

Cyber Quest | Kips


When a
new value is stored in avariable, its previous value gets
1
a. Accepted b. Overwritten C. Overlapped
operator.
Values are assigned to variables using the
b. print) C. Assignment
a. String
should be
The data type for i2.4
a. int b. float C. Str

the output
5, >>> print(10*t 20) will give
a. 30 b. 1020 C. 2010

: Answer the following questions.


language.
1. Write any three features of the Python

variable?
2. What is a

Python.
Explain the different working modes of
3.

in Python.
types? Explain any tWo data types
data
4. What are

print) function?
What is the use of
D.

103

Kips | Cytber Quest


6. Discuss the rules for naming the variables.

?. Discuss any two separators used with the print() function.

ASTIAYY
SEGTION
MY ACTIVITY Learning While Playing
A. Write the output for the following statements.
1. >>>print(' India', 'Delhi')
2. >>>print (' India', '\t', 'Delhi')
3. >>>print ('India', '\n', 'Delhi')
4. >>>a=10

>>>b=20

>>>c=(a+b) *4

>>>print( c)
5. >>> a='10

>>> b'20'

>>> print (a+b)

6. >>> a-13
>>> b=20

>>> print (a+b)

Cid the errors and rewrite the following


statements after correcting them.
>>>10=c
1.

2. >>>Print('India')

3. >>>Print (age)
4 >>>a=10

>>>b=20

>>>a+b=C

>>>print (c)

C. Write the output of the following code in the space provided.


one 1

two = 2

three = one + two

print(three)
hello = "hello"
World = "World"
helloworld hello + " " + World

print (helloworld)

LAB SESSION Perfection Through Practice

A
Execute the following statements in the interactive mode of Python.
1. >>> 2* 3.14* 5
2. >>> 4+5/38-5
B Write the code for the following programs in the Script mode.
Write a program to find the product of tWO numbers x and y, where x=150 and y=200.
1.
It takes 3 hours to drive a distance of 192 km. Create a program to calculate the
2.
average speed in km/h?
3 Create a program calculate and print the circumference and area of a circle.
Create a program to input the roll number, name, and marks in five subjects of a student.
Calculate the total and percentage marks of the student.

GROUP DISCUSSION For Concept Clarity

topic:
Discuss the following
mode
Interactive mode vs Script

ONLINE LINKS Looking For More

Python, visit the following websites:


know more about
To https:/Iwww. tutorialspoint.com/python/
https://www.w3schools.com/python/

10
Cyber Quest

You might also like