UNIT I
1
INTRODUCTION
Unit Structure
1.0 Objectives
1.1 Introduction: The Python Programming Language
1.2 History
1.3 Features
1.4 Installing Python
1.5 Running Python program
1.6 Debugging
1.6.1 Syntax Errors
1.6.2 Runtime Errors
1.6.3 Semantic Errors
1.6.4 Experimental Debugging
1.7 Formal and Natural Languages
1.8 The Difference Between Brackets, Braces, and Parentheses
1.9 Summary
1.10 References
1.11 Unit End Exercise
1.0 OBJECTIVES
After reading through this chapter, you will be able to –
To understand and use the basic of python.
To understand the history and features of python programming.
To understand the installation of python.
To handle the basis errors in python.
To understand the difference between brackets, braces and
parenthesis.
1.1 INTRODUCTION: THE PYTHON
PROGRAMMING LANGUAGE
Python is an object-oriented, high level language, interpreted,
dynamic and multipurpose programming language.
Python is not intended to work on special area such as web
programming. That is why it is known as multipurpose because it
can be used with web, enterprise, 3D CAD etc.
1
We don’t need to use data types to declare variable because it
is dynamically typed so we can write a=10 to declare an integer
value in a variable.
Python makes the development and debugging fast because there is
no compilation step included in python development.
1.2 HISTORY
Python was first introduced by Guido Van Rossum in 1991 at the
National Research Institute for Mathematics and Computer
Science, Netherlands.
Though the language was introduced in 1991, the development
began in the 1980s. Previouslyvan Rossum worked on the ABC
language at CentrumWiskunde & Informatica (CWI) in
the Netherlands.
The ABC language was capable of exception handling and
interfacing with the Amoeba operating system. Inspired by the
language, Van Rossum first tried out making his own version of it.
Python is influenced by programming languages like: ABC
language, Modula-3, Python is used for software development at
companies and organizations such as Google, Yahoo, CERN,
Industrial Light and Magic, and NASA.
Why the Name Python?
Python developer, Rossum always wanted the name of his new
language to be short, unique, and mysterious.
Inspired by Monty Python’s Flying Circus, a BBC comedy series,
he named it Python.
1.3 FEATURES
There are a lot of features provided by python programming language
as follows
1. Easy to Code:
Python is a very developer-friendly language which means that
anyone and everyone can learn to code it in a couple of hours or
days.
As compared to other object-oriented programming languages like
Java, C, C++, and C#, Python is one of the easiest to learn.
2. Open Source and Free:
Python is an open-source programming language which means that
anyone can create and contribute to its development.
Python has an online forum where thousands of coders gather daily
to improve this language further. Along with this Python is free to
download and use in any operating system, be it Windows, Mac or
Linux.
2
3. Support for GUI:
GUI or Graphical User Interface is one of the key aspects of any
programming language because it has the ability to add flair to
code and make the results more visual.
Python has support for a wide array of GUIs which can easily be
imported to the interpreter, thus making this one of the most
favorite languages for developers.
4. Object-Oriented Approach:
One of the key aspects of Python is its object-oriented
approach. This basically means that Python recognizes the
concept of class and object encapsulation thus allowing
programs to be efficient in the long run.
5. Highly Portable:
Suppose you are running Python on Windows and you need to shift
the same to either a Mac or a Linux system, then you can easily
achieve the same in Python without having to worry about
changing the code.
This is not possible in other programming languages, thus making
Python one of the most portable languages available in the
industry.
6. Highly Dynamic
Python is one of the most dynamic languages available in the
industry today. What this basically means is that the type of a
variable is decided at the run time and not in advance.
Due to the presence of this feature, we do not need to specify the
type of the variable during coding, thus saving time and increasing
efficiency.
7. Large Standard Library:
Out of the box, Python comes inbuilt with a large number
of libraries that can be imported at any instance and be used in a
specific program.
The presence of libraries also makes sure that you don’t need to
write all the code yourself and can import the same from those that
already exist in the libraries.
1.4 INSTALLING PYTHON
To install Python, firstly download the Python distribution from
official website of python (www.python.org/ download).
Having downloaded the Python distribution now execute it.
Setting Path in Python:
3
Before starting working with Python, a specific path is to set to set path
follow the steps:
Right click on My Computer--> Properties -->Advanced System
setting -->Environment Variable -->New
In Variable name write path and in Variable value copy path up to C://
Python (i.e., path where Python is installed). Click Ok ->Ok.
1.5 RUNNING PYTHON PROGRAM:
There are different ways of working in Python:
1) How to Execute Python Program Using Command Prompt:
If you want to create a Python file in .py extension and run. You can
use the Windows command prompt to execute the Python code.
Example:
Here is the simple code of Python given in the Python file
demo.py. It contains only single line code of Python which prints
the text “Hello World!” on execution.
So, how you can execute the Python program using the command
prompt. To see this, you have to first open the command
prompt using the ‘window+r’ keyboard shortcut. Now, type the
word ‘cmd’ to open the command prompt.
This opens the command prompt with the screen as given
below. Change the directory location to the location where you
have just saved your Python .py extension file.
We can use the cmd command ‘cd’ to change the directory
location. Use ‘cd..’ to come out of directory and “cd” to come
inside of the directory. Get the file location where you saved your
Python file.
To execute the Python file, you have to use the keyword
‘Python’ followed by the file name with extension.py See the
example given in the screen above with the output of the file.
4
2) Interactive Mode to Execute Python Program:
To execute the code directly in the interactive mode. You have to
open the interactive mode. Press the window button and type the
text “Python”. Click the “Python 3.7(32 bit) Desktop app” as given
below to open the interactive mode of Python.
You can type the Python code directly in the Python interactive
mode. Here, in the image below contains the print program of
Python.
Press the enter button to execute the print code of Python. The
output gives the text “Hello World!” after you press the enter
button.
Type any code of Python you want to execute and run directly on
interactive mode.
5
3) Using IDLE (Python GUI) to Execute Python Program:
Another useful method of executing the Python code. Use the
Python IDLE GUI Shell to execute the Python program on
Windows system.
Open the Python IDLE shell by pressing the window button of the
keyboard. Type “Python” and click the “IDLE (Python 3.7 32
bit)” to open the Python shell.
Create a Python file with .py extension and open it with the Python
shell. The file looks like the image given below.
6
It contains the simple Python code which prints the text “Hello
World!”. In order to execute the Python code, you have to open the
‘run’ menu and press the ‘Run Module’ option.
A new shell window will open which contains the output of the
Python code. Create your own file and execute the Python code
using this simple method using Python IDLE.
1.6 DEBUGGING
Debugging means the complete control over the program
execution. Developers use debugging to overcome program from
any bad issues.
debugging is a healthier process for the program and keeps the
diseases bugs far away.
Python also allows developers to debug the programs using pdb
module that comes with standard Python by default.
We just need to import pdb module in the Python script. Using pdb
module, we can set breakpoints in the program to check the current
status
7
We can Change the flow of execution by using jump, continue
statements.
1.6.1 Syntax Error:
Errors are the mistakes or faults performed by the user which
results in abnormal working of the program.
However, we cannot detect programming errors before the
compilation of programs. The process of removing errors from a
program is called Debugging.
A syntax error occurs when we do not use properly defined syntax
in any programming language. For example: incorrect arguments,
indentation, use of undefined variables etc.
Example:
age=16
if age>18:
print ("you can vote”) # syntax error because of not using indentation
else
print ("you cannot vote”) #syntax error because of not using
indentation
1.6.2 Runtime Errors:
The second type of error is a runtime error, so called because the
error does not appear until after the program has started running.
These errors are also called exceptions because they usually
indicate that something exceptional (and bad) has happened.
Some examples of Python runtime errors:
division by zero
performing an operation on incompatible types
using an identifier which has not been defined
accessing a list element, dictionary value or object attribute
which doesn’t exist
trying to access a file which doesn’t exist
1.6.3 Semantic Errors:
The third type of error is the semantic error. If there is a semantic
error in your program, it will run successfully in the sense that the
computer will not generate any error messages, but it will not do
the right thing. It will do something else.
The problem is that the program you wrote is not the program you
wanted to write. The meaning of the program (its semantics) is
wrong.
Identifying semantic errors can be tricky because it requires you to
work backward by looking at the output of the program and trying
to figure out what it is doing.
8
1.6.4 Experimental Debugging:
One of the most important skills you will acquire is debugging.
Although it can be frustrating, debugging is one of the most
intellectually rich, challenging, and interesting parts of
programming.
Debugging is also like an experimental science. Once you have an
idea about what is going wrong, you modify your program and try
again.
For some people, programming and debugging are the same thing.
That is, programming is the process of gradually debugging a
program until it does what you want.
The idea is that you should start with a program that does
something and make small modifications, debugging them as you
go, so that you always have a working program.
1.7 FORMAL AND NATURAL LANGUAGES
Natural languages are the languages people speak, such as English,
Spanish, and French. They were not designed by people (although
people try to impose some order on them); they evolved naturally.
Formal languages are languages that are designed by people for
specific applications.
For example, the notation that mathematicians use is a formal
language that is particularly good at denoting relationships among
numbers and symbols. Chemists use a formal language to represent
the chemical structure of molecules.
Programming languages are formal languages that have been
designed to express computations.
Formal languages tend to have strict rules about syntax. For
example, 3 + 3 = 6 is a syntactically correct mathematical
statement.
Syntax rules come in two flavors, pertaining to tokens and
structure. Tokens are the basic elements of the language, such as
words, numbers, and chemical elements.
The second type of syntax rule pertains to the structure of a
statement; that is, the way the tokens are arranged. The statement
3+ = 3 is illegal because even though + and = are legal tokens, you
can’t have one right after the other.
1.8 THE DIFFERENCE BETWEEN BRACKETS,
BRACES, AND PARENTHESES:
Brackets [ ]:
Brackets are used to define mutable data types such as list or list
comprehensions.
9
Example:
To define a list with name as L1 with three elements 10,20 and 30
>>> L1 = [10,20,30]
>>> L1
[10,20,30]
Brackets can be used for indexing and lookup of elements
Example:
>>>L1[1] = 40
>>>L1
[10,40,30]
Example: To lookup the element of list L1
>>> L1[0]
10
Brackets can be used to access the individual characters of a string
or to make string slicing
Example:
Lookup the first characters of string
str>>>’mumbai’
>>> str [0]
‘m’
Example: To slice a string
>>> str [1:4]
‘umb’
Braces {}
Curly braces are used in python to define set or dictionary.
Example:
Create a set with three elements 10,20,30.
>>> s1 = {10,20,30}
>>> type(s1)
<class ‘set’>
Example:
Create a dictionary with two elements with keys, ‘rollno’ and ‘name’
>>> d1= {‘rollno’:101, ‘name’:’ Vivek’}
>>> type(d1)
<class ‘dict’>
Brackets can be used to access the value of dictionary element by
specifying the key.
>>> d1[‘rollno’]
101
10
Parentheses ( )
Parentheses can be used to create immutable sequence data type
tuple.
Example: Create a tuple named ‘t1’ with elements 10,20,30
>>> t1= (10,20,30)
>>> type(t1)
<class ‘tuple’>
Parentheses can be used to define the parameters of function
definition and function call.
Example:
Multiply two numbers using a function
def mul(a,b):
returns a*b
x=2
y=3
z=mul (2,3)
print(x,’*’,y,’=’z)
In the function definition def mul(a,b) formal parameters are
specified using parentheses
In the function call z=mul (2,3) actual values are specified using
parenthesis.
1.9 SUMMARY
In this chapter we studied Introduction, history, features of Python
Programming Language.
We don’t need to use data types to declare variable because it
is dynamically typed so we can write a=10 to declare an integer
value in a variable.
In this chapter we are more focused on types of errors in python
like syntax error, runtime error, semantic error and experimental
debugging.
Execution of Python Program Using Command Prompt and
Interactive Mode to Execute Python Program.
Also, we studied Difference between Brackets, Braces, and
Parentheses in python.
1.10 REFERENCES
www.journaldev.com
www.edureka.com
www.tutorialdeep.com
11
www.xspdf.com
Think Python by Allen Downey 1st edition.
Python Programming for Beginners By Prof. Rahul E. Borate, Dr.
Sunil Khilari, Prof. Rahul S. Navale.
1.11 UNIT END EXERCISE
1. Use a web browser to go to the Python website http: // python.org.
This page contains information about Python and links to Python-
related pages, and it gives you the ability to search the Python
documentation.
For example, if you enter print in the search window, the first link
that appears is the documentation of the print statement. At this
point, not all of it will make sense to you, but it is good to know
where it is.
2. Start the Python interpreter and type help () to start the online help
utility. Or you can type help ('print') to get information about the
print statement.
*****
12
2
VARIABLES AND EXPRESSION
Unit Structure
2.0 Objectives
2.1 Introduction
2.2 Values and Types
2.2.1 Variables
2.2.2 Variable Names and Keywords
2.3 Type conversion
2.3.1 Implicit Type Conversion
2.3.2 Explicit Type Conversion
2.4 Operators and Operands
2.5 Expressions
2.6 Interactive Mode and Script Mode
2.7 Order of Operations
2.8 Summary
2.9 References
2.10 Unit End Exercise
2.0 OBJECTIVES
After reading through this chapter, you will be able to –
To understand and use the basic datatypes of python.
To understand the type conversion of variables in python
programming.
To understand the operators and operands in python.
To understand the interactive mode and script mode in python.
To understand the order of operations in python.
2.1 INTRODUCTION
Variables in a computer program are not quite like mathematical
variables. They are placeholders for locations in memory.
Memory values consists of a sequence of binary digits (bits) that can
be 0 or 1, so all numbers are represented internally in base 2.
Names of variables are chosen by the programmer.
13
Python is case sensitive, so myVariable is not the same
as Myvariable which in turn is not the same as MyVariable.
With some exceptions, however, the programmer should avoid
assigning names that differ only by case since human readers can
overlook such differences.
2.2 VALUES AND TYPES
A value is one of the basic things a program works with, like a letter or
a number. The values we have seen so far are 1, 2, and 'Hello, World!'.
These values belong to different types: 2 is an integer, and 'Hello,
World!' is a string, so-called because it contains a “string” of letters.
Youcan identify strings because they are enclosed in quotation marks.
If you are not sure what type a value has, the interpreter can tell you.
>>>type ('Hello, World!')
<type ‘str’>
>>> type (17)
<type ‘int’>
Not surprisingly, strings belong to the type str and integers belong to
the type int. Less obviously, numbers with a decimal point belong to a
type called float, because these numbers are represented in a format
called floating-point.
>>> type (3.2)
<type ‘float’>
What about values like '17' and '3.2'? They look like numbers, but they
are in quotation marks like strings.
>>> type (‘17’)
<type ‘str’>
>>> type (‘3.2’)
<type ‘str’>
They are strings.
2.2.1 Variables:
One of the most powerful features of a programming language is the
ability to manipulate variables. A variable is a name that refers to a
value.
An assignment statement creates new variables and gives them values:
>>> message = ‘Welcome to University of Mumbai’
>>> n = 17
>>> pi = 3.1415926535897932
The above example makes three assignments. The first assigns a string
to a new variable named message, the second gives the integer 17 to n,
the third assigns the (approximate) value of π to pi.
14
A common way to represent variables on paper is to write the name
with an arrow pointing to the variable’s value.
>>> type(message)
<type ‘str’>
>>> type(n)
<type ‘int’>
>>> type(pi)
<type ‘float’>
2.2.2 Variable Names and Keywords:
Programmers generally choose names for their variables that are
meaningful they document what the variable is used for.
Variable names can be arbitrarily long. They can contain both letters
and numbers, but they have to begin with a letter. It is legal to use
uppercase letters, but it is a good idea to begin variable names with a
lowercase letter.
The underscore character, _, can appear in a name. It is often used in
names with multiple words, such as my_name or
airspeed_of_unladen_swallow.
If you give a variable an illegal name, you get a syntax error:
>>> 76mumbai= 'big city'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced python'
SyntaxError: invalid syntax
76mumbai is illegal because it does not begin with a letter. more@ is
illegal because it contains an illegal character, @. But what’s wrong
with class?
It turns out that class is one of Python’s keywords. The interpreter uses
keywords to recognize the structure of the program, and they cannot be
used as variable names.
Python has a lot of keywords. The number keeps on growing with the
new features coming in python.
Python 3.7.3 is the current version as of writing this book. There are
35 keywords in Python 3.7.3 release.
We can get the complete list of keywords using python interpreter help
utility.
$ python3.7
>>> help ()
help> keywords
15
Here is a list of the Python keywords. Enter any keyword to get more
help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
You might want to keep this list handy. If the interpreter complains
about one of your variable names and you don’t know why, see if it is
on this list.
2.3 TYPE CONVERSION
The process of converting the value of one data type (integer, string, float,
etc.) to another data type is called type conversion. Python has two types
of type conversion.
2.3.1 Implicit Type Conversion:
In Implicit type conversion, Python automatically converts one data
type to another data type. This process doesn't need any user
involvement.
example where Python promotes the conversion of the lower data type
(integer) to the higher data type (float) to avoid data loss.
Example 1: Converting integer to float
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print ("datatype of num_int:”, type(num_int))
print ("datatype of num_flo:”, type(num_flo))
print ("Value of num_new:”, num_new)
print ("datatype of num_new:”, type(num_new))
When we run the above program, the output will be:
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
16
In the above program, we add two variables num_int and num_flo,
storing the value in num_new.
We will look at the data type of all three objects respectively.
In the output, we can see the data type of num_int is an integer while
the data type of num_flo is a float.
Also, we can see the num_new has a float data type because Python
always converts smaller data types to larger data types to avoid the
loss of data.
Example 2: Addition of string(higher) data type and integer(lower)
datatype
num_int = 123
num_str = “456”
print (“Data type of num_int:”, type(num_int))
print (“Data type of num_str:”, type(num_str))
print(num_int+num_str)
When we run the above program, the output will be:
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>
Traceback (most recent call last):
File "python", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
In the above program, we add two variables num_int and num_str.
As we can see from the output, we got TypeError. Python is not able to
use Implicit Conversion in such conditions.
However, Python has a solution for these types of situations which is
known as Explicit Conversion.
2.3.2Explicit Type Conversion:
In Explicit Type Conversion, users convert the data type of an object
to required data type. We use the predefined functions
like int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user
casts (changes) the data type of the objects.
Syntax:
<required_datatype>(expression)
Typecasting can be done by assigning the required data type function to
the expression
17
Example 3: Addition of string and integer using explicit conversion
num_int = 123
num_str = "456"
print (“Data type of num_int:”, type(num_int))
print (“Data type of num_str before Type Casting:”, type(num_str))
num_str = int(num_str)
print (“Data type of num_str after Type Casting:”, type(num_str))
num_sum = num_int + num_str
print (“Sum of num_int and num_str:”, num_sum)
print (“Data type of the sum:”, type(num_sum))
When we run the above program, the output will be:
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>
In the above program, we add num_str and num_int variable.
We converted num_str from string(higher) to integer(lower) type
using int() function to perform the addition.
After converting num_str to an integer value, Python is able to add
these two variables.
We got the num_sum value and data type to be an integer.
2.4 OPERATORS AND OPERANDS:
Operators are particular symbols which operate on some values and
produce an output.
The values are known as Operands.
Example:
4+5=9
Here 4 and 5 are Operands and (+), (=) signs are the operators.
They produce the output 9
Python supports the following operators:
Arithmetic Operators.
18
Relational Operators.
Logical Operators.
Membership Operators.
Identity Operators
Arithmetic Operators:
Operators Description
// Perform Floor division (gives integer value after division)
+ To perform addition
- To perform subtraction
* To perform multiplication
/ To perform division
% To return remainder after division (Modulus)
** Perform exponent (raise to power)
Arithmetic Operator Examples:
>>> 10+20
30
>>> 20-10
10
>>> 10*2
20
>>> 10/2
5
>>> 10%3
1
>>> 2**3
8
>>> 10//3
3
Relational Operators:
Operators Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
19
Relational Operators Examples:
>>> 10<20
True
>>> 10>20
False
>>> 10<=10
True
>>> 20>=15
True
>>> 5==6
False
>>>5!=6
True
Logical Operators:
Operators Description
and Logical AND (When both conditions are true output will
be true)
or Logical OR (If any one condition is true output will be
true
not Logical NOT (Compliment the condition i.e., reverse)
Logical Operators Examples:
a=5>4 and 3>2
print(a)
True
b=5>4 or 3<2
print(b)
True
c=not(5>4)
print(c)
False
Membership Operators:
Operators Description
in Returns true if a variable is in sequence of another
variable, else false.
not in Returns true if a variable is not in sequence of
another variable, else false.
20
Membership Operators Examples:
a=10
b=20
list= [10,20,30,40,50]
if (a in list):
print (“a is in given list”)
else:
print (“a is not in given list”)
if (b not in list):
print (“b is not given in list”)
else:
print (“b is given in list”)
Output:
>>>
a is in given list
b is given in list
Identity operators:
Operators Description
is Returns true if identity of two operands are same, else
false
is not Returns true if identity of two operands are not same,
else false.
Identity operators Examples
a=20
b=20
if (a is b):
print (“a, b has same identity”)
else:
print (“a, b is different”)
b=10
if (a is not b):
print (“a, b has different identity”)
else:
print (“a, b has same identity”)
>>>
a, b has same identity
a, b has different identity
21
2.5 EXPRESSIONS
An expression is a combination of values, variables, and operators.
A value all by itself is considered an expression, and so is a variable,
so the following are all legal expressions (assuming that the variable x
has been assigned a value):
17
x
x + 17
A statement is a unit of code that the Python interpreter can execute. We
have seen two kinds of statement: print and assignment.
Technically an expression is also a statement, but it is probably
simpler to think of them as different things. The important difference
is that an expression has a value; a statement does not.
2.6 INTERACTIVE MODE AND SCRIPT MODE:
One of the benefits of working with an interpreted language is that you
can test bits of code in interactive mode before you put them in a
script. But there are differences between interactive mode and script
mode that can be confusing.
For example, if you are using Python as a calculator, you might type
>>> miles = 26.2
>>> miles * 1.61
42.182
The first line assigns a value to miles, but it has no visible effect. The
second line is an expression, so the interpreter evaluates it and displays the
result. So we learn that a marathon is about 42 kilometers.
But if you type the same code into a script and run it, you get no
output at all.
In script mode an expression, all by itself, has no visible effect. Python
actually evaluates the expression, but it doesn’t display the value
unless you tell it to:
miles = 26.2
print (miles * 1.61)
This behavior can be confusing at first.
A script usually contains a sequence of statements. If there is more
than one statement, the results appear one at a time as the statements
execute.
For example
22
print 1
x=2
print x
produces the output
1
2
The assignment statement produces no output.
2.7 ORDER OF OPERATIONS
When more than one operator appears in an expression, the order of
evaluation depends on the rules of precedence. For mathematical
operators, Python follows mathematical convention. The acronym
PEMDAS is a useful way to remember the rules:
Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want. Since expressions in
parentheses are evaluated first,
2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to
make an expression easier to read, as in (minute * 100) / 60, even if it
doesn’t change the result.
Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4,
and 3*1**3 is 3, not 27.
Multiplication and Division have the same precedence, which is higher
than Addition and Subtraction, which also have the same precedence.
So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
Operators with the same precedence are evaluated from left to right
(except exponentiation). So, in the expression degrees / 2 * pi, the
division happens first and the result is multiplied by pi. To divide by
2π, you can use parentheses or write degrees / 2 / pi.
Example for Operator Precedence
>>> 200/200+(100+100)
201.0
>>>
>>> a=10
>>> b=20
>>> c=15
>>> (a+b)*(c+b)-150
900
>>> (a+b)*c+b-150
320
>>> a+b**2
410
23
>>> a or b + 20
10
>>> c or a + 20
15
>>> c and a + 20
30
>>> a and b + 20
40
>>> a>b>c
False
>>>
2.8 SUMMARY
In this chapter we studied how to declare variables, expression and
types of variables in python.
We are more focuses on type conversion of variables in this chapter
basically two types of conversion are implicit type conversion and
explicit type conversion.
Also studied types of operators available in python like arithmetic,
logical, relational and membership operators.
Focuses on interactive mode and script mode in python and order of
operations.
2.9 UNIT END EXERCISE
1. Assume that we execute the following assignment statements:
width = 17
height = 12.0
delimiter = '.'
For each of the following expressions, write the value of the expression
and the type (of the value of
the expression).
1. width/2
2. width/2.0
3. height/3
4. 1 + 2 * 5
5. delimiter * 5
24
Use the Python interpreter to check your answers
2. Type the following statements in the Python interpreter to see what
they do:
5
x=5
x+1
Now put the same statements into a script and run it. What is the
output? Modify the script by transforming each expression into a print
statement and then run it again.
3. Write a program add two numbers provided by the user.
4. Write a program to find the square of number.
5. Write a program that takes three numbers and prints their sum. Every
number is given on a separate line.
2.9 REFERENCES
Think Python by Allen Downey 1st edition.
Python Programming for Beginners By Prof. Rahul E. Borate, Dr.
Sunil Khilari, Prof. Rahul S. Navale.
https://learning.rc.virginia.edu/
www.programiz.com
www.itvoyagers.in
*****
25