KEMBAR78
Chapter-5 (Getting Started With Python) | PDF | Data Type | Reserved Word
0% found this document useful (0 votes)
12 views21 pages

Chapter-5 (Getting Started With 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, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views21 pages

Chapter-5 (Getting Started With 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, TXT or read online on Scribd
You are on page 1/ 21

CHAPTER -5

GETTING STARTED WITH PYTHON


Introduc on to python

We have wri en algorithms for different problems in Chapter 4. Let us now move a step further
and create programs using any version of Python 3. But before learning about Python programming
language, let us understand what is a programming language and how it works.
An ordered set of instruc ons to be executed by a computer to carry out a specific task is
called a program, and the language used to specify this set of instruc ons to the computer is
called a programming language.
As we know that computers understand the language of 0s and 1s which is called machine language
or low- l e v e l language. However, it is difficult for humans to write or comprehend instruc ons
using 0s and 1s. This led to the advent of high-level programming languages like Python, C++, Visual
Basic, PHP, Java that are easier to manage by humans but are not directly understood by the
computer.
A program wri en in a high-level language is called source code. Recall from Chapter 1
that language translators like compilers and interpreters are needed to translate the source
code into machine language. Python uses an interpreter to convert its instruc ons into
machine language, so that it can be understood by the computer.
Features of Python

 Python is a high level language. It is a free and open source language.


 It is an interpreted language, as Python programs are executed by an interpreter.
 Python programs are easy to understand as they have a clearly defined syntax and
rela vely simple structure.
 Python is case-sensi ve. For example, NUMBER and number are not same in Python.
 Python is portable and pla orm independent, means it can run on various opera ng
systems and hardware pla orms.
 Python has a rich library of predefined functions.
 Python is also helpful in web development. Many popular web services and applica ons are
built using Python.
 Python uses indenta on for blocks and nested blocks.
Working with Python
To write and run (execute) a Python program, we need to have a Python interpreter installed on our
computer or we can use any online Python interpreter. The interpreter is also called Python shell.
In the above screen, the symbol >>> is the Python prompt, which indicates that the interpreter
is ready to take instruc ons. We can type commands or statements on this prompt to execute
them using a Python interpreter.
Execu on Modes
There are two ways to use the Python interpreter:
Interac ve mode
Script mode
Interac ve Mode: Interac ve mode allows execu on of individual statement instantaneously.
we can simply type a Python statement on the >>> prompt directly. As soon as we press enter, the
interpreter executes the statement and displays the result(s), as shown in Figure

Working in the interac ve mode is convenient for tes ng a single line code for instant execu on.
But in the interac ve mode, we cannot save the statements for future use and we have to retype
the statements to run them again.
Script mode: Script mode allows us to write more than one instruc on in a file called Python
source code file that can be executed.

 In the script mode, we can write a Python program in a file, save it and then use the
interpreter to execute it.
 Python scripts are saved as files where file name has extension “.py”.
 By default, the Python scripts are saved in the Python installa on folder.
 While working in the script mode, a er saving the file, click [Run]->[Run Module] from the
menu as shown in Figure.
Python source code file
Execu on of Python in Script mode using IDLE

Output of a program executed in script mode

Python Keywords:
Keywords are reserved words. Also known as pre-defined word.
Each keyword has a specific meaning to the Python interpreter, and we can use a keyword in our
program only for the purpose for which it has been defined.
As Python is case sensitive, keywords must be written exactly as given in Table.

False class finally is return


None continue for lambda try
True def global not with
and del if or yield
as elif from nonlocal while
assert else import pass
break except in raise

Identifiers:
Name given to programming element known as Identifier.
In programming languages, identifiers are names used to identify a variable, function, or other
entities in a program.
The rules for naming an identifier in Python are as follows:

 The name should begin with an uppercase or a lowercase alphabet or an underscore sign
(_). This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore
(_). Thus, an identifier cannot start with a digit.
 It can be of any length. (However, it is preferred to keep it short and meaningful).
 It should not be a keyword or reserved word given in keyword Table.
 We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
Variables
A variable is basically a named storage location in a program that holds data, which can change
(or “vary”) while the program is running.
In Python we can use an assignment operator to create new variables and assign specific values
to them.
Example:
gender = 'M'
message = "Keep Smiling"
price = 987.9

Comments
comments are lines in a program that are not executed by the interpreter.

 They are added with the purpose of making the source code easier for humans to
understand.
 In Python, a comment starts with # (hash sign). Everything following the # till the end of
that line is treated as a comment and the interpreter simply ignores it while executing the
statement.

Types of Comments in Python


Single-line comments

 Begin with a # symbol.


 Everything after # on that line is ignored by Python.
Example:
# This is a single-line comment
print("Hello World") # This prints a message
Multi-line comments

 Python doesn’t have a special syntax for multi-line comments.


 Commonly, we use triple quotes (''' or """) to write multi-line comments.
'''
This is a multi-line comment.
It can take multiple lines.
Useful for explaining large sections of code.
'''
print("Hello Python")

Data Types

 Every value belongs to a specific data type in Python.


 Data type identifies the type of data values a variable can hold and the operations that
can be performed on that data.

Number
Number data type stores numerical values only. It is further classified into three different types:
int, float and complex.
Type/ Class Description Examples

int integer numbers –12, –3, 0, 125, 2

float real or floating point numbers –2.04, 4.0, 14.23

complex complex numbers 3 + 4j, 2 – 2j

Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of two
constants, True and False. Boolean True value is non-zero, non-null and non-empty. Boolean
False is the value zero.
Example >>> var1 = True
>>> num1 = 10 >>> type(var1)
>>> type(num1) <class 'bool'>
<class 'int'>
>>> float1 = -1921.9
>>> num2 = -1210 >>> type(float1)
>>> type(num2) <class 'float'>
<class 'int'>
>>> var2 = -3+7.2j
>>> type(var2)
<class 'complex'>

Variables of simple data types like integers, float, boolean, etc., hold single values. But such
variables are not useful to hold a long list of information, for example, names of the months in a
year, names of students in a class, names and numbers in a phone book or the list of artefacts in
a museum. For this, Python provides data types like tuples, lists, dictionaries and sets.
Sequence

 A Python sequence is an ordered collection of items, where each item is indexed by an


integer.
 The three types of sequence data types available in Python are Strings, Lists and Tuples.
String

 String is a group of characters. These characters may be alphabets, digits or special


characters including spaces.
 String values are enclosed either in single quotation marks (e.g., ‘Hello’) or in double
quotation marks (e.g., “Hello”). The quotes are not a part of the string, they are used to
mark the beginning and end of the string for the interpreter. For example,
>>> str1 = 'Hello Friend'
>>> str2 = "452"
List
 List is a sequence of items separated by commas and
 the items are enclosed in square brackets [ ].

#To create a list


>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
Tuple

 Tuple is a sequence of items separated by comma and items are enclosed in parenthesis (
).Once created, we cannot change the tuple.
Example :
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a') #print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')

Set
Set is an unordered collection of items separated by commas and the items are enclosed in curly
brackets { }. A set is similar to list, except that it cannot have duplicate entries. Once created,
elements of a set cannot be changed.
#Create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))

<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set
>>> set2 = {1,2,1,3}
>>> print(set2)
{1, 2, 3}

None
None is a special data type with a single value. It is used to signify the absence of value in a
situation. None supports no special operations, and it is neither same as False nor 0 (zero).
Example :
>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None
Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard mapping
data type in Python called dic onary.
Dictionary
Dic onary in Python holds data items in key-value pairs. Items in a dic onary are enclosed in curly
brackets { }. Dic onaries permit faster access to data. Every key is separated from its value using
a colon (:) sign. The key: value pairs of a dic onary can be accessed using the key. The keys are
usually strings and their values can be any data type. In order to access any value in the
dic onary, we have to specify its key in square brackets [ ].
#Create a dic onary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120
Mutable and Immutable Data Types

 Variables whose values can be changed a er they are created and assigned are called
mutable.
 Variables whose values cannot be changed a er they are created and assigned are called
immutable. When an a empt is made to update the value of an immutable variable, the old
variable is destroyed and a new variable is created by the same name in memory.

OPERATORS
An operator is used to perform specific opera on (mathema cal or logical) on values.

Arithme c Operators
Python supports arithme c operators that are used to perform the four basic arithme c
opera ons as well as modular division, floor division and exponen a on.
Arithme c Operators in Python

Operator Operation Description Example


+ Addition Adds the two numeric values on >>> num1 = 5
either side of the operator
>>> num2 = 6
This operator can also be used to
>>> num1 + num2
concatenate two strings on either
side of the operator 11

>>> str1 = "Hello"

>>> str2 = "India"

>>> str1 + str2

'HelloIndia'

- Subtraction Subtracts the operand on the right >>> num1 = 5


from the operand on the le
>>> num2 = 6

>>> num1 - num2

-1

* Multiplication Mul plies the two values on both >>> num1 = 5


side of the operator
>>> num2 = 6

>>> num1 * num2

30

Repeats the item on le of the >>> str1 = 'India'


operator if first operand is a string
>>> str1 * 2
and second operand is an integer
value 'IndiaIndia'

/ Division Divides the operand on the le >>> num1 = 8


by the operand on the right and
>>> num2 = 4
returns the quo ent
>>> num2 / num1
0.5

% Modulus Divides the operand on the le >>> num1 = 13


by the operand on the right and
>>> num2 = 5
returns the remainder
>>> num1 % num2

// Floor Division Divides the operand on the le >>> num1 = 13


by the operand on the right and
>>> num2 = 4
returns the quo ent by removing
the decimal part. It is some mes >>> num1 // num2
also called integer division.
3

>>> num2 // num1 0


** Exponent Performs exponen al (power) >>> num1 = 3
calcula on on operands. That is,
>>> num2 = 4
raise the operand on the le to the
power of the operand on the right >>> num1 ** num2

81

Rela onal Operators


Rela onal operator compares the values of the operands on its either side and determines the
rela onship among them. Assume the Python variables num1 = 10, num2
= 0, num3 = 10, str1 = "Good", str2 = "Afternoon" for the following examples:
Rela onal operators in Python

Operator Operation Description Example

== Equals to If the values of two operands are >>> num1 == num2


equal, then the condi on is True,
False
otherwise it is False
>> str1 == str2
False

!= Not equal to If values of two operands are not >>> num1 != num2
equal, then condi on is True,
True
otherwise it is False
>>> str1 != str2
True
>>> num1 != num3
False

> Greater than If the value of the le -side >>> num1 > num2
operand is greater than the value
True
of the right- side operand, then
condi on is True, otherwise it is >>> str1 > str2
False
True

< Less than If the value of the le -side >>> num1 < num3
operand is less than the value of
False
the right- side operand, then
condi on is True, otherwise it is >>> str2 < str1
False
True
>= Greater than If the value of the le -side >>> num1 >= num2
or equal to operand is greater than or equal
True
to the value of the right-side
operand, then condi on is True, >>> num2 >= num3
otherwise it is False
False

>>> str1 >= str2


True

<= Less than or If the value of the le operand is >>> num1 <= num2
equal to less than or equal to the value of
False
the right operand, then is True
otherwise it is False >>> num2 <= num3
True
>>> str1 <= str2
False

Assignment Operators
Assignment operator assigns or changes the value of the variable on its le .
Assignment operators in Python

Operator Description Example

= Assigns value from right-side operand >>> num1 = 2


to left-side operand.
>>> num2 = num1
>>> print(num2)
2
>>> country = 'India'
>>> country
'India'
+= It adds the value of right-side operand to the >>> num1 = 10
le -side operand and assigns the result to the >>> num2 = 2
le -side operand >>> num1 += num2
Note: x += y is same as x = x + y >>> num1

12
>>> num2
2
>>> str1 = 'Hello'
>>> str2 = 'India'
>>> str1 += str2
>>> str1

'HelloIndia'

-= It subtracts the value of right-side operand >>> num1 = 10


from
the le -side operand and assigns the >>> num2 = 2
result to
le -side operand >>> num1 -= num2
num1
Note: x -= y is same as x = x - y >>>
8

*= It mul plies the value of right-side operand >>> num1 = 2


with the value of le -side operand and
>>> num2 = 3
assigns the result to le -side operand
>>> num1 *= 3
Note: x *= y is same as x = x * y
>>> num1
6
>>> a = 'India'
>>> a *= 3
>>> a
'IndiaIndiaIndia'

/= It divides the value of le -side operand >>> num1 = 6


by the
value of right-side operand and assigns >>> num2 = 3
the
result to le -side operand >>> num1 /= num2
num1
Note: x /= y is same as x = x / y >>>
2.0

%= It performs modulus opera on using >>> num1 = 7


two
operands and assigns the result to le - >>> num2 = 3
side
operand >>> num1 %= num2
num1
Note: x %= y is same as x = x % y >>>
1
//= It performs floor division using two >>> num1 = 7
operands
and assigns the result to le -side operand >>> num2 = 3
Note: x //= y is same as x = x // y >>> num1 //= num2
>>> num1
2

**= It performs exponen al (power) >>> num1 = 2


calcula on on
operators and assigns value to the >>> num2 = 3
le -side
operand >>> num1 **= num2
num1
Note: x **= y is same as x = x ** y >>>
8

Logical Operators
There are three logical operators supported by Python. These operators (and, or, not) are to be
wri en in lower case only. The logical operator evaluates to either True or False based on the logical
operands on either side.
Logical operators in Python

Operator Operation Description Example

and Logical AND If both the operands are >>> True and True
True, then condi on
True
becomes True
>>> num1 = 10
>>> num2 = -20
>>> bool(num1 and num2)
True
>>> True and False
False
>>> num3 = 0
>>> bool(num1 and num3)
False
>>> False and False
False
or Logical OR If any of the two >>> True or True
operands are True, then
True
condi on becomes True
>>> True or False
True
>>> bool(num1 or num3)
True
>>> False or False
False

not Logical NOT Used to reverse the >>> num1 = 10


logical state of its
>>> bool(num1)
operand
True
>>> not num1
>>> bool(num1)
False

Iden ty Operators
Iden ty operators are used to determine whether the value of a variable is of a certain type or not.
Iden ty operators can also be used to determine whether two variables are referring to the
same object or not. There are two iden ty operators.

Operator Description Example

is Evaluates True if the variables on either >>> num1 = 5


side of the operator point towards the
>>> type(num1) is int
same memory loca on and False
otherwise. var1 is var2 results to True if True
id(var1) is equal to id(var2)
>>> num2 = num1
>>> id(num1) 1433920576
>>> id(num2) 1433920576
>>> num1 is num2
True

is not Evaluates to False if the variables on >>> num1 is not num2


either side of the operator point to the
False
same memory loca on and True
otherwise. var1 is not var2 results to True
if id(var1) is not equal to id(var2)
Membership Operators
Membership operators are used to check if a value is a member of the given sequence or not.
Membership operators in Python

Operator Description Example

in Returns True if the variable/value is found in >>> a = [1,2,3]


the
specified sequence and Falseotherwise >>> 2 in a
True
>>> '1' in a
False

not in Returns True if the variable/value is not >>> a = [1,2,3]


found in
the specified sequence and Falseotherwise >>> 10 not in a
True
>>> 1 not in a
False

Precedence of Operators
Evalua on of the expression is based on precedence of operators. When an expression contains
different kinds of operators, precedence determines which operator should be applied first. Higher
precedence operator is evaluated before the lower precedence operator.
Precedence of all operators in Python

Order of Operators Description


Precedence

1 ** Exponen a on (raise to the power)

2 ~ ,+, - Complement, unary plus and unary minus

3 * ,/, %, // Mul ply, divide, modulo and floor division

4 +, - Addi on and subtraction

5 <= , < , > , >=, == , != Rela onal and Comparison operators

6 =, %=, /=, //=, -=, +=, Assignment operators


*=, **=

7 is, is not Iden ty operators

8 in, not in Membership operators


9 not

10 and Logical operators

11 or

Note:

 Parenthesis can be used to override the precedence of operators. The expression


within () is evaluated first.
 operators with equal precedence, the expression is evaluated from le to right.

1)How will Python evaluate the following expression?


20 + 30 * 40
Solution:
= 20 + (30 * 40) #Step 1
#precedence of * is more than that of +
= 20 + 1200 #Step 2
= 1220 #Step 3
2)How will Python evaluate the following expression?
20 - 30 + 40
Solution: The two operators (–) and (+) have equal precedence. Thus, the first operator, i.e.,
subtrac on is applied before the second operator, i.e., addi on (le to right).
= (20 – 30) + 40 #Step 1
= -10 + 40 #Step 2
= 30 #Step 3
3)How will Python evaluate the following expression?
(20 + 30) * 40
Solution:
= (20 + 30) * 40 # Step 1
#using parenthesis(), we have forced precedence of + to be more than that of *
= 50 * 40 # Step 2
= 2000 # Step 3
4)How will the following expression be evaluated in Python?
15.0 / 4 + (8 + 3.0)
Solution:
= 15.0 / 4 + (8.0 + 3.0) #Step 1
= 15.0 / 4.0 + 11.0 #Step 2
= 3.75 + 11.0 #Step 3
= 14.75 #Step 4

INPUT AND OUTPUT


INPUT

Some mes, a program needs to interact with the users to get some input data or informa on from
the end user and process it to give the desired output. In Python, we have the input () func on for
taking the user input. The input() func on prompts the user to enter data. It accepts all user
input as string. The user may enter a number or a string but the input() func on treats them as
strings only. The syntax for input()is:
input ([Prompt])
The input() takes exactly what is typed from the keyboard, converts it into a string and assigns it
to the variable on le -hand side of the assignment operator (=). Entering data for the input
func on is terminated by pressing the enter key.
>>> fname = input("Enter your first name: ")
Enter your first name: Arnab
>>> age = input("Enter your age: ")
Enter your age: 19
>>> type(age)
<class 'str'>
#func on int() to convert string to integer
>>> age = int( input("Enter your age:")) Enter your age: 19
>>> type(age)
<class 'int'>

OUTPUT
Python uses the print() func on to output data to standard output device — the screen.

Statement Output

print("Hello") Hello

print(10*2.5) 25.0

print("I" + "love" + "my" + "country") Ilovemycountry

print("I'm", 16, "years old") I'm 16 years old


TYPE CONVERSION
Process of convert a data type from one form to another type.
Explicit Conversion

 Explicit conversion, also called type cas ng happens when data type conversion takes place
because the programmer forced it in the program.
 The general form of an explicit data type conversion is: (new_data_type) (expression)
 With explicit type conversion, there is a risk of loss of informa on since we are forcing
an expression to be of a specific type.
 For example, conver ng a floa ng value of x = 20.67 into an integer type, i.e., int(x) will
discard the frac onal part .67.

Function Description

int(x) Converts x to an integer

float(x) Converts x to a floa ng-point number

str(x) Converts x to a string representa on

chr(x) Converts ASCII value of x to character

ord(x) returns the character associated with the ASCII code x

Program of explicit type conversion from int to float.

#Explicit type conversion from int to float


num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))

Output:
30
<class 'int'>
30.0
<class 'float'>
Program of explicit type conversion from float to int.

#Explicit type conversion from float to int

num1 = 10.2

num2 = 20.6

num3 = (num1 + num2)

print(num3) Output:

print(type(num3)) 30.8

num4 = int(num1 + num2) <class ‘float’>

print(num4) 30

print(type(num4)) <class ‘int’>

Program to show explicit type conversion.


#Explicit type conversion
icecream = '25'
brownie = '45'
#String concatena on
price = icecream + brownie
print("Total Price Rs." + price)
#Explicit type conversion - string to integer
price = int(icecream)+int(brownie)
print("Total Price Rs." + str(price))
Output:
Total Price Rs.2545
Total Price Rs.70

Implicit Conversion
when data type conversion is done automa cally by Python and is not instructed by the
programmer.
Program to show implicit conversion from int to float.
#Implicit type conversion from int to float

num1 = 10 #num1 is an integer


num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float and an integer
print(sum1) print(type(sum1))
Output:
30.0
<class 'float'>
In the above example, an integer value stored in variable num1 is added to a float value stored
in variable num2, and the result was automa cally converted to a float value stored in
variable sum1 without explicitly telling the interpreter. This is an example of implicit data
conversion. One may wonder why was the float value not converted to an integer instead?
This is due to type promo on that allows performing opera ons (whenever possible) by
conver ng data into a wider-sized data type without any loss of informa on.

DEBUGGING
The process of iden fying and solving errors known as debugging.
Errors occurring in programs can be categorised as:

 Syntax errors
 Logical errors
 Run me errors
Syntax errors

 Like other programming languages, Python has its own rules that determine its syntax.
 The interpreter interprets the statements only if it is syntac cally (as per the rules of
Python) correct.
 If any syntax error is present, the interpreter shows error message(s) and stops the execu on
there.
 For example, parentheses must be in pairs, so the expression (10 + 12) is syntac cally
correct, whereas (7 + 11 is not due to absence of right parenthesis. Such errors need to be
removed before the execu on of the program.
Logical Errors

 A logical error produces an undesired output but without abrupt termina on of the
execu on of the program.
 Since the program interprets successfully even when logical errors are present in it, it is
some mes difficult to iden fy these errors.
 The only evidence to the existence of logical errors is the wrong output.
 For example, if we wish to find the average of two numbers 10 and 12 and we write the
code as 10 + 12/2, it would run successfully and produce the result 16. Surely, 16 is not
the average of 10 and 12. The correct code to find the average should have been (10 +
12)/2 to give the correct output as 11.
 Logical errors are also called seman c errors as they occur when the meaning of the program
(its seman cs) is not correct.
Run me Error

 A run me error causes abnormal termina on of program while it is execu ng.


 Run me error is when the statement is correct syntac cally, but the interpreter cannot
execute it.
 Run me errors do not appear un l a er the program starts running or execu ng.
Example of a program which generates run me error.
#Run me Errors Example
num1 = 10.0
num2 = int(input("num2 = "))
#if user inputs a string or a zero, it leads to run me error
print(num1/num2)

You might also like