Lectures

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

PHC-101

Computer Programming
References
Introduction to computing
• Computer is employed for scientific research, e-commerce, banking,
weather prediction, etc.

• ENIAC (Electronic Numerical Integrator and Computer) - the first general-


purpose digital computer made in 1945.

• To optimally use a computer, knowledge about its memory capacity and


power of processors is required.

• Often, experiments and computer simulations complement each other.

• We can simulate stars on a computer, but it is impossible to perform


experiments on a star.
Components of a computer
von Neumann architecture

1. Processor
A unit that performs arithmetic and logical
operations

2. Memory
Data and program instructions are stored here.

3. Input/Output
Computer takes data from input devices, e.g.,
keyboard, mouse; and sends results to output
devices, such as, printer, terminal, etc.
Processor
This unit can perform billions of arithmetic and logical
operation per second.

The processor contains 64 cores residing in 16 blocks of


4 processors each.

The cores of the processor communicate with each


other via the memory block in the middle.

Each core has its own L1 and L2 caches, but 4 cores of a


block share 16 MB of L3 cache.

Cache, being closer to the core, is faster than RAM.

The cores communicate with each other, as well as to Inside Rome 7742 processor
the RAM and PCI devices, via buses.
Estimation of the peak performance
• The clock speed of the processor is 2.5 GHz.

• A Rome processor can perform 16 floating-point operations per clock


cycle.

• Hence, the peak performance of each core can be estimated to be


16x2.24 ≈ 35 Giga Floating-Point OPerations/Second (FLOPS).

• Consequently, the peak performance of a Rome processor is 35 x 64


cores ≈ 2.24 TeraFLOPS or TFLOPS.

• Such information is useful for estimating the time for a computing job.
Memory
• The data and programs reside in computer’s memory
also called random access memory (RAM).
1 byte = 8 bits
• The CPU reads the program and data from RAM and
write the results back on it.

• Note that RAM is active only when the computer is


powered on, hence it is a temporary memory.

• We need to write the data to the hard disk for


permanent storage.

• A desktop has RAM in the range of 4 Gigabytes to 64


Gigabytes.
RAM & Storage
• The clock speed of RAM ranges from 200 MHz Hard disk (HD) and Solid-state disk (SSD)
to 400 MHz, which is slower than processor’s
clock speed.
• HD and SSD are permanent storage of a
computer.
• Following strategies are adopted to offset this
deficiency of RAM:
• Programs and data reside here safely after
the computer is powered off.
1. The motherboard has multiple channels
or roads for data travel between the CPU
• When a computer is powered on, the
and the RAM.
required programs and data are
transferred from the HD to the RAM; this
2. The CPU has its own memory called
process is called boot up.
cache. The data which is needed
immediately is kept in the cache for a
faster access.
Computer Software: Operating System
• The Operating System (OS) makes a computer aware of its hardware—CPU, memory,
hard disk &
the connected input/output units—computer screen, keyboard, mouse, printer, etc.

• OS loads as soon as a computer is turned on; this process is called boot up.

• The OS performs the following tasks:


Unix OS
• The leading OS of today’s
computers are Unix and Windows.

• MacOS, the OS of Apple


Computers, is a variant of Unix.

• Unix itself consists of many


programs, which are categorized
into two classes:

Unix Kernel and Unix Shell

• Ubuntu OS is also based on Unix.


Application Softwares
• Everyday we use computers for many jobs:
▪ sending/receiving emails
▪ browsing internet
▪ watching movies
▪ playing songs
▪ writing documents
▪ occasionally programming.

• Each of these tasks are performed using application softwares. For example,
▪ we write documents using MS Word;
▪ browse internet using Firefox, Internet Explorer, Chrome, etc.
▪ watch movies using Mplayer, VLC, etc.
System Software and Programming Languages
• At the base level, a computer understands only two alphabets—0 and 1.

• Therefore, all the instructions and data are to be converted to strings of 0’s and 1’s.

• For example, an addition of two numbers A and B involves the following operations:
1. Get numbers A and B from the memory and put them into the CPU registers.
2. Add the numbers and put result A+B into another register.
3. Transfer the result from the register to the memory.

• The addition of numbers involves bitwise operations, such as 0+0=0, 1+0=1, 1+1=0 with
a carry of 1, etc.

• Such instructions, coded in binary, are called object code.

• It is cumbersome to write object codes for complex tasks, e.g., weather forecasting code.
System Software and Programming Languages
• Compilers and Interpreters help overcome this difficulty.

• A user writes programs in a higher-level language; then Compilers and Interpreters translate
these programs into object codes.

• These softwares save the programmer from the drudgery of writing object codes.

• The leading programming languages are C, C++, Fortran, Java, Python, Matlab, etc.

• In C, C++, and Fortran, complete computer programs is written first, after which the
programs are converted to object codes using compilers. Hence, C, C++, and Fortran are
called compiler languages.

• On the other hand, Python and Matlab interpreters execute the codes in pieces, hence
Python and Matlab are called interpreter languages.
Top programming languages
• The PYPL PopularitY of Programming
Language Index is created by
analyzing how often language
tutorials are searched on Google.

• The more a language tutorial is


searched, the more popular the
language is assumed to be. It is a
leading indicator. The raw data
comes from Google Trends.

https://pypl.github.io/PYPL.html?country=IN
Python
• Guido Van Rossum created Python programming language, which
appeared in 1991 for the first time.

• Python is used for a large number of applications:


Data types
• Integers: Integers are 32 bits long,–232 to 232 – 1.
• Long Integers: unlimited precision, limited by the memory
• Floating Point Numbers: Floating-point numbers are also known as
double-precision numbers and use 64 bits.
• Boolean: It can hold only one of two possible values: True or False.
• Complex Number: has a real and an imaginary component, both
represented by float types. 2+3j is a complex number.
• Strings: Sequences of Unicode characters.
• Lists: Ordered sequences of values.
• Tuples: Ordered, immutable sequences of values.
• Sets: Unordered collections of values.
• Dictionaries: Unordered collections of key-value pairs.
Naming rules
• You can use any names you want, as long as they follow these rules:
• Names must start with either a letter or an underscore character ( _ ).

• You can't use any of Python's reserved words or keywords.

These are words that have specific meanings to Python, such as if


(which begins an if statement).

• Names are case-sensitive. num is different from NUM and nUm.


• By convention, most Python programmers use lowercase for names
that stand for values. They use other rules for names that stand for
functions and classes

• It's a Good Idea to use meaningful names. If you name everything with
a single-letter, for example, you may have trouble remembering what the
name stands for later.
Line joining
• A physical line is a line that you see in a program.
• A logical line is a single statement.

• The end of a physical line marks the end of most statements (No ;).

• When a statement is too long to fit on a single line, you can join two
adjacent physical lines into a logical line by ensuring that the first physical
line has no comment and ends with a backslash (\).

• Python also joins adjacent lines into one logical line if an open
parenthesis ( ( ), bracket ( [ ), or brace ( { ) is not closed.
Characters
• Unicode (Universal Coded Character Set) is a standard that uses 16-bit
characters to represent characters on your computer. Unlike ASCII
(American Standard Code for Information Interchange), which consists of
8 bits, Unicode uses 16 bits and represents characters by integer value
denoted in base 16.

• A number does not include any punctuation and cannot begin with a
leading zero (0).

• Leading zeros are used for base 2, base 8, and base 16 numbers.

• For example, a number with a leading 0b or 0B is binary, base 2, and uses


digits 0 and 1. Similarly, a number with a leading 0o is octal, base 8, and
uses the digits 0 to 7, and a number with a leading 0x or 0X is
hexadecimal, base 16, and uses the digits 0 through 9, plus a, A, b, B, c, C,
d, D, e, E, f, and F.
Unary Operators
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Membership and Identity Operators
Operator precedence
Python data types: Characters
• The characters are encoded as numbers in a computer • In [124]: y = '&'

• In [125]: ord(y)
• Characters are enclosed within single quotes (‘.’) or double
• Out[125]: 38
quotes (“.”); both these quotes are used interchangeably.
• In [117]: x = '@' • In [126]: chr(38)
• Out[126]: '&'
• In [118]: ord(x)
• Out[118]: 64 • In [127]: print(chr(38))
• &
• In [119]: chr(64)
• Out[119]: ‘@’
• For a given decimal number y,
• Here, x represents character ‘@’, which is represented Python function chr(y) provides
using decimal number 64 in ASCII (American Standard the corresponding character in
Code for Information Interchange) format. ASCII representation.
• The Python function ord() provides the corresponding
ASCII value.
Python data types: Strings
• A Python string, which is an ordered sequence of
characters, is an important data types of Python.
In [16]: s1 = 'Prepare '
• A character is treated as a string with a single element. In [17]: s2 = 'very '
In [18]: s3 = 'well for MTE’
• Python strings too are enclosed within single quotes (‘
’) or double quotes (“.”). In [19]: s = s1+s2+s3

In [8]: s = 'Welcome to the course PHC-101' In [20]: s


Out[20]: 'Prepare very well for MTE’
In [9]: s
Out[9]: 'Welcome to the course PHC-101' In [21]: s_1 = s1+3*s2+s3
• Two strings can be added together using In [22]: s_1
concatenation operator, +. Out[22]: 'Prepare very very very well for MTE'

• Multiplication of a string by an integer, a replication


operation, yields a larger string with its multiple copies
strung together.
Strings
• Function str() converts an integer or a float In [29]: x1 = input('Enter the value of x\n')

to the corresponding strings. Enter the value of x


10
• We can read a string from the keyboard In [30]: x1
using the function input(). Out[30]: '10'

• Note that input() returns a string. In [31]: x = int(x1)


In [32]: xf = float(x1)

In [26]: x = 125.0 In [33]: x


In [27]: s_x = str(x) Out[33]: 10
In [28]: s_x In [34]: xf
Out[28]: '125.0' Out[34]: 10.0
String formatting
In [37]: print('This course is {}, and we are learning {}'.format('
...: programming', 'Python'))
This course is programming, and we are learning Python

In [39]: print('First name: {1}, last name: {0}'.format('Pandey',


...: 'Ambrish'))
First name: Ambrish, last name: Pandey

• In the above examples, {} are black boxes, whose values are


filled using the arguments of the format().
• We can also specify which arguments of format() fills which {}.

In [40]: print('Pi is {:2.2f}'.format(pi))


Pi is 3.14
In [41]: print('Pi is {:2.6f}'.format(pi))
Pi is 3.141593
List
Arrays
• A numpy array contains data of same type, and • linspace (start, stop, n): Returns uniformly-
its array size is fixed. distributed n real numbers from start to
stop.
• Note that unlike list, we cannot insert an
element in an array or delete an element of the • arange ([start,] stop [, step,]): Returns real
array. numbers from start to stop (excluding) in
steps of step. In a mixed array containing
• In a mixed array containing int and float, numpy int and float, numpy converts types of all
converts types of all the elements to float. the elements to float.
In [120]: x = array([1, 2, 3])
In [132]: linspace(-1,1,5)
In [121]: x.dtype Out[132]: array([-1. , -0.5, 0. , 0.5, 1. ])
Out[121]: dtype('int64')
In [133]: arange(1.5, 2.3, 0.1)
In [122]: x = array([1, 2, 3.])
Out[133]: array([1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2])
In [123]: x.dtype
Out[123]: dtype('float64')
Multidimensional arrays
In [139]: x = array([[4,5,6], [7,8,9], [1,2,3]])
• We can access the elements of a 2D array
In [140]: x using two indices [i,j] or [i][j]. In Python,
Out[140]: the data is stored in such a way that the
array([[4, 5, 6], column index moves faster than the row
[7, 8, 9], index.
[1, 2, 3]])
• For example, the elements of array x is
In [141]: size(x)
stored in sequence as [0,0], [0,1], [0,2],
Out[141]: 9
[1,0], [1,1], and [1,2].
In [142]: shape(x)
• This arrangement, called row-major order,
Out[142]: (3, 3)
is also followed in C and C++.
In [150]: x[0,:] • However, the array storage in Fortran
Out[150]: array([4, 5, 6]) follows column-major order.

In [151]: x[1,2]
Out[151]: 9
Operation on numpy arrays
Conditional flows
• In a computer program, we perform In [56]: x = 591
operations based on certain conditions. In [57]: if x%2 == 1:
...: print('{} is odd'.format(x))
• The code segments related to conditionals 591 is odd
are called conditional or branching
program structures. In [59]: x = 58
In [60]: if x%2 == 1:
...: print('{} is odd'.format(x))
...: else:
...: print('{} is even'.format(x))
58 is even

control-flow diagram
Further conditional branches
In [67]: x = 141
In [68]: if x%2 == 0:
...: print('{} is even'.format(x))
...: elif x%3 == 0:
...: print('{} is divisible by 3'.format(x))
...: else:
...: print('{} is neither divisble by 2 nor by 3')
141 is divisible by 3

Nature of roots of a quadratic equation


In [96]: a, b, c = 1, 2, 1
In [97]: discr = b**2-4*a*c
In [98]: if discr > 0:
...: print('two distinct real roots')
...: elif discr == 0:
...: print('equal roots')
...: else:
...: print('comple conjugate roots')
equal roots
Looping
• Programs typically involve repetitive In [110]: fruit_list = ['Apple', 'Mango', 'Grapes', 'Guava']

structures. ...: for fruit in fruit_list:


...: print(fruit)

• A for loop works as follows: Apple


Mango
Grapes
Guava

In [111]: n = int(input('Enter a number\n'))


...: print('You entered n = ', n)
...: # calculating the factorial
...: fact = 1
...: for j in range(2,n+1):
...: fact = fact*j
...: print('Factorial of {} = {}'.format(n, fact))
Enter a number
6
You entered n = 6
Factorial of 6 = 720
While loop
• Structure for a while loop: In [113]: fruit_list = ['Apple', 'Mango', 'Grapes', 'Guava']
...: no_of_fruits = len(fruit_list)

• while (expression): ...: j = 0


...: while j < no_of_fruits:

body of while loop ...: print(fruit_list[j])


...: j += 1

• The body of while loop is executed until Apple


Mango
condition of while (expression) statement
Grapes
remains True. Guava
In [116]: fact = 1
• The loop is terminated as soon as the ...: j = 2
condition becomes false. ...: while j <= n:
...: fact = fact*j
• A break statement could also be used to ...: j += 1
terminate the while loop. ...: print('Factorial of {} = {}'.format(n, fact))
Enter a number
7
You entered n = 7
Factorial of 7 = 5040
Functions
• A code segment that is used often can be def function_name (parameters):
abstracted as a function. body of the function
return statement
• Functions in a programming language provide the
following benefits:
In [4]: def factorial(n):
...: fact = 1
1. avoiding repetition of codes. ...: for j in range(2,n+1):
...: fact = fact*j
2. codes become smaller and readable with ...: return fact

functions. In [5]: n = int(input('Enter a number\n'))


...: print('You entered n = ', n)
3. Functions help modularise complex problems into ...: # calculating the factorial
...: fact = factorial(n)
smaller tasks. ...: print('Factorial of {} = {}’.
format(n, fact))
4. Different functions can be kept in different files; Enter a number
this arrangement makes programming manageable. 6
You entered n = 6
Factorial of 6 = 720
5. Modification of a program becomes easier with
functions.
Local and global scope
Output formatting
• In Python, there are several ways to print('%d'%a)
present the output of a program. 25
print('%4d'%a)
• Data can be printed in a human-readable 25
form, or written to a file for future use, or a = 25+4/7 print('%i'%a)
even in some other specified form. 25
print('%3u'%a)
25
a = 1+1/3
Output formatting
Version Meaning
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal.
u Unsigned decimal.
x Unsigned hexadecimal (lowercase).
X Unsigned hexadecimal (uppercase).
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()).
s String (converts any python object using str()).
% No argument is converted, results in a "%" character in the result.
Escape sequences
In [14]: print('Welcome to Computer Programming Course')
Welcome to Computer Programming Course

In [15]: print('Welcome to Computer \n Programming Course')


Welcome to Computer
\n Newline Programming Course

\t Tab In [16]: print('Welcome to Computer \t Programming Course')


\v Vertical tab Welcome to Computer Programming Course
\\ Literal backslash In [17]: print('Welcome to Computer Programming Course "PHC-101"')
\' Single quote Welcome to Computer Programming Course "PHC-101"
\" Double quote In [18]: print('Welcome to Computer Programming Course \'PHC-101\'
Welcome to Computer Programming Course 'PHC-101'

In [19]: print('Welcome to Computer Programming Course \"PHC-101\"


Welcome to Computer Programming Course "PHC-101"
Dictionary
• Dictionaries provide a mutable data In [25]: phc_lab = {'EP1': ['Mon', '11-13'], 'BP1': 'Tue', 'EP2':'Wed’}
structure that can be accessed through
In [26]: phc_lab['EP1']
mapping method. Out[26]: ['Mon', '11-13']

In [27]: phc_lab['BP1']
• Dictionaries are constructed using curly Out[27]: 'Tue’
brackets with each element consisting of
a key and a value, separated by a colon: In [28]: phc_lab.keys()
Out[28]: dict_keys(['EP1', 'BP1', 'EP2'])

In [29]: phc_lab.values()
• dict1 = {key1:val1, key2:val2:, key3:val3} Out[29]: dict_values([['Mon', '11-13'], 'Tue', 'Wed'])

In [30]: phc_lab.items()
Out[30]: dict_items([('EP1', ['Mon', '11-13']), ('BP1', 'Tue'), ('EP2',
'Wed')])

You might also like