[go: up one dir, main page]

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

New Note CSC 201 Scientific Programming Language

This document provides an introduction to programming languages, focusing on Python as a high-level, versatile language suitable for various applications including web development and data science. It covers the importance of programming languages, features of Python, and its uses in different fields, along with practical guidance on writing and executing Python code. Key concepts such as data types, sequences, and the structure of Python code are also discussed.

Uploaded by

yinka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views18 pages

New Note CSC 201 Scientific Programming Language

This document provides an introduction to programming languages, focusing on Python as a high-level, versatile language suitable for various applications including web development and data science. It covers the importance of programming languages, features of Python, and its uses in different fields, along with practical guidance on writing and executing Python code. Key concepts such as data types, sequences, and the structure of Python code are also discussed.

Uploaded by

yinka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

PAGE | 1 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

INTRODUCTION TO SCIENTIFIC PROGRAMMING LANGUAGE (PHYTON)

1. Introduction to Programming Languages


What is a Programming Language?
A programming language is a structured set of instructions and rules that allows humans to
communicate with computers. It is used to create programs that perform specific tasks, such as
calculations, automation, data analysis, and more. Programming languages act as a bridge
between human intentions and machine execution.
Importance of Programming Languages
i. Automate repetitive tasks.

ii. Solve complex problems through logical structures.

iii. Build applications, websites, and software.

iv. Analyze and process data efficiently.

Categories of Programming Languages


Programming languages are broadly categorized into:
i. Low-Level Languages:

ii. Machine Language: Written in binary (0s and 1s) and directly understood by computers.

iii. Assembly Language: Uses mnemonics (symbolic instructions) for readability, but still
close to hardware.

iv. High-Level Languages: User-friendly and use human-readable syntax. Examples include
Python, Java, and C++.

v. Scripting Languages: Focus on automating tasks and interacting with other software.
Examples include Python, JavaScript, and PHP.

vi. Markup and Query Languages: Used to format and retrieve data. Examples include HTML
(markup) and SQL (query).

Overview of Python
Python is a high-level, interpreted, and general-purpose programming language that is widely
used for web development, data science, machine learning, and more. It was created by Guido van
Rossum in 1991 with the goal of making programming simple and accessible.
Why Learn Python?
i. Beginner-Friendly: Python’s simple and clean syntax makes it easy for beginners to
understand.

ii. Versatile: Python is used in a variety of fields, from web development to artificial
intelligence.

iii. Large Community and Resources: Python has a massive community, making it easy to
find solutions to problems and access learning resources.

iv. Extensive Libraries: Python includes libraries like NumPy, Pandas, and Matplotlib, which
simplify complex tasks.
PAGE | 2 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

1→ Python was created by Guido Van Rossum at CWI (Centrum & Informatica) which is a
National Research Institute for Mathematics and Computer Science in Netherlands.
2→ Father of Python Language is Guido Van Rossum. (Watch his pics)

3→ The language was released in I991.


4→ Python got its name from a BBC comedy series from seventies- “Monty Python‟s
Flying Circus”.
5→ It is free to use. You can download it from the website www.python.org

SALIENT FEATURES OF PYTHON


i. General purpose programming language which can be used for both scientific and non
scientific programming.
ii. Platform independent hence highly portable language.
iii. simple high level language with vast library of add-on modules (library).
iv. Interpreted as well as compiled language.
v. Object oriented and functional programming language.
vi. Clean and elegant coding style.
vii. Suitable for beginners (of course having strong maths and general IQ) who have no
knowledge of computer language.
viii. Python code is significantly smaller than the equivalent C++/Java code.
ix. Python is an OSS (Open Source Software). We are free to use it, make amends in the
source code and redistribute, even for commercial interests. It is due to such openness
that Python has gathered a vast community which is continually growing and adding
value.

USES AND APPLICATION OF PYTHON IN VARIOUS FIELDS


1→ Python is used in Google search engine, YouTube, Bit Torrent peer to peer file sharing
etc.
2→ Companies like Intel, Cisco, HP, IBM use Python for hardware testing.
PAGE | 3 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

3→ Animation Company Maya uses Python Script to provide API (Application


Programming Interface). Similarly, 3ds Max, Blender, Cinema 4D, Houdini apply
Python 3D animation productions.
4→ A robot production company i-Robots uses Python to develop commercial robots.
5→ Python has got application in web development.
6→ Python has become the obvious choice for working in Scientific and Numeric
Applications.
7→ NASA and others use Python for their scientific programming task.
8→ Python is used for developing complex GUI and image processing
applications.
9→ Programmers deliver graphics software like Inkscape, Scribus, Paint Shop Pro etc.

GUI TO WRITE AND RUN PYTHON SOURCE CODE


To write and run (execute) python program we must install in our system a GUI (Graphical
User Interface) called IDLE (Integrated Development and Learning Environment)
We will be using version 3.6.5 of Python IDLE to develop and run Python code, in this
course. It can be downloaded from www.python.org
Python shell can be used in two ways, viz., interactive mode and script mode. In interactive
mode, we write the python statement (code) and the interpreter displays the result(s)
immediately.
In script mode, we type Python program in a new file and then use the interpreter to execute
the content from the file. For coding more than few lines, we should always save our code so
that we may modify and reuse the code.

WORKING IN INTERACTIVE MODE


When we start python IDLE (Integrated Development and Learning
Environment), we observe following window:

Primary prompt

>>> is a primary prompt indicating that the interpreter is ready to take a python command.
There is secondary prompt also which is “…” indicating that interpreter is waiting for
additional input to complete the current statement.
PAGE | 4 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

Example: 1→ Concept of script programming

Now as we hit the Enter Key the result is immediately shown, as is given below:

Example: 2 → What will be the output of following code in interactive mode?


A = -5
B=7
A + 4, B – 8
Output: It’s given below:

WORKING IN SCRIPT MODE


To create and run a Python script, we will use following steps in IDLE
1. File>Open OR File>New Window (for creating a new script file)
2. Write the Python code as function i.e. script
3. Save it (Ctrl + S )
4. Execute it in interactive mode- by using RUN option (^F5)
Otherwise (if script mode on) start from Step 2
Note: For every updating of script file, we need to repeat step 3 & step 4.
Example: 3 → Find the output of the following python code def test():
x=–4y
= –5
z=x+y
print z
Output: Code has been written in a file an1.py
PAGE | 5 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

When we click Run from Menu or click F4, the following output is shown:

INDENTATION
Leading whitespace (spaces and tabs) at the beginning logical line is important. This is called
indentation. Indentation is used to determine the level of the logical line, which in turn is used
to determine the grouping of statements.
It means that statements which go together must have same indentation. Each such statements
are called blocks. Let us understand it by the following code,
Example: 4 →
# File Name: indentation.py | Code by: A. Nasra
def test(): #Block.1 upto last
a = 12
b = 6
if a > b:
x = print('a is greater than b')#Block.2
y = print('Python is smarter.')
else:
x = print('a is less than b')#Block.3
y = print('Python is smarter.')
# For execution in Shell we have to call function
test()
PAGE | 6 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

MULTILINE SPANNING
String statements can be multi-line if we use triple quotes, as is given in the following
example,
Example: 5 → Multiline spanning
>>> big = """This is a multiline
... block of text.
... Python interpreter
... puts end_of_line mark
... at the end of each line."""
>>> big
'This is a multiline\n... block of text.\n... Python
interpreter\n... puts end_of_line mark\n... at the
end of each line.'

COMMENTS
Comments are used to explain notes or some specific information about whatever is written
in the Python code. Comments are not executed. In Python coding # is used for comments, as
shown below.
Example: 6 → Illustration of comments in Python
>>> print("I care my students.")#this is comment
I care my students.
>>> #note that comment is not executed.

Many IDE’s like IDLE provide the ability to comment out selected blocks of code, usually
with "#".

OBJECT
Object is an identifiable entity which combine data and functions. Python refers to anything
used in a program as an object. This means that in generic sense instead of saying
“Something”, we say “object”.
Every object has,
1. an identity - object's address in memory and does not change once it has been
created.
2. data type - a set of values, and the allowable operations on those values.
3. a value

DATA TYPES
Data type is a set of values, and the allowable operations on those values. Data type is of
following kind,
PAGE | 7 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

Data Types

Numbers None Sequence Set Mapping

Integer & Floating


Complex String Tuple List Dictionary
long Point

Boolean

Let us study all these data types one by one,

NUMBERS
The data types which store numbers are called numbers. Numbers are of three kinds,
1. Integer and Long (Integer also contains a data type known as Boolean)
2. Float or Floating point
3. Complex
1. INTEGERS AND LONG
Integers are the whole numbers consisting of + or – sign 100000, -99, 0, 17. While writing a
large integer value, we have not to use comma or leading zeros. For writing long integer, we
append L to the value. Such values are treated as long integers by python.
Example: 7 →
>>> a = 4567345
>>> type(a)
<class 'int'>
>>> # Interpreter tells that a is of integer type
>>> type(a*13)
<class 'int'>
Integers contain Boolean Type which is a unique data type, consisting of two constants, True
and False. A Boolean True value is Non-Zero, Non-Null and Non-empty.
Example: 8 →
>>> a, b = 23, 45
>>> a > b
False
>>> b > a + b
False
>>> type(a < c)
PAGE | 8 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

>>> c = a < b
>>> type(c)
<class 'bool'>

2. FLOAT (FLOATING POINT)


Numbers with fractions or decimal point are known as floating point numbers. It contain – or
+ sign (+ is understood if not provided) with decimal point.
Example: 9 →
>>> f1 = 2.3 + 4 + 6
>>> print(f1)
12.3
>>> type(f1)
<class 'float'>

3. COMPLEX
Complex numbers are pairs of real (float) and imaginary (float attached with the sign ‘j’ or
‘J’) numbers. It is of the form A + Bj, where A and B represent float j is defined as √−1.
Example: 10 →
>>> A = 9 - 7j
>>> print('Real-Part = ',A.real,'Imag-part =',A.imag)
Real Part = 9.0 Imaginary part = -7.0
>>> type(A)
<class 'complex'>

None (NoneType)
None is special data type that is used to signify the absence of any value in a particular
situation.
One such particular situation occurs with the print function. Print function displays text in the
console-window (often monitor); it does not compute and return a value to the caller. It is
clear from the following Example.16, where the The inner print function displayed the value
4 on in the console (it doesn’t return any value. Now there is no value for outer print function,
that’s why the outer print function displays None. We can assign the value None to any
variable. It represents “nothing” or “no object.”
Example: 11 →
>>> x = print(print('4'))
4
None
>>> type(x)
<class 'NoneType'>
PAGE | 9 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

SEQUENCE
An ordered collection of items is known as Sequence. This ordered collection is indexed by
positive integers. There are three kinds of Sequence data type – String, List and Tuple.

1. STRING (type str)


A string is a sequence of Unicode characters that may be a combination of letters, numbers,
and special symbols. To define a string in Python, we enclose the string in matching single (‘
’) or double (“ ”) quotes.
Example: 12 →
>>> a = 'Do you love Python?'
>>> type(a)
<class 'str'>
>>> type('p')
<class 'str'> #A string of length of 1 is a character.

Example: 13 →
>>> a = 'Do you love Python?\n'
>>> b = 'Yes, I love Python.'
>>> c = a + b
>>> print(c)
Do you love Python?
Yes, I love Python.

2. LIST
List is a sequence of values of any type. These values are called elements or items separated
by comma. Elements of list are mutable (changeable) and indexed by integers. List is
enclosed in square brackets [ ].
Example: 14 →
>>> L1 = [1, 564, 56.88, 'express', L1 'study', '*@(c)']
>>>
[1, 564, 56.88, 'express', 'study', '*@(c)']
>>> print(L1)
[1, 564, 56.88, 'express', 'study', '*@(c)']
>>> print(L1[3])
express
>>> type(L1)
<class 'list'>
PAGE | 10 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

3. TUPLE
Tuple is a sequence of values of any type. These values are called elements or items.
Elements of tuple are immutable (non-changeable) and indexed by integers. List is enclosed
in ( ) brackets.
Example: 15 → Concept of tuple.
>>> T1 = (7, 102, 'not-out', 50.75)
>>> print(T1)
(7, 102, 'not-out', 50.75)
>>> len(T1)
4
>>> T1[3]
50.75

SETS
Set is an unordered collection of values, of any type, with no duplicate entry. Sets are
immutable.
Example: 16 →
>>> A = set([1,2,3,1,4,5,7,6,5])
>>> print(A)
{1, 2, 3, 4, 5, 6, 7}
>>> len(A)
7

MAPPINGS
A mapping is a collection of objects identified by keys instead of order. Mapping is an
unordered and mutable. Dictionaries fall under Mappings.
NOTE – In mathematics mapping is defined as: If X and Y are two non-empty sets then a
subset f of XY is called a function(or mapping) from X to Y if and only if for each xX,
there exists a unique yY such that (x, y) f. It is written as f: X→Y

1. DICTIONARY (dict)
A dictionary is a collection of objects (values) which are indexed by other objects (keys)
where keys are unique. It is like a sequence of ‘key : value’ pairs, where keys can be found
efficiently. We declare dictionaries using curly braces {}. Keys must be immutable objects:
ints, strings, tuples etc.
Example: 17 →
>>> wheel={0:'green',1:'red',2:'black',3:'red',
4:'yellow',5:'green', 6:'orange',7:'violet'}
>>> wheel
PAGE | 11 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

{0: 'green', 1: 'red', 2: 'black', 3: 'red', 4:


'yellow', 5: 'green', 6: 'orange', 7: 'violet'}
>>> print(wheel[3])
red
>>> len(wheel)
8

VARIABLE
Variable is like a container that stores values that can be accessed or changed as and when we
need. If we need a variable, we will just think of a name and declare it by assigning a value
with the help of assignment operator = .
In algebra, variables represent numbers. The same is true in Python, except Python variables
also can represent values other than numbers.
Example: 18 → Illustration of variable in Python.
>>> q = 10 # this is assignment statement
>>> print(q)
10

The key to an assignment statement is the symbol = which is known as the assignment
operator. The statement assigns the integer value 10 to the variable q. Said another way, this
statement binds the variable named q to the value 10. At this point the type of q is int because
it is bound to an integer value.

RULES OF DECLARING VARIABLES


1→ Variable names must have only letters, numbers, and underscores. They can start with a
letter or an underscore, but not with a number. For example, a variable name may be
message_1 but not 1_message.
2→ Spaces are not allowed in variable names. Underscores can be used to separate words in
variable names. For example, greeting_message is valid, but greeting message is invalid.
3→ Python keywords and function names cannot be used as variable names.

MUTABLE AND IMMUTABLE VARIABLES


A variable (object) whose value can be changed in place, is called mutable variable. A
variable whose value cannot be changed in place, is called immutable variable. Modifying an
immutable variable will rebuild the same variable. Here rebuilt menas new object by the
same name.
As told before, everything in Python that can be named is an object. Every object has unique
identity that refers to memory location. If an object is mutable or not, can be known by the
built in function id().
PAGE | 12 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

Example: 19 → Illustration of mutable and immutable variables (object).


>>> x = 7 # x is number object (immutable)
>>> id(x)
1604073824
>>> x = 3*x # rebuilding x, not change inplace
>>> print(x)
21 # it seams that x in changed, no it is
# rebuilt because id is different.
>>> id(x)
1604074048

>>> L = [6, 7, 8]# List is mutable object


>>> id(L)
50857544
>>> L += [1] ''' L is changed in place, L = L +
[1]
is rebuilding
>>> print(L)
[6, 7, 8, 1]
>>> id(L)
50857544 # id is same
LIST OF IMMUTABLE VARIABLES

KEYWORDS
Keywords are the reserved words which are used by the interpreter to recognize the structure
of the program, they cannot be used as variable name.

and as assert break class continue def del


elif else except exec finally for from global
if import in is lambda not or pass
print raise return try while with yield nonlocal
 exec is no longer a keyword in Python 3.x
 nonlocal is added in Python 3.x, it is not in Python 2.x

Note:  Variables are created when they are assigned a value.


PAGE | 13 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

 Variables refer to object and it must be assigned a value before using it.

OPERATORS AND EXPRESSION


Operator is a symbol that does some operation on one or more than one values or variables.
The values or variables on which operation is done is called operand. The operator(s) together
with value(s) or/and variables, is called expression.
Example: 20 → Illustration of operators and operands.
>>> 3 + 4 # + is operator.3, 4 are operands
7
>>> # 3 + 4 is expression. The result/output of
the expression is called evaluation.

Example: 21 → Illustration of Expression.


>>> a, b, c = 9, 12, 3
>>> x = a - b/3 + c*2 - 1 #-, *, +, / are
operators.variable a, b, c, are variable with values
9,12,3.a-b/3+c*2-1 is expression.
The output(evaluation of expression) will be stored
in variable x.
>>> print('x = ',x)
x = 10.0

SOME IMPORTANT OPERATORS


1. Arithmetic or Mathematical Operators
2. Relational or Comparison Operators
3. Logical Operators
4. Assignment or Shorthand Operators

Arithmetic Operators
Operator Operator Name Examples
Symbol

+ Addition

- Subtraction

* Multiplication
PAGE | 14 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

/ Division
(Returns float in Python
3.5.6)

% Remainder / Modulo

** Exponentiation

// Integer division in Python


2.7;
Floor division in Python 3.5.6

Relational Operators
Operator Symbol Operator Name Examples

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal

== Equal to

!= Not equal to
PAGE | 15 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

Logical Operators
Operator Symbol Evaluation Examples

or x Y x or y

false false False

false true True

true false True

true true True

not x not y

false True

true False

and x Y x and y

false false False


Note: and behaves
false true False
Like multiplication.
true False False

true true True

PRESIDENCE OF OPERATORS
Operator Description
High → Low

** Exponentiation (raise to the power)

+, – unary plus and minus

*, /, %, // Multiply, divide, modulo, floor division

+, – Addition and subtraction


Low ←
High

<, <= , >, >= Comparison or Relation operators

==, != Equality operators

%= ,/=, //= , –=, +=, * Assignment operators


=

Not, and, or Logical operators


PAGE | 16 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

Example: 22 → Calculation of area of a rectangle.


>>> length = 15
>>> breadth = 9
>>> area = length*breadth

Area of ▭ = 135
>>> print('Area of \u25AD = ',area)

Perimeter of ▭ = 48
>>> print('Perimeter of \u25AD =‘,2*(length+breadth))

In the above example, we observe that the value of length and breadth are already given. It
means the user has no interaction with the program. For this type of interaction we need
input-output capability.

INPUT AND OUTPUT


The print function enables a Python program to display textual information to the user.
Programs may use the input function to obtain information from the user. The simplest use of
the input function assigns a string to a variable:
x = input() # in Python 3.6.5 and Python 3.7.x x = raw_input() #in Python
2.7.x
We must note that the input function produces only strings by default.
int(input('Please enter an integer value: ')) float(input('Enter a float
value:'))
uses a technique known as functional composition. The result of the input function is passed
directly to the int function instead of using the intermediate variables shown in
Interactive/Script Mode: add_2integers.py.
THE EVAL( ) FUNCTION
The eval function in Python is so powerful that it accepts int, float or str type data/value. The
eval function dynamically translates the text provided by the user into an executable form
that the program can process. This allows users to provide input in a variety of flexible ways;
for example, users can enter multiple entries separated by commas, and the eval function
evaluates it as a Python tuple. It is illustrated in the add_int.py file.
Example: 23 → CIllustration of eval() function.
# File Name: name.py | Script by: A. Nasra
x = input('Enter your name: ')
print('Hello dear',x,'! Do you want to ask
something?') y = input('...')
print('Dear',x,',you think too much! Your time is
up!') # Sample run of name.py
PAGE | 17 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

Enter your name: Pillai


Hello dear Pillai ! Do you want to ask something?
...What is science
Dear Pillai ,you think too much! Your time is up!

Example: 24 → A program to find area.


# File Name: area1.py | Script by: A. Nasra
l = float(input('Length of \u25AD = '))
b = float(input('Breadth of \u25AD = '))
area = l*b
print('Area of \u25AD = ',area)

Length of ▭ = 13.9
# Sample run of area1.py

Breadth of ▭ = 11
Area of ▭ = 152.9

Example: 25 → A program to tell future.


# File Name: num_fun.py | Script by: A. Nasra
x = int(input('Enter a number to know the future: '))
print('You\'ve entered',x,'!\nYou silly student!.\
nCan a numbers tell future?')
# Sample run of num_fun.py
Enter a number to know the future: 45
You've entered 45 !
You silly student!.
Can a numbers tell future?

Example: 26 → Program to add two integers.


# File Name: add_2int.py | Script by: A. Nasra
x = int(input('Enter an integer: '))
y = int(input('Enter another integer: '))
print(x,'+',y,'=',x+y)
# Sample run of add_2int.py
Enter an integer: 23
Enter another integer: 98
23 + 98 = 121

Example: 27 → Program showing flexibility of eval() function.


>>> n = eval(input('Enter a number: '))
Enter a number: 76
>>> print('Number is',n,'of',type(n))
Number is 76 of <class 'int'>
>>> n = 78.6
PAGE | 18 | LECTURE NOTE 1

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- -----------------------_-


-

>>> print('Number is',n,'of',type(n))


Number is 78.6 of <class 'float'>
>>> n = 'om'
>>> print('Number is',n,'of',type(n))
Number is om of <class 'str'>
>>> n = 78 + 6j
>>> print('Number is',n,'of',type(n))
Number is (78+6j) of <class 'complex'>

Example: 28 → Efficient use os eval() function.


# File Name: eval_sum.py | Script by: A. Nasra
num1, num2 = eval(input('Enter number1, number2: '))
print(num1,'+',num2,'=',num1+num2)
# While entering numbers, comma must be used.
# Sample run(s) of eval_sum.py
# Sample run - 1
Enter number1, number2: 78, 86
78 + 86 = 164
# Sample run - 2
Enter number1, number2: 7.8, 8.6
7.8 + 8.6 = 16.4
# Sample run - 3
Enter number1, number2: 7 + 8j, 8 + 6j
(7+8j) + (8+6j) = (15+14j)
# Sample run - 4
Enter number1, number2: 'School', '-Captain'
School + -Captain = School-Captain

You might also like