Docsity

Python notes on computer, Lecture notes of Computer Science

Partial preview of the text

Download Python notes on computer and more Lecture notes Computer Science in PDF only on Docsity!

Lecture Notes on Python Programming

and Gnuplot (SEM I: Paper CC1)

A brief introduction to Python

Python is a high level computer language, one of the latest in the market. Unlike, FORTRAN, C and other computer languages, it is an interpreter based language. As you keep writing each line on the command prompt (>>>) [Python interpreter]; it is being executed or interpreted in contrast to a FORTRAN or C program where the entire program has be executed at one go. We, of course, write the bigger and standard programs (scripts) in a file and then run it.

How to install Python on your computer?

To install Python on your desktop/ laptop over Microsoft Window, go to www.python.org/downloads/ and click “Download Python 2.7.X” (latest version) from any of the mirror sites.

For Linux based system one can install Python 2.7.X using following command from the terminal. $ sudo apt-get install python2.

Operation Syntax Addition (+) x+y= Subtraction (-) x-y= Multiplication () xy= Division (/) x/y= Modulus (%) [Remainder when x is divided by y]

x%y=

Power or exponent () xy= Rounding off (//) For example, if x=100, y= then 100/3=33 also 100//3= but 100.0/3=33.3333…whereas 100.0//3=33.

Mathematical Operators:

Consider two variables ‘x’ and ‘y’. Given x=8, y=

Input/Output Statements: [To write or print something.]

>>> print ‘I am learning Python. ’ I am learning Python. The output

If we write: >>> x= >>> print x 50

>>> x=input() # Wait for the input value of ‘x’. >>> x= input(‘Enter x: \n’) # \n is to send the cursor to next line Enter x: # Here we enter the value of ‘x’

For many inputs:

>>> x,y,z =input()

Play with a list: Properties and Utilities

>>> sorted(X) [-4, 0, 1, 3, 5, 9] # Arranging in ascending order

>>> sorted(X, reverse=True) [9, 5, 3, 1, 0, -4] # Arranging in descending order

>>> sorted(Y) [‘Alex’, ‘Asish’, ‘Sweta’, ‘Sudipta’]

>>> X+Y [3, 5, 1, 9, 0, -4, ‘Sudipta’, ‘Asish’, ‘Alex’, ‘Sweta’ ] # Sum of two lists

>>> X* [3, 5, 1, 9, 0, -4, 3, 5, 1, 9, 0, -4, 3, 5, 1, 9, 0, -4, ] # Repeated 3 times

>>> len(X) 6 # Total number of items in the list ‘X’

Play with a list: Properties and Utilities

>>> len(Y) # Total number of items in the list ‘Y’ 4

>>> sum(X) # Sum of the numbers in list ‘X’ 14

>>> max(X) # Maximum of the numbers in list ‘X’ 9

>>> min(X) # Minimum of the numbers in list ‘X’

>>> X.index(max(X)) # Location of the maximum in list ‘X’ 3

>>> X.index(1) # Location of ‘1’ in the list ‘X’ 2

*Note that the positions are counted from left: 0, 1, 2, 3….

List comprehension and slicing of lists

Filtering items in a list: Suppose we have a list. often, we want to gather only the items that meet certain criteria. Below we have a list of words, and we want to extract from it only the ones that contains ‘wo’.

>>> wood='How much wood would a woodchuck chuck if a woodchuck could chuk wood?'.split() >>> wood ['How', 'much', 'wood', 'would', 'a', 'woodchuck', 'chuck', 'if', 'a', 'woodchuck', 'could', 'chuk', 'wood?'] >>> wolist=[] >>> for x in wood: if 'wo' in x: wolist.append(x) >>> wolist ['wood', 'would', 'woodchuck', 'woodchuck', 'wood?']

or simply

>>> [x for x in wood if 'wo' in x] ['wood', 'would', 'woodchuck', 'woodchuck', 'wood?']

List comprehension and slicing of lists

Transforming items in a list

A list of word length, for every word in wood :

>>> [len(x) for x in wood] [3, 4, 4, 5, 1, 9, 5, 2, 1, 9, 5, 4, 5]

Slicing: >>> X=[1,4,9,0,-5,8,6] >>> X[-1] 6 >>> X[-2] 8 >>> X[1:3] [4, 9] >>> X[2:5] [9, 0, -5] >>> X[:5] [1, 4, 9, 0, -5]

>>> X[5:]

[8, 6]

>>> X[:]

[1, 4, 9, 0, -5, 8, 6]

>>> X[-3:]

[-5, 8, 6]

Numbers There are four kind of numbers that Python supports.  int [Integers with + ve or – ve sign] Examples : 57683, -  long [Long integers, integers of unlimited size] Examples: Any number followed by I or L. 345609L  float [Floating point real values, numbers with a decimal point] Examples: -0.03, 5.67, -6.626e-34, 2.303e

complex [Complex number of the form a+bj, j = − 1 ] Examples: 2.1-5j, 4.8j, 2.3e-12j

Examples: Operations with numbers >>> x=2.2e- >>> y=2e >>> xy*

>>> a= >>> b=-4.2j >>> a+b 3-4.2j

Examples: Presentation of numbers >>> x=345. >>>int(x) 345 >>> long(x) 345L

>>> a= >>>float(a)

>>> complex(a) 43+0j

>>>x= >>>y= >>>complex(x,y) 2+3j

Loops If we want to do something repeatedly, we put the instruction (s) inside a loop. In Python, it is a ‘for loop’. For easy execution of a ‘for loop’, we make use of a system function: range (begin, end, step). The range (n) function generates 0 to n-1, in increasing order.

>>> range(5) # Generate numbers from 0 to 4. [0,1,2,3,4] >>> range(1,10) # Numbers from 1 to 9. [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1,10,2) # Numbers from 1 to 9 with a interval 2. [1, 3, 5, 7, 9]

Example: For loop

structure of the ‘for loop’

For x in range(begin, end, step): Statement 1 Statement print…. Note that the statements are indented. Two statements have the same indentation. This means they are under the same loop (for loop). The print statement is not indented, which means it is outside the loop.

Decision making : Logical Statements

If statement

  • If
  • If….else
  • If…elif…else
  • Nested if

‘If’ is used for logical decision making, followed by one or more statements. ‘If…else’ is used when one decision is false, and we have to go for another decision. Nested if is used when one logical if is inside another logical if.

Examples:

If x==5: print ‘x = ’ , x OR If x==5: print ‘value of x is 5’

If x=5: print ‘ x is 5 ’ else: print ‘ x is not 5’

a,b,c =input(‘Enter a,b,c: \n’) x=bb-4a*c If x<0: print ‘x is negative’ elif x> print ‘x is positive’ else: print ‘x is zero’

If If….else If….elif….else

To Define Functions: A function block begins with the keyword ‘def’ followed by the name with parentheses () and colon, while the parameters are put inside it.

Example: def f(x): # Square of a number return x*x print f(2)

OR def main(): x= def f(x): return x*x print f(x) main()

System functions: What are system functions? System functions are some built-in functions that are kept in the system library for ready use. For every computer programming language, there is a system library.

Online help:

Type help(class/function/module/etc) in interpreter to get all the details about the concern class/function/module/etc. Example: >>> help(tuple) Help on class tuple in module builtin: class tuple(object) | tuple() -> empty tuple | tuple(iterable) -> tuple initialized from iterable's items | | If the argument is a tuple, the return value is the same object. | | Methods defined here: | | add(...) | x.add(y) <==> x+y | | contains(...) | x.contains(y) <==> y in x | | eq(...) | x.eq(y) <==> x==y

Basic idea of namespaces-local and global

A namespace is a collection of currently defined symbolic names along with information about the object that each name references. You can think of a namespace as a dictionary in which the keys are the object names and the values are the objects themselves. In a Python program, there are four types of namespaces,

  1. Build-In
  2. Global
  3. Enclosing
  4. Local
  • The built-in namespace contains the names of all of Python’s build-in objects. These are available at all times when Python is running. You can list the built-in namespace with the following command: >>>dir(builtins)
  • The global namespace contains any names defined at the level of the main program. Python creates the global namespace when the main program body starts, and it remains in existence until the interpreter terminates. The interpreter also creates a global namespace for any module that your program loads with the import statement.
  • The Local and Enclosing Namespaces: As we learned, the interpreter creates a new namespace whenever a function executes. That namespace is local to the function and remains in existence until the function terminates.