[go: up one dir, main page]

0% found this document useful (0 votes)
21 views18 pages

GE Chapter1

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)
21 views18 pages

GE Chapter1

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/ 18

CHAPTER

PYTHON PROGRAMMING:
1 AN INTRODUCTIOON

CHAPTER OUTLINE

1.1 IDLE- An Interpreterfor Python 1.5 Bitwise Operators


1.2 Python Strings 1 . 6 Variables and Assignment Statements
1.3 Relational Operators 1.7 Keywords
1.4 Logical Operators 1.8 Script Mode

Python is an interactive programming language. Simple syntax of the


language makes Python programs easy to read and write. Python was
developed by Guido Van Rossum in 1991 at the National Research Institute
for Mathematics and Computer Science in the Netherlands. Guido Van
Rossum named Python by getting inspired from his favourite comedy show
Monty Python's Flying Circus.
Ever since the language was developed, it is becoming popular day
by day amongst the programmers. Various versions of Python have been
released till date ranging from version 1.0. This book uses Python 3.6. Python
s used in various application areas such as the web, gaming, scientific and

uneric computing, text processing, and network programming.

IDLE- AN INTERPRETER FOR PYTHON


IDLE
Estands for Integrated Development and Learning Environment.
shaDLE comprises Python shell and Python Editor. While Python Python shell displays
shell is an interactivo interpreter, Python Editor allows us to work in seript the prompt >>> too
mode While indicate that it is wait
inofor a
using Python shell, we just need to type Python code at the
»prprompt and press the enter key, and the shell will respond with the ing user com
mand
Sul
OTthe computation. For example, when we type
print ('hello world') the text to be printed
and is enclosed between
press enter key,Python shell will display: apostrophe marks
Python Programming
2
hello world
the apostrophe marks
when we type
are not displayed in
Python shell may also be used as a calculator, for example,
the output 18 5 followed by enter, Python shell outputs the value of the

expression, i.e. 23, as shown below:

operator + acts on the >>> 18 +5


operands 18 and 5
23
The numbers, 18 and
In the expression 18 5, + is called the operator.
called the operands. In general, an
5 on which the operator + is applied, are
and operands. In Python, all
expression is a valid combination of operators and 23 are
called values or objects. For example, 18, 5,
forms
of data are
the expression
objects. The expression 18 + 5 yields the value 23. Similarly,
18* 5 yields 90, as Python
18 5 the value 13.
yields The expression The expression 27/5
uses
*
as the symbol for themultiplication operation.
5 is real number. In Python,
operators:+, * yields 5.4. Note that theresult of division 27/
11, , and ** result of division is always a real number. However,
if you wish to obtain
an integer (for example, floor(5.4), Python
result operator// (two slashes
be used. For example, 27 // 5 yields
without any intervening blank) can
one of the two operands
5. However, while using the operator //, if at least,
is a real number; the result is a real number, for example, the expression
numbers
27.0// 5 yields 5.0. Real numbers are called floating point
in Computer Science terminology in view of the floating point representation
is not
used to represent real numbers. However, the number representation
known
the subject matter of this book. Python operator & (percentage sign),
as modulus, yields the remainder of the division, for example, 27 8 5 yields
2 because on dividing 27 by 5 we get 2 as the remainder. In Fig. 1.1, we
illustrate these examples in Python shell.

Python 3.6.1 Shell


File Edit Shell Debug Options Window Help
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v. 1900 32 bit (Intel)
on win32
Type "copyright" "credits" or "license ()" tor more information.
>>> 18 + 5
23
Python shell window
>>> 1 8 . 5
90

>>> 27/5
5.
» 27 /1 5
5
>> 27.0 // 5
S.0
27 5

Lne15 Cok4

Fig. 1.1 Computation of arithmetic expressions

The exponentiation operator (**) yields raise to the power operation, i.e.
a. For example, 32 is expressed as 3 2 , and yields the value 9.
Programming:
An lIntmduction 3
Athon

-1 yields 0.5 as expected. The expressions in each of


*
Similarly
mentioned aabove involved only single mathematical
he examples we wOuld require more complex expressions. Note that
operator,
t practice,
in
whereas
the expression 6 / 3 2 yiclds1.0(= (6/ 3)/ 2),
left associative oper
the
expression
2 **
**2 yields 512 (= 2 ** (3 ** 2)). This ators:+,
n because whereas the operator / (as also +, -, *. //, 3) is evaluated 1,
to right, the exponentiation operator is evaluated right to left. We say right associative oper

operators, +, ,/,//, and 3, are left associative operators and ator:*


that the
the operator ** is right associative. Python operator - (negation) yields

For example, and -5


10 *
-5 multiplies 10
negative of the operand.
(negative of 5), yielding -50 as a result. Next, we evaluate the foregoing
expressions in Python shell:

>> 3 ** 2

9
>6 3 2
1.0
>> 2 ** 3 ** 2

512 operator works as


>>> 1 0 * -5 negation operator
-50

When we enter the expression 7 + 4 * 3, the system responds with

value 19 as a result. Note that in the expression 7 + 4 * 3, Python


evaluates the operator *
before + as if the input expression was 7 + (4 *
3) because the operator * has higher precedence than +. In Table 1.1, we

list the operators in decreasing order of their precedence. The expressions


within parentheses are evaluated first; for example, given the expression
(7 3) 10 5, the system would yicld 20.0. Parentheses are
often used to improve the readability of an expression.

Table 1.1 Precedence of arithmetic operators


0(parentheses) while the parenthe-
ses have the highest
(exponentiation) precedence, addition
decreasin9
(negation) order
and subtraction are
at the lowest level
Gvision) I/ (integer division) (multiplication) % (modulus)

laddition) (subtraction)
An eTor occurs when the input expression is not corectly formed. For Python complains
when it encounters
Xample, the exp
expression 7 3(4 + 5) generates an error because the a wrongly formed
Perator between 3 and
( is missing expression

> 7+ 3(4 5)
eback (most recent call last)
ile
* l e " P y s h e l 1 # 17>", 1ine 1, in <module>
Python Programming
7 3(4 5)
TypeError: 'int' object is not calllable

Similarly, the expression 7 0 yields a zero division error since division


by zero is a meaningless operation.
division y zero
is a meaningless >>>7 / 0
operation
Traceback (most recent call last) :
File "<pyshell#18>", line 1, in <module>
7/0
ZeroDivisionError: division by zero

1.2 PYTHON STRINGS


A string is a sequence of characters. To specify a string, we may enclose
a sequence of characters between single, double, or triple quotes. Thus,
"what 's ", ' ' ' today 's
a Python string may 'Hello world',
'"Ajay " ' ,
be enclosed within are the examples of strings. A string enclosed
' '

r"action" plan?'
single, double, or in single quotes may include double quote marks and vice versa. A string
triple quotes
enclosed in triple quotes (also known as docstring, i.e. documentation
string) may include both single and double quote marks and may extendd
over several lines, for example:

>>> 'Hello World'


'Hello World'
>>> print ('Hello World')
Hello World
>>> """Hello
What'ss
nappening""n

"Hello\nWhat's\nhappening"
>>> print ("" "Hello
What'ss
happening" " ")
Hello
What's
happening
Note that enclosing quote marks are used
only to specify a string, and they
do not form part of the
escape sequence \n
marks a new line
string. When we print a string using the print
instruction, the value of the string, i.e. the sequence of characters within
quotes is printed. Also, note that, within a string, \n denotes the
of a line. When a string having \n is
new
beginning
printed, everything after \n
(excluding \n) is printed on the next line. In this section, we shall study
basic operations on strings. Let us
begin
with the concatenation operator (+),
An
m Programming: An Intvduction
5
used
sed to produce a string by concatenating two strings; for example,
to r
is
which
theCxpression ' h e l ] + !!' yiclds the string 'hello !!'
expression 'how' +'are' + ' you?'
yields
the
ou?' (=('how' +
Similarly, 'how use of+ as the con
are') + you') as shown catenation operator
are you
below:
>>>
'hello
'
+ '!!
h e l l o ! !

are' + you?'
>>> 'howt
how are you?'

The o p e r a t o r *
(multiplication) is used to repeat a string a specified use of operatorfor
mber oftimes; for example, the expression 'hello' 5 yields the repeating string
several times
cring 'hellohellohellohellohello':

>>>'hello' * 5

hellohellohellohellohello

1.3 RELATIONAL OPERATORS


Relational operators are used for comparing two expressions and yield
True or False. In an expression involving both arithmetic and
relational operators, the arithmetic operators have higher precedence than
the relational operators. In Table 1.2, we give a list of relational operators

Table 1.2 Relational operators

(equal to)
(less than) relational opera
(greater than) tors for comparing
expression values
(less than or equal to)
(greater than or equal to)

|!=(notequal to)
A operator applied on expressions takes the following form:

tor> expression
Lession <comparison opera

Thus, the expressions, 23 25, 23 != 23, and 23


2.5 >= relational operators
5 arithmetic yield values: True,
4
yield True, False, and True, respectively.As False
the
precedence than the relational operators,
h
expre a v23 higher
e 2 . 5 >= 5 * 4 is evaluated as if it were (23
2.5) 5
>= *
(5 4 ) . When the relational operators
are applied to

strings strings are co


compared left to right, character by character, based
Python Programming

For example, ASCII


6 ASCII values.
also called
on their
ASCII codes,
' 0 ' - ' 9 ' lie in therange [65, 901.
char 'a'
'
z', and
- H' yields True
ASCII values of 'A' ' Z
-' . '

are used
for codes of 'h
Thus,
acters
122. and |48,
571. respectively. than ASCIH
value of 'H' (=
string comparison 197. l04) is greater
value of ' h ' = T r u e since
' h ' is greater
as ASCIl yields
'hello'>
'Hello'
yields True because
the first
72).Also. 'hi'
>'hello'
'H'. Similarly, code of
'
i ' is greater
is identical and ASCII
than
two strings the
Python 3 does
not character in the
string is a prefix of another string,
' e ' . Also, if a
alow string values thanASCll code of
with will be
considered large.
to be compared longer string
numeric values

1.4 LOGICAL OPERATORS


to logical operands
and, and o r are applied
not, T r u e or
The logical operators and yield either
also called Boolean values,
i.e. it requires only
one
True and False,
n o t is a unary operator, False and
F a l s e . The operator
combining expres n o t False yield
n o t True and
sions using logical The expressions Boolean operands and
operand. An expression involving two
operators True, respectively. are True, and
False
True if both the operands
the and operator yields Boolean operands and
two
Similarly, an expression involving
otherwise.
is True, and False
logical operators not,
the or operator yields
True if at least one operand
o r yield val-
This is shown in Table 1.3.
and,
ues: True, False otherwise.

and, and or operators


Table 1.3 not,

not

False
True
True
False

and True False

True False
True
False False
False

or True False

True True True

False True False

Precedence of logical operators is shown in Table 1.4.

Table 1.4 Precedence of logical operators


not

and Decreasing
order
or
Phthon Programming:
An Intduction

aluating an expression involving an and operator, the second


While evalu

sub-expressIOn
is evaluated only if the first sub-expression yields True.
example, in the expression (10 5) and ((5/ 0)<10)), short-circuit evalu
For first sub-expression (10 < 5) ation of a boolean
c* the yields False, and thus
expression
rmines the value of the entire expression as False, Python does not
ate the second sub-expression. This is called short-circuit evaluation
holean expression, However, the expression (10> 5) and ((5
of1 0 ) yields an error since the first sub-expression yields True,
dPvthon attemptsto evaluate the second sub-expression ( (5 0)<
0 that yields an error because division by zero is an illegal operation:
>>> (10 5) and ( ( 5 / 0) <10)
False
> (10> 5) and ( (5 0) < 10)

Traceback (most rcent call last) :


File "<pyshell#104>", line 1
(10 5) and ((5 0) <10)
ZeroDivisionError: division by zero

Similarly, while evaluating an expression involving an or operator, the


second sub-expression is evaluated only if the first sub-expression yields
False. Thus, whereas the expression (10 5 ) or ((5 0)
10) yields True, the expression (10 < 5) ór ( (5/ 0) <10)
yields an error.
To evaluate an expression comprising arithmetic, relational, and
expressions involving
logical operators, the operators are applied according to precedence order arithmetic, relational,
for the operators given in Table 1.5. For example, the expression not 9 and logical operators

8and 7 + 1 != 8 or 6 < 4.5 is evaluated as ifit were the


tollowing equivalent parenthesized expression:
(not (9 == 8)) and ((7 + 1)
!= 8)) or (6< 4.5) expression evaluation

1.e. ( (not False) and ((7 1 ) != 8)) o r (6< 4.5) using precedence
rules
1.e.(True and (7+1) != 8)) o r (6 < 4.5)
.e, (True and (8!= 8)) or (6 < 4.5)

1.e.(True and False) o r (6 4.5)


1.e.False or (6 < 4.5)
1.e. False or False
i.e. False

Table 1.5 Precedence of operators

Arithmetic operators
Decreasing
Relational operators order
Logical operators
Python Programming

1.5 BITWISE OPERATORS


Bitwise operators are the operators that operate on integers interpreted as
strings of binary digits O and 1, also called bits. In Table 1.6, we list bitwise
operators, their description, along with examples. For the sake of brevity.
bitwise operators
operate bit by bit we assume that all numbers are eight-bit long.
Table 1.6 Boolean operators

Bitwise Descriptlon Example


operator

Bitwise AND A bit inx & y is 1 if the 10& 6 yields 2:


x& Y corresponding bit in each 10: 000010100
of x and y is 1, and 0 6: 00000110
otherwise.
***********

2: 00000010

I yis 1 if at least 10 6 yields 14:


Bitwise OR Abit in x

one of the corresponding 10: 000010100


xY
bits in x and y is 1, and 0 6: 00000110
otherwise.
14: 00001110

Bitwise A bit in~x is 1 if and only ~11 yields -12:


Complement if the corresponding bit inx| 11 00001011
x is 0.
The result obtained from -11: 1 11101 00
this operation is -x-1. Note that 1 1 1 1 01 0 0 is the
two's complement of
12: 00001 100.
Bitwise A bit in x y is 1if exactly 10 6 yields 12:
Exclusive OR one of the corresponding 10 00001010
x y bits in x and y is 1, and o 6: 000001100
otherwise.
12 00001100
Left Shift Bits in the binary 5 < 2 yields 20:
x << y representation of x are 5 00000101
shifted left by y places.
Rightmost y bits of the | 20 00010100
result are filled with zeros.
The result obtained from
this operation is x*2Y.
Right Shift Bits in the binary 5 >> 2 will yield 1 as the result as
x>y representation of x are
shown below:
shifted right by y places. | 5: 00000101
Leftmosty bits of the result **

are filled with sign bit.


result obtained from this
The 1: 00000001
operation is x/2.
Table 1.7 shows precedence order of different operators in Python
Programming: An Intwductio
on
Pithon

Table 1.7 Precedence of operators

+X X, ~x

parentheses have the


Decreasing highest precedence
order while logical opera-
tors have the lowest
precedence
=
,>, !=
not

and

or

1.6 VARIABLES AND ASSIGNMENT STATEMENTS


Variables provide a means to name values so that they can be used and
manipulated later on. Indeed, a program essentially carries out variable a variable is a name
manipulations to achieve the desired objective. For example, variables given to a value
english, maths, and commerce may be used to deal with the
marks obtained in these subjects, and the variables totalMarks and
percentage may be used to deal with aggregate marks and the overall
percentage of marks, respectively. If a student has obtained 57 marks in
english, this may be expressed in Python using the following statement:
>english = 57

When the above statement is executed, Python associates the variable assignment state
english with value 57. We can also say that the the variable english ment
5signed the value 57, or that the variable english refers to value 57.
uch a
statement that assigns value to a variable is called an assignment
aiement. In Fig. 1.2, we see that the variable english refers to the value
A figure such as Fig. 1.2 is known as reference diagram or state
r a m as it shows the
current state of the variable.

english

variable english
refers to value 57
57

Fig. 1.2 Current state diagram of variable english


10 Python Prog rammin
In Python style (often called Pythonic style, or Pythonic
in Python, variables
are offen called vaniables are called names, and an assignment is called an association c way
names binding. Thus, we say that the name e n g l i s h has been associated wis
the data object 57, o r that the variable e n g l i s h has been bound to th
an assignment state data object 57. Note that. unlike an expression. on the execution ofan
the
ment binds a vari an
assignment statement. IDLE does not respond with any output. Of course
able to an object rse
the value of the variable english can be displayed as follows:

> english
57

In the above example. english is a variable whose value is 57


Similarly. the following statements will assign values 64 and 62 to the
variables maths and commerce, respectively.
maths = 64

Commerce = 62

In this example, we assume that maximum mark in each subject is 100.


Total marks in these three subjects and overall percentage can be computed
using another sequence of statements:
>>> totalMarks = english + m a t h s + commerce
computing overall
from percentage = (totalMarks / 300) *100
percentage
marks in different >>> percentage
subjects 61.0

Assignment Statement
As discussed above, values are assigned to variables using an assignment
statement. The syntax for assignment statement is as follows:
syntax for assign- variable = expressi on
ment statement
where expression may yield a value such as numeric, string, or Boolean. In

an assignment statement, the expressi on on the right-hand


side of the
equal to operator ( ) is evaluated and the value so obtained is assignedt
seen
the variable on the left-hand side of the operator. We have already
=

we must follow the following


rules
some examples of variables. In general,
while using the variables:

rules for naming vari A variable must begin with a letter or(underscore character)
ables A variable may contain any number of letters, digits, or underscOe
characters. No other character apart from these is allowed.

max_marks,_emp, maxMarks, nt,


Thus,marks, name,
followIng
valid variables. However, note that the
max _of_3_numbers are

are not valid variables:


#use of dot (.)
total _no. #begins with a digit
1st_number
An Intnduction 11
Ar
Programming:

Amount In$ #use of dollar symbol ($)


Total Amount #Presence of blank bet ween two words

d programming practice to make sure that the variables are


meaningt as carefully chosen variables make your code readable. For
always use meaning-
to denote the total marks obtained,it is easy to understand ful variable nanes
ample,

the variable totaI Marks represents than a variable a, ,


k S o r total used for the same purpose. There are several styles
Variables. for example:
of forming
total_marks

TotalMarks

totalMarks

TOTAL_MARKS

However, one must be consistent in following a style. In this book, we prefer follow a consistent
to use the lowerCamelCase style in which the first letter of every word is style in choosing
capitalized, except the first word which begins with a lowercase letter, for variables

ample. total Marks. While forming variables, it is important to note


that Python is case-sensitive. Thus, age and Age are different variables.
So.if we assign a value to the variable age and display the value of Age.
the system will respond with an error message.

>>age = 24
Python is case-sen-
sitive.
>Age age and Age are dif
ferent names
Traceback (most recent call last)
File "<pyshell#1>", 1ine 1, in <module>
Age
NameError: name 'Age' is not defined

Next, let us examine the following statements:

>> a = 5
more than one vari-
> b = a able may refer to the
>> a = same object

The nrst statement assigns name a to an integer value 5 as shown in


E3a). The next statement assigns another name b to the same value
. 1 . 3 (b). Finally, the third statement assigns a different value 7 to a
. 3 (c)). Now the variables a and b refer to different values.

Shorthand
By
Notation
fW, we have seen several examples of assignment statements. The
g assignment statement updates value of the variable a by adding
to the existing value.
a = a+ 5
12
Python Programminy
b

5 5 7 5

(a) (b) (c)


Fig. 1.3 Current state diagram

Alternatively, we can write the above statement as

a shorthand notation >>> a + 5

Thus, the operator += serves as shorthand notation in assignment statement


Similarly, the statements
>>> a = a + b t C

>>> a a a (b+c)
can be written as follows, respectively:

>>> a += b + c
>>> a **= b +c

As the shorthand notation works for all binary mathematical operators.


a = a <operator> b

is equivalent to

a <opera tor>= b

Python also allows multiple assignments in a single statement; for example.


the following sequence of three
assignment statements
msg = 'Meeting'

>>>day = 'Mon'
>>> time = '9'

may be replaced by a single statement:


mutiple assignments
in a single >>msg, day, time
statement =

'Meeting', Mon', 9
Thus, we can
specify more variables than the left side ot an
one on
assignment statement, and the
expr1>, <expr2>, corresponding number of expressions, like
the
syntax for
.
.., <exprk>, on the right side. Formally.
an
assignment statement may be described as follows:
namel>, Kname2>, .
.., <nameK> =
<exprl>, <expr
exprk>
Progrnamming:
An Intmduction
n.chon
13
be used to enhance the
notation
This
can
readability of the program. We
also assign a comm value to multiple variables, for example, the
may
assignment s t a t e m e n t

>totalMarks = Count = 0
assigning same
value to multiple
variables in a single
may he used to replace the following two assignments: statement

>>>tota lMarks = 0
Count = 0

S upposo we wish to Swap values of two variables, say, num1 and num2.
For this purpose, we use a variable temp as follows:

>>> numl, num2 = 10, 20


>> temp = num1

>>numl = num2

>> num2 = temp

print (numl, num2)


20 10

Note that before executing the assignment statement


num1 = num2

we save the value of the variable numl in the variable


temp, so that the
same can be assigned to the variable num2 in the
following assignment
statement. A variable that is used to hold the value of
another variable
temporarily is often called temporary variable.
Alternatively, we can use the following statement to swap the values
of two variables:

>>> numl, num2 =


num2, numi

1.7 KEYWORDS
Keywords are the reserved words that are already defined by
the Python
Tor specific uses. keywords have spe
They cannot be used for any other purpose. Hence, make cial meaning
Sure that none of the names used in a program should match any of the
Keywords. The list of the keywords in Python 3.6 is given in Fig. 1.4.

False class inally is return None


continue for lambda try True def
from nonlocal while and del global keywords cannot
not be used for namingg
ith as if or yield
assert
objects
else import pass break except
in
raise elif

Fig. 1.4 List of Python keywords


Python Programming
14

1.8 SCRIPT MODE


shell, an interactive environment
So far, we have done all work using Python
names, etc., exist only during an
of IDLE. The definitions of objects,
IDLE Session, and start another IDLE
mode, I DLE session. When we exit an
in Script This is not a convenient mode of
instructions are writ- session, we must redo all computations. tasks. Python provides another
ten in a file operation for most of the computational instructions necessary for a task
called script mode. All the
way of working source code,
are stored in a file often
called a source file script, program,
extension .py or
a script should have that such a file must have
or a Python requires
module.
Window option
IDLE provides a New
extension Py or
pyw. To create a script, Python Editor
Pyw the New Window option, a Python
in the F i l e menu. On clicking
of instructions, collectively
window opens, where we can write a sequence
can be saved using
the Save As
called a program o r a script. A script Run
in the F i l e menu. It may
be executed in shell by selecting
option
Module option in the Run menu.
1.5 takes two
readNshow in Fig.
As a trivial example, the script
the first
these numbers. On executing
numbers from the user and outputs
number which
waits for the user to enter a
line of the script, the system second line of
number1. On executing the
is assigned to the variable number which is
the user to enter another
the script, the system waits for n u m b e r l and
to the variable number2. The values of variables
assigned
the third line of the script.
number2 are displayed on executing

Chapret 1
File Edit Format Run Options Window Help
numberl input ()
a simple script number2= input ()
print (number1, number2)
Ln: 5 Cot0

ythor 3.61 Shell


File Edit Shell Debug Options Window Help
(Intel)1
Python 3.6.1 (v3.6.1:69codb5, Mar 21 2017, 17:54:52) [MSC v.19o0 32 bit

on win32
more information.
"license ()" for
"credits" or
TYpe "copyright",
output on executing =RESTART: F:/Python Programs/Chapter-1/readNshow.py

the script S

3 6

Lne 13 Cob 4

Fig. 1.5 Input-output program


The problem with the above script is that as we have developed
remember that the program requires two numberS As
it just now, we
the input. However, if we wish to use it a month later, we may forget
what inputs are required by the program, and we will need to examin
ming: An Introduction 15
Python

the program again


m again before running it. Surely, we would like to avoid
good programming practice is to display to the user what
ffort.
A good
this
h e entered. The modified script readNshowWe l l (Fig. 1.6)
data is
datat h i s by displaying a message to the user as the system waits

for user input.

NShOWWelt.py- RPython Programs/Chapter-1/readNshowiWell.py3.61


Format Run Options Window Help
Re Edi
)
tirst number:
aerl i n p u t ( " E n t e r s e c o n d number: )
DUnber2 input ('Enter
Drint('Numbers are n d e r1, number2)
Lne 5 Cot 0

Python 3.6.1Shell
File Edit Shell Debug options Window Help
Python 3.6.1 (v3.6.1:69codb5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)

on win32
pe "copyright", "credita" or "1icense () *
tor more information.

RESTART: F:/Python Programs/Chapter-1/readNshowwel1.py ***

Enter first nunber: 3


Enter second number: 6
Numbers are: 3 6

Ln:8 Cok4

Fig. 1.6 Input-output program

SUMMARY
.Python interpreter executes one expression (command) at a time.
. An expression is a valid combination of operators and operands. Operands are the objects
on which
operators are applied.
.Arithmetic, relational, logical, and bitwise operators are used for performing computations
in a program.
A String is a sequence of characters. To specity a string, we may use single, double. or

triple quotes.
h e operator + (addition) applied on two string operands is used for concatenating them.
the (multiplication) is used to repeat a string a specitic number of
milarly, operator*
times.
strings, strings are compared lett to right
When relational operators are applied ASCIl
on

their values
aracter by character according to
.
a Boolean expression
involving and operator, the second sub-expression
nile evaluating
s evaluated only if the first sub-expression yields True.
is
8. operator, the second sub-expression
e evaluating an expression involving
or

False.
auated only if the first sub-expression yields
9.
Precedence order for the operators is as follows:
16 Python Programming

+Xr

Decreasing
order

not

and

or

variable associates a
10. A variable is a name that refers to a value. We may also say that a
or Boolean.
name with a data object such as number, character, string,
statement. The syntax for assignment
11. Values are assigned to variables using assignment
statement is as follows:
variable = e x p r e s s i on

numeric, string, or Boolean.


value such as
where expression may yield any
on on the right-hand side
of the equal to
12. In assignment statement, the expressi
an
variable on the left
value so obtained is assigned to the
operator (A is evaluated and the
hand side of the = operator.
It may contain any
13. A variable begin with a letter or_(underscore character).
name must
from these is
number of letters, digits or underscore
characters. No other character apart

allowed.
Thus, age and Age are different variables.
14. Python is case-sensitive.

15. The shorthand notation for a =


a <opera tor> b is

a <operator>= b
line as follows:
T6. In Python, multiple assignment statements can be specified in a single
name1>, <name2>, . . . Kexpressi on1>, <expression2>,
T7. A keyword is a reserved word that is already defined by Python for a speciie Usc
Keywords cannot be used for any other purpose. The list of the Python keywords is giv en

below:

False class finally is return None


continue for lambdatry True def
Programming:An.lntroduction
17
Pn

nonlocal while and


from del global
with as
OL
not yield
else import pass break
a s s e r t

except
raise elif

s Python
Python programming
programm can be done in an interactive and script mode.
18.

ExERCISESs

Evaluate the following expressions:


(x< y) or ( n o t (z == y) and (z < x))

(a) x =
0, y =
6, z =10
b) x= 1, y =
1, z =1
Evaluate the following expressions involving arithmetic operators:
(a) -7 * 20 + 8 / 16 * 2 + 54
b) 7 ** 2 // 9 3

(c) 7 - 4 *2) * 10 5 ** 2 + 15

(d) 5 10 + 10 25 * 8// 5

(e) hello' 2 5
3. Evaluate the following expressions involving relational and logical operators:
(a) 'hi' > hello' and 'bye' <'Bye"
(b) 'hi' > 'hello' or 'bye' < 'Bye'
c) 7> 8 or 5 < 6 and ' I am fine'> 'I am not fine'
(d) 10 != 9 and 29 >= 29
e) 10 != 9 and 29>= 29 and 'hi' > 'hello' or 'bye' < 'Bye' and
7 <= 2.5
4. Evaluate the following expressions involving arithmetic, relational, and logical operators:
(a) 5 8 10 10< 50 and 29 29
(b) 7 * 2 <= 5 // 9 8 3 or 'bye' < 'Bye'

C)5 10 < 10 and- 25 > 1 *


8 // 5
(d) 7 **
2// 4+ 5 > 8 or 5 = 6
4 <6 and 'I am fine'> ' I am not fine'
10 + 6* 2 **
2 != 9// 4 3 and 29 >= 29 /9
'bye'< 'Bye'
g) "hello'5> 'hello' or
5. Evaluate the following expressions involving bitwise operators:

(a) 15& 22
(b) 15 22
c-15 & 22
(d) -15 I 22
(e)15
()22
g)-20
(h) 15 22
Python Programmin
18

8 3
(i) <<

40 >> 3
()
Differentiate between the following operators with the help of examples:
6.
(a) and= ==

(b)and
(c)and//
**
(d) *
and
7. What output will be displayed when the following commands are executed in Pytha
shell in sequence:
(a)>> a = 6
>>> a == 6

>>> a < 5.9


>>> a > 5.9
(b)>>> b = 7

>>b / 6
>>> b // 6
>>> b /4
>>> b % 4

>>>b 7
>>> b *2
>>> b ** 2

8. Construct logical expressions for


(a) marks scored should be representing the following conditions:
greater than 300 and less than 400.
b) Whether the value of
grade is an uppercase letter.
(c) The post is
engineer and experience is more than four
9.
Identify Python keywords from the years.
And class following list of words:
PASS if exec PRINT
10. Write Not
Python statements for the
following equations:
(a) roob =b+Vb 4ac
2a
(b) result =ZXY- 9y 4yx
2xy 2y
(c) result =
2 cos (x + y) cos(x - y)+
log (v) e- 1 +tan x
11. How
does the
(a) x += x effect
+ 10
of the
following two statements
(b) x x
=
+ differ?
10

You might also like