0%(1)0% found this document useful (1 vote) 420 views19 pages7-Introduction To Python
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
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, print 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:
BOD rai water 1. Boil water in a large pan.
2. Add some pasta to the boiling water.
to sam peste 3. Simmer for 10 minutes.
1 spoon olive oit 4, Strain and cool.
1 large chopped onion 5. Add olive oil in a pan.
6. Add the onions and fry gently.
pp gern chopped eociatnes, 7. Stir in the tomatoes and the hummus.
100 gram humus 8. Leave it to simmer for 5 minutes.
9. Add the pasta and mix it. Serve while hot.
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 fs 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 QuestoO
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 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 Cy
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.
Ithas 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 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.Figure 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 a)
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- ens
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.
Python 3.7.4 (tags/v3.7.4:6093591126, Jul 6 9
2) [MSC v.1916 32 bit (Intel)] on win32
type "help", "copyright", "credits" or "license()" for m
ore information,|
019, 19%
Figure 7.3: Python 3.7.4 Shell Window
Kips | Cyber Quest© Components of IDLE Python
Just like any other application window, the IDLE Python screen has the following components:
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul @ 2019, 19:29
222) [MSC v.1916 32 bit (Intel)] on win32
‘Type "help", "copyright", "credits" or *license()" for m
Promet_Jore information.
we at ~
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 fs used to work with the options related to the currently used
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
exiting the application.
The Edit Menu
This menu is generally used to edit the file in use. You can i)
cut, copy, or paste the selected text. You can also search for a
particular text or phrase, and even replace it with some other,
text. ie
Figure 7.6: Edit Menu
The Help Menu
To get help related to any topic of Python, press the F1 key or click on
the Help menu.
Command Prompt
The command prompt is denoted by ‘>>>’. This is the area where you
type a code.
cI)
‘About IDLE
IDLE Help
Python Docs FI
Tuttle Demo
Figure 7.7: Help Menu.
Cyber Quest | KiesStatus 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-line, 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:
dstwny Gone >»>
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.
Neon
The Interactive mode is useful for testing code where you type the
commands, one at a time, and get the result or error immediatel
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.
Kis | Cyber Quest.
"You can press the FA
to use Python Help.
‘The Python int
Development and
Learning Environm
IDLE) executesFor example:
>>>print ("Hello World") will display Hello World
Python 3.7.4 (tags/v5.7.47e09359112e, Jul 6 2019, 19:29:22) (MSC v.1916 32 bit
(intel) | on win32
‘neip", "eopyright®, "eredits” or *1icense()* for more information,
>> print (erie word")
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.
Python 3.7.4 (tage/v3.7.420093591120, Jul 8 2019, 19:29:22) (MSC v.1916 32 bit
(intel) } on win32
lzype "help, "copyright", "credits" or *1iconse()* for more information,
P>> print ("fython is « Bigh Tevel Tanguage
Jpytnon is a high level language Tt has easy’ syntax
p>> print ("aoesc=, 10456)
frovse= 66
b> print (*10*0-80+20+2/10-", 10¥8-50+30%2/10)
foss'so+30*2/10- 36.0
bs> peine('s plus 5 =*,5¢5, ‘and $ into $ =, 5*5)
f puke 8 aovand 8 into #28
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. Fyeton 17.4 (eags/.7. tress, val 9 2008, 18298
Ifyou type an arithmetic expression at the type "help", "copyright™, credits" or "ticense()" for mo
see
Python command prompt and press the |)
Enter key, the interpreter automatically p.5 a
LSS ere
evaluates it and shows the result. In this |:
case, the interpreter acts as a simple isu.)
calculator, The expressions are evaluated 2!
using operators, like +, -, *, /, etc. The
basic BODMAS rules are followed for
performing calculations.
Figure 7.10: IDLE as a Calculator
92 Joe . ae . Cyber Quest | Kips= 23°98
= (100+58)/3
.. 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.
'® Interpreter is a language processor.
© 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:
Nery Dean Ta)
# Value 10 is assigned to the variable a.
b=20 # Value 20 is assigned to the variable b.
# 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,
20, and not 10.
ios | Cyber QuestRules 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 underscore (_ ).
* Avariable name can consist of letters, digits, and underscore. No other character is
allowed.
Akeyword cannot be used as a variable name.
Avariable 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, age1980, a45r
Examples of some invalid variable names are:
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.
ABCaltd 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.
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 «is used in the print() function without
being defined.
= 9, "
Se sp al i
Figure 7.11: Undefined Variable Error
= 94 oe oa 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.
esa ie lt Ca AN,
eating New File Figure 7.13: Editor Window
‘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 'progt.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:
plete a a
Figure 7.14: Saving a File
‘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 QuestoO
+ The output will be generated on the Python Shell window.
Fle Est Format Run Options Window Help
0 Python She
0 Check Module
c=atb
peineerthe a ee
Figure 7.18: Run Module
Observe the difference between the Script mode and the Interactive mode as shown in
Figure 7.16.
Ble fst farmat fan Optens neon tp [Be tat Shel Deg Goton Window Hp
jaslo- SSS Ptnon 3.74 (tags /v3.7. 4200935)
be20 19:29:22) [msc v.1916 32 bit (1!
crab ‘Type "help", "copyright", "cred!
print ("the sum of the numbers is:", c) ||fF more information.
RESTART! C2,
Python/B7/prog:
os
dace CaiceoMe ty
11. Write a program to print the general details about your school in five tines.
2. Write a program to calculate the sum of two given numbers.
® 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 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, 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.
196 — - Cyber Quest | KiesThe basic data types used in Python are mentioned here:
int (integer): It represents integral numbers (numbers without any
fractional part). There are three types of integers in Python:
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.
Boolean (bool) It represents logical values in the form of True
or False. In Boolean, 0 represents False and 1
represents True.
float: It represents floating point values (numbers with fractional
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:
79
Computer Application
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 serigtisa program
with the input() function. |_youtype in Python.
Kips | Cyber Questfoe ey ote er
python 3.7.4 (tags/v3.7-4:e083551126, Jul 8 2019, 19:28:22) (WSC v.1516
32 bit (intel)] on wind2
[type “neip", “copyeignt", “creaits™ or "license()" for more information.
Soe aeinpue enter tne FEE val
>>> beingut (enter the second valve:*)
eter tm second valu: 30
Figure 7-47: 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:
Figure 7.11
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:
foe fat She Opens ne
python 3.7.4 (tags/v3.7.4ze083501126, Jul 6 2019, 19:29:22) [MSC V.I9I6
32 bit Cinte1)} on winse
[type “help, "copyright", "credits" or "license()" for more information.
>>> aninput ("enter the cirst val
Jonter the first value: 200
>>> einput (Tenter th
Jenter the second valt
Ss" print (arb)
File "cpyshell#2>", Line 1, in
print a*b)
rypoError: can*t multiply sequence by non-int of type ‘str’
| Figure 7.419: 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:Program 4:
ibython 3.7.4 (tags/v3.7.4:e093591i26, Jul 8 2019, 19:28:22) (MSC v.181¢
icense()" for more information
”
fenter the second number: 300
>> print ("the sum of the numbers is:*, a+b)
fone fim of the numbers 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:
arint (input ("enter the value of ai*)) [ated oe
Deine input enter the Yaltie of B:")) Ke acat, Menedat or Scisaty*
abe,
ipHint ("value of 2 after svaping:*,a)
Prine(*value of 6 after swaping:",)
Figur 7.21: Swapping Two Numbers Output
Program 6:
pene Reasons ta | Beare
Figure 7.22 Area and Perimeter of «Square Output
dCs
4. Create a program to calculate 5% discount on the total purchase of stationery.
2. Create a program in Python to convert miles into kilometres.
1 Mile = +6 kilometres
3. Create a program to convert temperature from Fahrenheit to Celsius.
Celsius = (Fahrenheit - 32) « 5/9
© Using print() Function
“> The print() function is used to print a message or value.
+ It converts the message or an object into a string before writing it on the screen.
© It can have multiple parameters.
*
It supports multiple escape sequences to format the output, for example, ‘\n’ (new line),
‘\t' (tab space), and ‘\r' (carriage return).
Kips | Cyber QuestUsing separators with print() function
Using (,) operator: When you use
displayed with a space between them,
Program 7:
Hle_f6t Format fun Options Window He
‘a=10
b=20
c=100
pe (a,b,c)
Figure 7.23: Using Comma Operator
operator as a separator among the values, the values are
cereal
[Python 3.7.4 (tags/v3.7.47e083¢
Gntel)} on win32
‘type help", "copyright", “cre
ee
10 20 100
jusers/D|
Output
Using tab space (\t'): When you use ‘\t' escape sequence as a separator among the values, the
values are displayed with a tab space between them.
Program 8:
Es at Fema Be ore Howe bey
a=i0
20
e=i00
print cay"\e" b,\e*ye
Figure 7.24: Using ‘t' Escape Sequence
(Be fat Sp Deng Goten nto ey
Python 3.7.6 (tags/v3.7.
32 bit (intel)] on win?
‘Type "help", “copyright™, “cr
93
sanene RESTART: C2 /Users/Di|
fo 2109]
‘Output
Using newline character (‘\n’): A newline character in Python is used to end a line and start
anew line. In Python, the new line character can be used with the input() function and with
the print() function. The ‘\n’ is a newline character used in Python.
Program 9:
print (a, "\n",b,
Figure 7.25: Using "w’ Escape Sequence
[python 3.7.4. (eage/W3-7-4se08358112
(intel) oa win
[fvpe "help", "copyright", “credits’
RESTART: C:/Users/Dinest
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:
Cyber Quest | Kipser pytan 3.7.4" (eage/v3-7-47 6099581120)
Bicactsater vere sent Sz bit. Gatet}} on winde
eee - type *nelpt, *copyrigne*, “ereaizo" {
Jclassminput (enter your cl Be
pane)
age)
class)
enter four ele
Figure 7.26: Program without Output
Escape Sequence
Now, in the Python script file, add ‘\n' with the input and print function:
Program 11:
Figure 7.27: Program with
Escape Sequence
In the above output window, in order to give a better understanding, the text and values are
placed one after another.
+ Python is a high-level language, used to write codes for the computer programs.
Python was created by Guido van Rossum when he was working at Centrum Wiskunde
and Informatica (CWI).
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 for 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.
The input() function is used to accept the value for a variable from the user.
ios | Cyber Quest = 101ee
—
A, Fill in the blanks, e
1. Python was created by ..
The
key is pressed to execute a Python program.
In the interactive mode of Python, the instructions are executed
A
is the name of the memory location that stores the data.
Se is pp
Python
B. Write T for True and F for False.
-annot be used as a variable name.
1. To evaluate an arithmetic expression, it is not necessary to use the print() function. (__]
Avariable name can consists of letters, digits, and underscore.
In Python, data types represent the type of data stored in a variable.
In Python, only one type of data can be stored in memory.
OO000
2.
3,
4,
5. The print() function is used to accept the value of a variable from the user.
6. The string values cannot be multiplied together.
¢
. Application-based questions,
1. Kritika’s computer teacher has given her an assignment to display the names of fruits separated
with a tab space in Python. Which separator should she use with the print() function?
2. Aman is working on his mathematics project work. He has to perform some quick
calculations. Which mode of Python programming should he use?
D. Select the correct option. eo
1. Which of the following data types is not supported in Python?
a. char b. float c. int
102) . Cyber Quest | Kies2. When a new value is stored in a variable, its previous value gets ..
a. Accepted b. Overwritten c. Overlapped
3. Values are assigned to variables using the .. operator.
a. String b. print() cc. Assignment
4, The data type for 12.4 should be
a. int b. float c. str
5. >>> 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.
5. What is the use of print() function?
Kips | Cyber Quest 10:6. Discuss the rules for naming the variables.
7. Discuss any two separators used with the print() function.
Pam
HZ Learning While Playing £23
‘A. Write the output for the following statements.
1, >>>print(‘India’, ‘Delhi')
2. >>>print("India', '\t', 'Delhi')
3. >>oprint(‘India’, ‘\n", 'Delhi')
4. >>>a=10
>>>b=20
>>oe=(atb)*4
>>>print( c)
5. >>> a='10"
>>> be'20"
>>> print(atb)
6. >>> a=10
>>> be2@
>>> print(atb)
B. Find the errors and rewrite the following statements after correcting them.
1. >>2102c
2. >>>Print( ‘India’ )
3. >>>Print (age)
Cyber Quest | Kips_—
4. >>asle
>>>b=20
>ooatb=
>>>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 =
helloworld = hello +" " + world
‘world"
print (helloworld)
‘A. Execute the following statements in the interactive mode of Python.
1, po 23.14°5
2, >9>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.
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.
Eo Rasy ror Ce Clarity
Discuss the following topic:
+ Interactive mode vs Script mode
‘To know more about Python, visit the following websites:
+ https: //www.tutorialspoint.com/python/
+ https://www.w3schools.com/python/