Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

CHAPTER

INTRODUCING PYTHON

LEARNING IN THIS CHAPTER


e Introduction to Python Variables in Python e Basic data types in Pyttm
e Python Working in Script Mode Input() runction

e Components of Python Window e Data types

Have you ever tried making pasta on your own? Figure 8.1 shows a recipe to make Tomato Pasta. It solves the

problem of "how to make Tomato Pasta?" The recipe is a set of instructions on what to do, how to do, and when to
do it. The set of instructions uses ingredients (inputs) to make Tomato Pasta (output).

RECIPE FOR TOMATO PASTA

List of required frtgredients: Instructions to make Tomato Pasta:

1. Boil water in large pan.


500 ml water
2. Add pasta to the boiling water.
150 gram pasta
3. Simmer for 10 minutes.
1 spoon olive oil
4. Strain and COOL

1 large chopped onion 5. Add olive oil in a pan.

300 gram chopped tomatoes


6. Add the onions and fry gently.
7. Stir in the tomatoes and the hummus.
100 gram hummus
8. Leave to simmer for 5 minutes.

9. Add the pasta and mix. Serve hot.

Figure 8-1: Making Tomato Pasta

Adding all the required ingredients to the recipe is input. Simmering the ingredients is processing, and the product
that you get after processing is output, which in our case is pasta.

Likewise, a computer also works in three stages. To get the work done on a computer, you enter the raw data

(input), a computer operates on this data (processing), and the desired result is obtained (output).

To get the desired output from the computer, you key in instructions to the computer using different programming
languages. There are some specific computer languages, which are used to write programs. Some of the popular
examples of Programming languages are Python, C, C+ w , LISP, Pascal, Java, PHP, etc.

Modem computers follow the set of operations called 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.

In this chapter, you will learn the basics of Python programming language, which is one of the most powerful,
high level programming languages.

Learnirg
Computers wm Kips 98
INTRODUCTION TO PYTHON
Python is a simple Programming language that is used to write codes for the computer
programs. Python was created by Guido Van Rossum when he was working at Centrum
Wiskunde & Informatica (CWI), which is a National Research Institute for Mathematics and
Computer Science in N ethertands. The language was released in 1991.

Python is a high level programming language.

Some of the features that make Python so popular are as follows:


It is an easy to leam general purpose programming language.
> It is a platform independent programming language, which means it can be used on any machine and in any
operating system.

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

APPLICATIONS/ PYTHON PROGRAMMING

Python is a popular and easy to learn language. It can be used to:


> Build a website

> Develop games


> Program robots
> Perform scientific computations
> Develop artificial intelligence applications

INSTALLING PYTHON

Python can be easily installed on your computer by following the given steps:

1. Obtaina Python Distribution: You candownload Python distnbutesfrom:

www.python.org/download.For this chapter, we have used Python 3.7.4.

python'

Python 3.7_4

Figure 82: Python


Learning
Cotnputers Wih Kips 99
2. Python Installation Process

Afterdownl oading the Python distributiont a II you need to do is, to execute it. Double-click the downloaded installer

software. Click on Run in the Dialog boxt and the installation process starts. Keep following the instruc'tions and
clicking on the Next button until you see the highlighted Finish button.

Afteryou have insta Iled Python* the [DLEscreen looks tike this:

Python Jul
32 bit on
Type "help", ico wright." , "credits" oc "license()"
ore information.

Figure 8.3: Pytl'0f1 3-7.4 Shell Window

On Windows machines, the Python installation is usually placed in 3.7.4 folderi though you can change this
when you are running the installer.

COMPONENTS OF PYTHON WINDOW


Just [Ike anyotherapplicationwindow, Pythonwindow has the fol lowingcomponents:

'Meru

22
Type "help", right", "credits" or "licen.selj•• for m

Scriz[hre

File Menu
Figure 8.4: Components of Python Window

Title Bar

This is the area that displays the name of the application and the document. It also contains

com mand buttons like minimize, maximizet restore, and close.


Menu Bar
The menu bar consists of various menus with different options. The common meni.s you will be

working with in this chapterare File, Edit, Shell, Debug Options, Window, and Help.
Working with File Menu Figure 8.5: File Menu

This menu is used to work with the options related to the currently used file. It
E:lii

U EdilW'f•u
includes suboptions like opening a new file, opening an existing file, viewing
recently used files, savingthe files, closing the files and exiting the application.

Working with EditMenu Ct'l•V

Select Zii
This menu is generally used to edit the file in use. You can cuti copy, or paste the

selected text. You can also search fora particular text orphrase, and even replace it Figure 8.6: Edit Menu

with some othertext.

Learnirg
with Kips 1
Working with Help Menu Help Menu Let's Recall
About IOLE
To get help related to any topic of Python, press Fl key or click on m high-level language is a
the Help menu. •OLÉ Help computer language that
Python Oocs uses letters. numbers, and
Script Area: This is the area where you type yourcode. Turtle Oemo special sy inbols for
coding- It is a user•frienWy
Status Bar: The Status Bar you the current status of your
tells Figure 8.7: Help Menu and interactive type of
control/cursor on the window. Iartguage. example,
C++ Python, Java, etc.
After installing Python, you are ready to workon it' You can work in Python in twoways„•
In Interactive made
In Script Mode
Python Programming in Interactive Mode
In the Interactive made of Pythone the instructions are executed$ line by [ines giving the
output.
In this mode, the commands are typed next to the Python Command prompt For
example, ifyou type 3 +6 next to the Python Prompt, itwlll give you the resultas 9.

To work in the Interactive made. fallow the process given:


Click an the Start button > scrol I down to Python 3.7 > IDLE(Python 3.7). ltwil[ open
the Python Shellwindowwhere you will see the Python

Let's Know More


Jui Syntaa refers to the
: 22) 32 on grammatical rules to be
Type "copyright." "credits" or "license O Lox followed while writing a
ore information program in any language-

Figure 8.8: Python Shell Window


Type the following commands next to Python prompt and Python will immediately
give the outputas shown in Figure 8.9.

weLearne LO pyl-harl woe 1 d f

32

Let's Know More


PY'Soy is a 3D game ertgirte
that supports Python-
based games-

Figure 8.9: Interactive Mode


Learning
Cotmputers with Kips.
NOTE Let's Recall

Interactive mode is beneficial lor testing code where you lypc the commands, one at a Ywcan press Fl key to
Python Help.
lime, and gel lhc result orcrrofimmcdiately.

use of Interpreter

In the interactive mode of the commands are executed line by line. When you
type a command next to the python prompt (>>>) and press the Enter key, the
interpreter converts the command into machine language. After processing, the

interpreter again converts the machine code into human readable form (output).
Let's Know More
Using print() function
The Python Integrated
The print() function is used to display the output of any command an the screen. It can Development and

also be used to printthespecified messages. Leaming Environment


(IDLE) executes
instructions one hoe at a
For example:
time.

{"Hello World" will display Kello World

wine
"r.retti •1 inform—t'.ic.n,.

world

Figure 8.10: Using printo function

Python is a casesensitive programing language. It means that Python differentiates

between capital and small letters. For example, Print. (P capital) and p rill (p small) 1.

are two different things far where prinl- is a valid command in Pythont while

P ein L isjustaword and notacommand.

You can also pass mare than one argument to the pr in L function. In such a case, the

arguments are separated by commas as shown in Figure & 11.

Jul a 32 bit
(Intel n on Win32
ri "credits" "license tor "c•re infüW*tion. Let's Know More
print e • a h i '1.1 level.
?ython ia a high Level Lt hat

python'
print ( • i - ' . SWS. 'an- 3.5 Of advanced
S S 10 and S S ZS version cartrtot be used on
Windows XP earlier

versions of Wifidmw

Figure 8.11: Separated Arguments by Commas

Learnimg
Ccnvuierswith KIPS 10
Using IDLE asa calculator

To evaluate an arithmetic expression, it is not neces•ry to use the print() functiom If you type an arithmetic
expression at the Python prompt and press the Enter key, the interpreter automatically evaluates it and shows the
result. In this case* the interpreter ac'ts as a simple calculator. The expressions are evaluated using operators like -

etc. The basic BODMAS rules are followed forperfarmingcalcu lations. Forexamplel

32 bit

copyrighter or moro information.

7.5

Figure 8.12: IDLE as a calculator

I IOLLr you can press Alt4P 10 repeat previous command.

PRACTICE TIME
i. Type fallowing expressions, onc by one* next Lo the Python prompl and mole down the output in lhc Lable
given below:

SNo, Lxpressi0i'l Result

1.

2. (100+58)/3

Wrile lhe slalemenlnexllothe Pylhon logc1Lhe fallowingoutpul:


a. Pylhonworksintwomodcs:lnleraclive mode and Scriplmode„

b. Interprelerisa language processor.

VARIABLES IN PYTHON

If you need to store some food forfuture use, whatwil[ you require? Well you need a container to store the food.
Similarly, when you are working with the values in Python, you require some storage to hold values for later use.
Such storage locationsare known as variables, Avariable can store only one data value at a time. When a new value is

stored in a its previous value gets overwrittem

Leaming
Computers with Kips.
The Assignment Operator
Values are ascigned to variables using n«ignment operator For example* the statement x=25 assigns the value
2S to the variable k

Observe the following codes to understand the use ofassignment operators:

a-IO Value 10 is assigned to the variable a

6=20 Value 20 is a—cigned to the variable b

c=awb t The numbers are added and the value is assigned to the variable c, i.e.. 30 is assigned to the variable c.

a=c-10 f

Rules to write the variable names

There are certain rules in Python which have to be followed to form valid variable names.. The rules for valid

identifier(varia ble name) are:

varia ble name can consistofa Iphabets, digits, and underscore. No other characteris allowed.
APythonkeyword cannotbe usedasavariablename.

NOTE
Avariable name can beofanylenglh.
Variable namesare names).

Examples ofsome valid variable namesare:


emp eode, rtinvalue, Ed 1
Followingare examples of some invalidvariable names:

Variablc Namc Reason


F.mp code Space is not allowed name.
in a variable
10 ende Variable name cannot slant wilh a digil.
is not allowed in a variable name.
Special characters are noc allowed in a variable name.
keyword
'else' is a in Pylh0111* so it cannot be used as a
variable name.

NOTE
If avariablc is being used withoul assigninga value* i.e., if lhc variable is not defined* iL gives an error.

Learning
Co•nvpuiers with
Kips 1
Let's Know More
int A variable is a named
location that
stores the data and whose
value change during
program execution.

.Lnt%;

Figure 8.13: Undefined Vari±le Error

The above code gives an error because the variable x is used in the print() function
without being defined.

WORKING IN SCRIPT MODE


Interactive mode is preferred for small programs, where only a few commands are to be Let's Know More
executed, This is because the output in interactive mode is compressed between the
keyword is a word that
statementsand may create confusion while writing long programs. conveys a special meaning
to the compiler-
For writing lengthy programs in Python* Script mode is used. Using this mode, we can
create and edit Python programs. In this mode, we can save ourfile so that it can be used
later. The complete script is written in an editor, such as a Notepad in Windows.

•1. Create Module/Script/Program File:


Lot's Know More
open IDLE Python
A compiler is a language
Click an the File > New File in [OLE Python Shell as shown in Figure 8.14. processor that converts a
prograr•n written in high-
iii. In the new window that opens, type the commands you want to save as a level language into
machine lar.gnapge and
program asshown in Figure 8.1 S. vice just like an
interpreter in one
single step.

*credit""

Know More
Figure 8.14: Creating New File Figue 8.15: New Window m script is a ptog:ram that
you type in python.

Learning
Cdtnputers with Kips
iv. Click on the File > Save, and save the file with the name 'progl .py' where .py is the extension for Python files.

, CUs

Ite9:46e

B:oü tri

u•me

type

Figure 8.16: Saving a File

2. Run Module/Script/Program File:

After the Python program file is created, you can run the program
by following the given steps: File nun Opttorz 'u'éndcrø,' Help

a-IO Pym-ton hell

Open IDLE Python Shell. b=20 Check Module Ah-X


Pan Module
c=a4b
Pan... Customize Shifters is "
> Click on the File > Open. (If the file is already opened, you Eint ( 't the
can directly follow the next step).

> Click on the Run > Run Module or press F5 key. Figure 8.17: Run

> ttwill executeall the commands you have stored in a separate Python Shell window.

Observe the difference between the Script mode and the Interactive mode as shown in Figure 8.18.

e,' •ptoyl.py - Pylhoo... Python

Etie Ee•t Qpt•ons Eile Edit Shell Qptrcnz delp

a—10 Python 3.7.4 (tags/v3.7.4:e093S!


b=20 (usc v. 1916 32 bit
c=a+b Type "help", "copyright", " cred.
lint ( "t:-s. sum the nu-ll±c-u-s is:" , c) for more information.

RESTART: C:/Users/Dine:
Python/B7/prog1. py
the sum of the nurahezs is: 30
>>>
Scttpt Mode INeracüve Mode

Figure 8.18: Program Output in Interactive Mode

Learnirg
witl Kips 1
PRACTICE TIME
1. Wrileapragramto printthegencral dctailsaboulyourschoolin live lines.
2. Wrilea programtocalculale lhcsumoflwogivennumbers.

DATATYPES
Suppose, you have planned a holiday trip during vacations* and you have to book tickets for your family members,
The first action that yau need to take is to fill a form to get the reservation done, where you need to give your
required details like train number, date of journey, name, age, etc. Here, every piece of data that you enter is of a

specific type; As your name is a String type, age is a numeric type* and date of journey is of date type. Similarly, in

Python* one mustspecify in a program, what kind ofva lues will be stared in a specific variable.

BASIC DATATYPES IN PYTHON

In Python, a data type represents the type of data stored in a variable. The data stored in memory can be of many
types. has various standard data types based on the type of value. For example, a studentß marks are stored
as a numer'icva[uet whereas, his or her address is stored asalphanumeric characters.

The basic data types used in Pyth on are mentioned here:

int (Integer): Represents integral numbers (numbers without any fractional part).There are three types of Integers

in Python:

integer type Description

Integer (inL) stores values in the range of • 2147483648 to 2147483647.

Long Integers (long inl) Support the values lie beyond the range of Integers.

IL represents logical values in lhc form of True and False. In goolean,


Boolean (bool)
O represents False and 1 represents True.

float: Represents floating point values (numbers withfractianal part). The fractional part of a floating point number

may be O as well. Examples of floating point numbersare, 3.14, -486, 180, etc.

Str (String): A String data type represents strings of characters enclosed within single or double quotation marks (i ii

or'"t)•

Examples ofstrings are,' Hetlo% '218" 'Peace', etc.

Some examples of data types in Pyth onare:

S.NO. Value Data Type


15 inl

7.9 noal
Computer Application str

4. bool

Learning
Cotmputers with Kips@
Input() FUNCTION

Input() function is used to accept the value for a variable from the user. To input integer and float values, we can use

int() or float() along with input().

Program 1:

2019,
32 bit on v:-n32
. ht-" "credit.s" "tieenseO • lor more inrornat-ina.
the value:" )
r irsl. vall&t:
the
enter the teccrå value; 300

Figure 8.19: Using Input() function

In Python, input() function takes one string argument. This means that whatever value is being entered by the user,

it will be taken as a string argument.

Program 2:

Python 3.7.' Jul n


on vins:
in tot•nut.ion.
a—input!
enter vol
b-input
enter —t: :

print
200 300

Figure 8-20: Sting

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:

J .7.4 (Laga/v3.'.a:eOSjS9112e, 2019,


32 blt (latel)l oa via32
Typ± •copy r iglit.•, •credit-a* ur i cense ( ) • rur inforn•lion.

can't se.raenc•e by o:

Figure 8.21 : Type Value Error

Here, in this program, when you try to multiply these two values, you get an error in the program. This is because the

strings values cannot be multiplied together.

Learnimg
Computers witl Kips 10
To work with the values provided by the user, Pyttuyt provides a method as discussed in the given exarnpbe•.

Program 4:
' .7.4
eat

D—lnt
enter
aab)
of the 4f-•0

Figure 822 Sun Nurrb«s


Observe. when you use int() function. the values are converted to Éitegers and are added.

Program 5:

't.

t l.zr:t

Figtre 823; Two

Program 6:

Figure 8-24. Area and of a

PRACTICE TIME
t. Oeateaprograrntooculdte stationery.

Z Createa$*ogruninPythontoconvertmiLesintokilomcters.
1 Mde- Kibrneters

toCeåsÅxs.

Cdsius- (Fahrenheit 32)Ä

Features of print() function

> ttconvertsthemessageoranobjectintoastringbefcxewritingitonthescreen.
> tt can have multiple parameters.

tt supports multiple escape sequences to format the output, e.g.. (new iim). It' (tab 9ace). and
(carriage return).

Using separators with print() function


Using operator : When you use operator as the separator among the values, the values Je displayed with a
space between them.

Coenert Kips
Program 7:

t; A.py .

Ådrt Nondc•,•.
Python 3.7.4 Itag5/v3.7.4:e093

• help",

print (a, b, c)

Figure 825: Using Comma Operator Output

Using flit' (tab space): When you use fit' escape sequence as the separatoramong the values, the values are displayed
with a tab space between them.

Program 8:

python
b-20
c-zuu

20

Figme 8.26: Using Escape Sequence Output

Using nvn' (Newline character):

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 function. tin' is a newline character used in Python.

Program 9:

file

(Intel i) on vir02
Type "help—€
c-100
print (a, 20

Figure 8.27: Using Escape Sequence Output

Let us consider another example. Suppose you want to make a program to accept the name, age, and marks of a
student. For this, add the following code in the Python script file:

Program 10:
grr'.

bit on vin::

Input
on same line

eate: age:
cot-ec c 1028:

Figure 8.28: without Sequence Output

Learning
Computers witl Kips 11
Now in the Python script file, add with the inputand printfunction:

Program 11 :

•me-me)
Input
eri"it i
an the rtext line
*'..ø.ai

17

Figure 829: Program with Fscape Sequence Output

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

fiNiECnp
Python wascrcaled byCuido Van Rossum when hcwas working atCcnLrumWtskunde & Informalica (CWI),

Python is a high level language used 10 write codes for lhc computer prograrns.

Interactive is beneficial for Lesling code where you type Lhc commands one at a Lime and get the result or
error immediately.

Script mode is used forwriting lengthy prograrns in Python.


The printo function is used Lo display oulpul of any comma nd on Lhc screen.

Python has various standard dala types based on lhe lypesoi values stored in variables.

Inpul() function is used to accept Lhc value fora variable from the user.

BRAIN
i DEVELOPER

SECTION -A

A. Fill in the blanks.

refers to the grammatical rules to be followed while writing a program in any language.

2. Python '.vas created by

3. menu is generally used to edit the file in use.

4. In the Interactive mode of Python. the instructions are executed giving the output.

5. is a named memory location that stores the data.

6. Python cannot be used as a variable name.

Variable •a
Syntax Guido Van Rossum Line by linc Keyword

Learning
Cognputers with Kips@
B. State True or False.

1. To evaluate an arithmetic expression, it is not necessary to use printo functiom

A variable name can consist of alpha bets* digits, and underscore


3. Ascript is a program that you type in Python.

4. In Pythonf only one type of data can be stored in memory.

5. Print()function is used to accept the value ofa variable from the user.

6. The string values cannot be multiplied together.

7. When we use operatoras the separatoramong the values, the va lues are displayed with a space
between them.

C. Application-based questions.
1. Kritika's computer teacher has given heran assignment to display the names of the fruits separated with a tab
space in Python-Whichseparatorshou[d she usewiththe print() fu nction?

2. Aman is working an his mathematics project work. He has to perform same quick calculations. Which mode of
Python programming should he use fordoing them?

SECTION B -

A. Multiple-choice questions.
1. Which of the following data types is not supported in Python?
a. N umbers b. String c. List

2. When a new value is stored in a variable. its previous value gets


a. Accepted b. Ovenvritten c. Overlapped
3. Values to variables are assigned using the operator.

a. String b. print() c. Assignment


4. The data type for 12.4 should be

a. int b. float c. str

5 To give a tab space while printing the statements you use

c. Tab key
6. The area where you type the code is called

a. Work area b. Worksheet c. Script area

7. print('10'+'2ff) will give the output


a. 30 b. 1020 c. 2010

Learnimg
Ccrnpuiers with 11
B. Answer the following questions.

1. Writeany four features of Python language.

Z What is a variable? Discuss the rules fornaming the variables.

3. Explain the different workingmodes of Python.

4. W/hat are data types? Explain any two data types in Python.

M/hat is the use ofprinr() function? Discuss all the separators used with the print() function.

6. What is an Interpreter? Howis it differentfrom a compiler?

Leaming
Cotmputers with
ASWiVii%Y
SECTION

MY ACTIVITY Learning While Playing

A. Write the outputfor the followingcode of statements.

a. 'Delhi')

b. 'Oclhlff)

c. An', 'Oelhi')

> print(c)

b-'20'

> print(a+b)

f. a—10
b-20
print(a+b)

Rewrite the fol towingstatements after correcting them.

C. Write the following code in the Scriptmode of Python and write the output in thegiven box.
one 1

two 2
three = one two
print(three)

hello "hello"
world = "world't
helloworld = hello + world

print(helloworid)

Learnirvg
Ccm.uiers with Kips 11
LAB SESSION Perfection Through Practice

Cive the output ofthe following commands in the Interactive mode of Python:

2. 4+5/3*8-5
Write the code for the following programs using the Script Mode:

1. Writeaprogramtofindthe
2. It takes 3 hours to drive a distance of 192km on a motorway. Create a program to calculate the average
speed in km/h?

3. Tocalculateand printthecircumferenceandareaofa circle.


4. To input the roll number* name, and marks in five subjects of a student. Calculate the total and
percentage marks ofthe student.

GROUP DISCUSSION For Concept Clarity

Divide the class into two groups and conduct a group discussion on the following topic:
Interactive mode vs Scrip t mode

ONLINE LINKS Looking For More

To know more about programming in Python* visit the following links:


https://www.tutorialspoint.com/python/

https://www.w3schools.com/python/

Learning
Coalputers with Kips@

You might also like