cmePle,
QD Introduction to Python
LEARNING OUTCOME:
The student will be able to:
know about Python and its features. |
install Python and identify the components of Python window. |
work with Interactive mode and Script mode.
use different data types, 4
|
|
| int and input functions.
Have you ever tried making pasta on your own? Figure 7.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 the ingredients
(input) to make tomato pasta (output).
Recipe for Tomato Pasta
__ List of required ingredients: Instructions to make Tomato Pasta:
1. Boil water in a large pan.
Add some pasta to the boiling water.
‘Simmer for 10 minutes.
Strain and cool.
‘Add olive oil in a pan.
‘Add the onions and fry gently.
Stir in the tomatoes and the hummus.
Leave it to simmer for 5 minutes.
‘Add the pasta and mix it. Serve while hot.
500 ml water
150 gram pasta
1 spoon olive oil
1 large chopped onion
300 gram chopped tomatoes
100 gram humus
yeneyaen
Figure 7.1: Making Tomato Pasta
‘Adding all the required ingredients to the recipe is the input. Simmering, straining, and stirring
the ingredients is the process, and the product that you get after processing is the output,
which is the 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 (process), and the desired result
is obtained (output).
Kips | Cyber QuestTo 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 a
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 isa 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 & Informatica (CWI),
which is a National Research Institute for Mathematics and Computer
Science in Netherlands. The language was 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 general-purpose high-level programming language.
It is a platform independent programming language, which means it can be used on any
machine and in any operating system.
© [thas a simple syntax.
“Python is a case-sensitive language.
It isan 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 following:
* Build a website ® Develop games
Program robots Perform scientific computations
Develop artificial intelligence based applications
® Installing Python
Python can be easily installed on your computer by following the given steps:
To download Python, visit the site: www.python.org/downloads and click on the Download
Python button under ‘Download the latest version for Windows’. You will get an .exe file.
Cyber Quest | KisFigure 7.2: Downloading Python
Double-click on the exe file. Click on Run or Install Now in the
dialog box, to start the installation. Keep following the instructions | ))
to install Python.
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-
click on the .exe file and select the Run or Install Now option.
®) Getting Started with Python
After installing Python, you can start with any of the following two
modes:
Interactive mode
Script mode
The Interactive mode is the default mode. To launch the in Interactive
mode, click on Start > Scroll down to Python 3.7 > IDLE (Python 3.7).
The IDLE screen appears as shown in Figure 7.3.
Be Be Bley Gm Bee
python 3.7.4 (tags/v3.7.4:609359112e, Jul 8 2019, 19:29
222) [MSC V.1916 32 bit (Intel)] on win32
‘Type “nelp", "copyright", "credits" or “license()" for m
lore information
>>
Ean
Figure 7.3: Python 3.7.4 Shell Window© Components of IDLE Python
Just like any other application window, the IDLE Python screen has the following components:
EB Se) Ban) Grew ner
Python 3.724 (tags/v3.7.4:e093591120, Jul 6 2019, 19:29
:22) [MSC v.1916 32 bit (Intel)] on win32
Command) zype "help", "copyright", "credits" or "license()" for m
Prompt _Joxe information.|
>>>,
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.
The File Menu
This menu is used to work with the options related to the currently used Scene“
file. It includes sub-options, like opening a new file, opening an existing #*"
file, viewing recently used files, saving the files, closing the files, and EiGiyu. Stam
exiting the application. =
The Edit Menu Figure 7.5: File Menu
: : : | Shall Debug Option Window Hel
This menu is generally used to edit the file in use. You can “uns EGaens) hz
cut, copy, or paste the selected text. You can also search fora". EIS
i it wit Ctalex
particular text or phrase, and even replace it with some other Cony et
text. Paste cue
sone a aia
igure 7.6:
The Help Menu Figure 7.6: Edit Menu
Help [ep nen) |
To get help related to any topic of Python, press the F1 key or click on >
the Help menu. ie
IDLE
IDLE Help,
Python Docs FI
Turtle Demo
The command prompt is denoted by >>>". This is the area where you Figure 7.7:
type a code.
Command PromptStatus Bar
‘The Status bar tells you the current status of your control or cursor on
the window.
® Working in Interactive Mode
in the Interactive mode of Python, the instructions are executed, line-
by-tine, giving the output.
In this mode, the commands are typed next to the Python Command
prompt (>>>). For example, if you type 3+6 next to the Python prompt,
it will give you the result as 9.
To work in the interactive mode, follow the process given:
dstvnyG Zone » >
Visit the lab and follow the given steps to get familiar with the Interactive
mode.
© Click on Start > Python 3.7 > IDLE (Python 3.7). It will open the Python
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.
Ere 14 ener 7cegutsize, Jet #2018, 18
Tipe “else, senyeiohe,
redite” or “Iisense()* for more Sntorm
The Interactive mode 1s useful for testing code where you type the
commands, one at a time, and get the result or error immediately.
Printing a Message
The print( ) function is used to display the output of any command on
the screen. It can also be used to print the specified messages.
Kips | Cyber Quest
can press the FL
use Python Hel
earns
1e Python integrated
Development and
Learning Environment
(IDLE) executes
91.PUA.
For example:
>>>print ("Hello World") will display Hello World
Python 3.7.4 (tags/v3.7-42@09359112e, Jul 8 2019, 19:26:29) [MSC v.1916 32 bit
(intel) } on wins2
‘type “heip", "copyright", "credits" or "license()" for more information.
p> print (Tr
Lip Moria
Figure 7.8: Using print() Function
Python 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 and
not a command.
You can also pass more than one argument to the print () function. In such a case, the
arguments are separated by commas, as shown in Figure 7.9.
3.7.4 (tags/v3.7.47e05959112e, Jul & 2019, 19:29:22) [wSC v.1916 32 bit
(intel) } on winsz
90480"2/106", 20*8-80#30"2/10)
36.0
>> print C10"
Hlos~s0rs0%2/1.
>> print ("5 plus 5 =',5#5, ‘and 5 into 9 =, 45)
ease eels
Figure 7.9: Separated Arguments by Commas
Using IDLE as a Calculator
To evaluate an arithmetic expression, it is
not necessary to use the print() function.
If you type an arithmetic expression at the
Python command prompt and press the
Enter key, the interpreter automatically
evaluates it and shows the result. In this
case, the interpreter acts as a simple
calculator. The expressions are evaluated
using operators, like +, -, *, /, etc. The
basic BODMAS rules are followed for
performing calculations.
[eS De con Ores me
python 3.7.4 (tags/v3,
(intel) on wins2
\Bype "help", “copyright”, “credits” or "License()" for nor
>> 0820
2
93551126, Jul 8 2019, 19:
92 Cyber Quest | Kips:In IDLE, you can press Alt+P to repeat the previous command.
Practice Time
Type the following expressions, one-by-one, next to the Python prompt and note down the output in the)
table given below:
SNo. Expression Result,
a 23°98
2. (100+58)/3
2. Write the statement next to the Python prompt using the print( ) function to get the following output: |
© Python works in two modes: Interactive mode and Script mode.
«neu aa J
5S Variables in Python
If you need to store some food for future use, what will you require? Well, you will need a
container to store the food. Similarly, when you are 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. A variable can store only
one data value at a time. When a new value is stored in a variable, its previous value gets
overwritten.
Assigning Values to Variables
Values are assigned to variables using the assignment operator (=). For example, the statement
x=25 assigns the value 25 to the variable x.
Observe the following codes to understand the use of the assignment operators:
a=10 _# Value 10 is assigned to the variable a. |
b=20 | # Value 20 is assigned to the variable b. |
—$—$§ —____ ee |
cearh _# The numbers are added and the value is assigned to the variable c, i.e., 30 is assigned
to the variable c,
|# Value 20 (30-10) is assigned to the variable a. So, now the value of the variable a is
), and not 10.
|arc-torules for valid identifier (variable name)
& Avariable name must start with an alphabet (capital or small) or an underscore ( _)-
4 Avariable name can consist of letters,
allowed.
°
%
Variable names are case-sensitive (e.
Examples of some valid variable names are:
Class, emp_code, totsalary,
Rules to Write the Variable Names
There are certain rules in Python that have
‘Akeyword cannot be used as a variable name.
‘variable name can be of any length.
Examples of some invalid variable names are:
to be followed to form valid variable names. The
are:
digits, and underscore. No other character is
g., Age and age are different variable names).
minvalue, bal_fee, age1980, a45r
Employee code space is not allowed in a variable name.
tocode Variable name cannot start with a digit.
A.B.C. Ltd (is not allowed in a variable name.
‘ABCaltd special characters are not allowed in a variable name, a
else “else’ is a keyword in Python, so it cannot be used as a variable name. 7
if a variable is being used without assigni
error.
The following code gives an error becau'
being defined.
ing a value, ‘.e., if the variable is not defined, it gives an
se the variable x is used in the print() function without
Undefined Variable Error© 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.
print ("the sum of the numbers
Figure 7.12: Creating New Filo
* In the new window that opens, type the
commands you want to save as a program as
shown in Figure 7.13.
* Click on File > Save, and save the file
with the name ‘progi.py’ where .py is the
extension for Python files.
Running Module/Script/Program File
After the Python program file is created, you can
run the program by following the given steps: Figure 744: Saving a Fils
Open IDLE Python Shell.
‘Click on File > Open. (if the file is already opened, you can directly follow the next step).
“Click on Run > Run Module or press F5 key.
It will execute all the commands.
Kips | Cyber QuestFile Edt Format fn, Options Window Help
a=10 | Python Shell
p20, Check Module AB
c=atb
pene (rene! Bit Cosemized StS
is", |
Figure 715: Run Module
observe the difference between the Script mode and the Interactive mode as shown in
Figure 7.16.
Te Se} Debog Gptens don Hp |
python 3.7.6 (tags/¥3.7.4220535)
1:29:22) (usc v.1916 32 bit (Zi
lnype “help", “copyright”, “cred
for more information.
[Sncnace= RESTART: Cz /Users/Dine:
python 81 (Pog Py
python 87 (Peg eloces is? 20
=
c=atb
peer sum of the nutbers
|
|
| |
Figure 7.16: Program Output in Interactive Mode
[oierar seit)
‘._ 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.
Saree
® Data Types
suppose, you have planned a holiday trip during vacations, and you have to Book tickets
for your family members. The first action that you need to take is to fila 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 te a5 Your
ame is a string type, age isa numeric type, and date of journey is of date type. Similariy, you
have to specify in a program, what kind of values will be stored in a specific variable.
Basic Data Types 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. Python has various standard data types based on the type
of value. For example, a student's marks are stored as a numeric value, whereas, his or her
address is stored as alphanumeric characters.
cyber Quest | MrsThe basic data types used in Python are mentioned here:
{int (integer): It represents integral numbers (numbers without any
_ Avariableisanamed |
fractional part). There are three types of integers in Python: eed
“stores the data and whose
Integer (int) It stores values in the range of — 2147483648 to oven senian
2147483647.
Long Integers (long int) It supports the values that lie beyond the range
of integers.
Boolean (bool) It represents logical values in the form of True
or False. In Boolean, 0 represents False and 1
represents True. :
‘Keywords are the reserved
float: It represents floating point values (numbers with fractional Se teem
part). The fractional part of a floating point number may be 0 as well.
Examples of floating point numbers are 3.14, ~48.6, 18.0, etc.
str (string): A string data type represents strings of characters enclosed
within single or double quotation marks ('' Or").
Examples of strings are ‘Hello’, “Myname’, '218', ‘Peace’, etc.
Some examples of data types in Python are:
15 int
79 float so 0
‘Computer Application) str |
[PoP 75328 "| bool =| gC
een
‘A compiler isa language
‘processor that converts
‘2 program written in
high-level language into
‘machine language, and
versa, just ke
ter but in one
You can assign a multiline string to a variable by
using three quotes (" “).
For example:
a="Adata type represents the type of data stored
ina variable. The data stored in memory can be of
many types.
® Using input() Function
The input() function is used to accept the value for a variable from the
user. To input integer and float values, you can use int() or float() along a serine ina program that |
with the input() function. you type in Python.
Kips | Cyber QuestProgram 1:
Des anes Unen ee =
4s008950112e, Jul © 2019, 19:29:22) [se v.1916
ses" of “License()" for more information.
>> aeinpue eater the first values)
Jonter the first value: 200
[S>> beinput (Yenter the second value:
ser te eecond values 900
”
Figure 7.17: Using input() Function
In Python, the 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:
ae
ion
Ne RSeyright”, “eragite’ or “Iicense” for wore information.
mie(renter she fist values")
ofthe Fs valuer200
Sep Anpath: tacond values”
er" the second veiue:S00, :
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:
a
python 3.7.4 (tags/v3.7.4:e09359112e, Jul § 2019, 19:28:22) (Msc v.1916
32 bit (ntel)] on wina
[type "help", "copyright", "credits" or "License()" for more information.
>>> asinput (enter the first value:")
Jenter the first value: 200
p>> Beinput ("enter the second values")
Jonter the second value: 300
Eaceback (nost_fecent call Test}?
File
", Line 1, in
print (arb)
yypebrrort 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 discussed in the
given example:
Cyber Quest | KipsProgram 4:
le Est Se Dehog Orton ndow Hp
python 3.7.4 (tags/v3.7.4:e09359112e, gul @ 2019, 19:29:22) [msc v.191
32 bit (intel)} on win32
lnype “help”, right", "credits" or “license()" for moze information,
pub anintiiapur teeter the first aambere"T)]
Jp>> beint (input ("Enter the second nunber:"))
lsnter the second number: 300
fp>> print ("zne sum of the munbers is:", arb)
Icke sum of the numbers is: 400
Figure 7. ‘of Numbers.
Observe, when you use int() function, the values are converted to integers and are added.
Program 5:
Jbxint Ginpat
ba
print (rvaiee of after owaping:tsad
prince b after svaping?">> print('10+'20/) will give the output ...
a. 30 b. 1020 c. 2010
E. Answer the following questions.
1. Write any three features of the Python language.
2. What is a variable?
3. Explain the different working modes of Python.
4, What are data types? Explain any two data types in Python.
What is the use of print() function?
Ses | Cyber Quest ~ 103,6. Discuss the rules for naming the variables.
7. Discuss any two separators used with the print() function.
HDZGiinae Learning While Playing a2?
A. Write the output for the following statements.
1. >>>print("India’, "Delhi") aa
>>>print(‘India', '\t', "Delhi")
2.
3. >>oprint(‘India’, ‘\n", ‘Delhi')
4.
>pra=le
>>>b=20
>>>c=(atb)*4
>>>print( c)
5. >>> a="10"
>>> b='20"
>>> print(atb)
6. >>> a-10
>>> b=2@
>>> print(a+b)
B. Find the errors and rewrite the following statements after correcting them.
1. >>>10=¢ Tc
2. >>>Print( India‘)
3. >>»Print(age) &>>raale f )
} |
voobe20 | |
>>vatb=c |
>>>print(c) \echhegenaa Bes.
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
|
|
Ee
print(helloworld)
LAB SESSION Perfection Through Practice
A. Execute the following statements in the interactive mode of Python.
1. so 283.1485
2, v9>445/3°8-5
B, Write the code for the following programs in the Script mode.
1. Write a program to find the product of two numbers x and y, where x=150 and y=200.
2. It takes 3 hours to drive a distance of 192 km. Create a program to calculate the
average speed in km/h?
3. Create a program calculate and print the circumference and area of a circle.
4, 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
Discuss the following topi
+ Interactive mode vs Script mode
Looking For More
To know more about Python, visit the following websites:
+ https://www.tutorialspoint.com/python/
+ hittps://www.w3schools.com/python/
=
ips | Cyber Quest