CSC 201 Scientific Programming Language (1) (Autorecovered)
CSC 201 Scientific Programming Language (1) (Autorecovered)
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 | 3 | LECTURE NOTE 1
Now as we hit the Enter Key the result is immediately shown, as is given below:
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 up to 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 | 5 | 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 | 6 | LECTURE NOTE 1
Data Types
Boolean
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 | 7 | LECTURE NOTE 1
>>> c = a < b
>>> type(c)
<class 'bool'>
3. COMPLEX
Complex numbers are pairs of real (float) and imaginary (float attached with the
is defined as √−1.
sign ‘j’ or ‘J’) numbers. It is of the form A + Bj, where A and B represent float j
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 | 8 | 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', 'study', '*@(c)']
>>> L1
[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 | 9 | 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 XY is called a function(or mapping) from X to Y if and
only if for each xX, there exists a unique yY 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 | 10 | LECTURE NOTE 1
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
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
Variables refer to object and it must be assigned a value before using it.
+ Addition
- Subtraction
* Multiplication
PAGE | 13 | LECTURE NOTE 1
/ Division
(Returns float in Python
3.5.6)
% Remainder / Modulo
** Exponentiation
Relational Operators
Operator Symbol Operator Name Examples
== Equal to
!= Not equal to
PAGE | 14 | 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
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.
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?