× MAIN HOME Introductions Notes Programmes

MODULE I


Python Quickstart

Function Use
print("Hello, World!") To display a Message
C:\Users\Your Name>python myfile.py Running python file in the Command Line
x = 5
y = "Hello, World!"
a,b = 10,"john"
Assigning value to vaiable
Python Indentation
if 5 > 2:
   print("Five is greater than two!")
Spaces at the beginning of a code line.
Python uses indentation to indicate a block of code.
#This is a comment comment
""" This is a comment written in more than just one line """ multi line comment


Python input() Function

The input() function allows user input

Syntax input(prompt)
Example x = input('Enter your name:')
print('Hello, ' + x)
Output Hello Me


Python output() Function

We use the print() function to output data to the standard output device (screen).

Syntax print(prompt)
Example print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
Output 1 2 3 4
1*2*3*4
1#2#3#4&

Output formatting


Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format() method. This method is visible to any string object.

>>> print('I love {0} and {1}'.format('bread','butter'))
>>> print('I love {1} and {0}'.format('bread','butter'))


OUTPUT:
I love bread and butter
I love butter and bread


Python Import

When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a filename and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter in Python. We use the import keyword to do this.

Example 1)import math
  print(math.pi)

2)>>> from math import pi
  >>> pi
Output 3.141592653589793

We can also add our own location to this list.


Operators

Types of Operators Python language supports the following types of operators.

  1. Arithmetic Operators
  2. Comparison (Relational) Operators
  3. Logical Operators
  4. Bitwise Operators
  5. Membership Operators
  6. Identity Operators

Arithmetic Operators


Operator Description Example
+ Addition Adds values on either side of the operator. a + b
- Subtraction Subtracts right hand operand from left hand operand. a-b
* Multiplicatio Multiplies values on either side of the operator a * b
/ Division Divides left hand operand by right hand operand b / a
% Modulus Divides left hand operand by right hand operand and returns remainder b % a
// Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. 9//2 = 4

Comparison Operators


Operator Description Example
== If the values of two operands are equal, then the condition becomes true. (a == b)
!= If values of two operands are not equal, then condition becomes true. (a != b)
<> If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is similar to != operator.
> If the value of left operand is greater than the value of right operand, then condition becomes true. (a>b)
<< If the value of left operand is less than the value of right operand, then condition becomes true. (a < b)
>= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b)
<= If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b)

Assignment Operators


Operator Description Example
= Assigns values from right side operands to left side operand c = a + b
+= It adds right operand to the left operand and assign the result to left operand c+=a
-= It subtracts right operand from the left operand and assign the result to left operand c -= a
*= It multiplies right operand with the left operand and assign the result to left operand c*=a
/= It divides left operand with the right operand and assign the result to left operand c/=a
%= It takes modulus using two operands and assign the result to left operand c%=a
**= Performs exponential (power) calculation on operators and assign value to the left operand c**=a

Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13;


Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands. (a&b)=12
(means 00001100)
| Binary OR It copies a bit if it exists in either operand. (a | b) = 61
(means 0011 1101)
^ Binary XOR- It copies the bit if it is set in one operand but not both. (a ^ b) = 49
(means 0011 0001)
~ Binary Ones Complement- It is unary and has the effect of 'flipping' bits. (~a ) = -61
(means 1100 0011 in 2's complement form due to a signed binary number.
<<< Binary Left Shift- The left operands value is moved left by the number of bits specified by the right operand. a << 2=240
(means 1111 0000)
>> Binary Right Shift- The left operands value is moved right by the number of bits specified by the right operand. a >> 2 = 15
(means 0000 1111)

Logical Operators


Operator Description Example
and Logical AND- If both the operands are true then condition becomes true. (a and b)
or Logical OR -If any of the two operands are non-zero then condition becomes true. (a or b)
not Logical NOT - Used to reverse the logical state of its operand. not(a and b)

Membership Operators


Operator Description Example
in Evaluates to true if it finds a variable in the specified sequence and false otherwise. x in y, here in results in a 1 if x is a member of sequence y.
not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.

Identity Operators


Operator Description Example
is Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y).
is not Evaluates to false if the variables on either side of the operator point to the same object and true otherwise. x is not y, here is not results in 1 if id(x) is not equal to id(y).


Python Data Types

The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.

Python has five standard data types:

  1. Numbers
  2. String
  3. List
  4. Tuple
  5. Dictionary
1. NUMBERS

Number data types store numeric values. Number objects are created when you assign a value to them.

Python supports four different numerical types:

  • int (signed integers)
  • long (long integers, they can also be represented in octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers)

2. STRINGS

Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.

Example

	str = 'Hello World!' 
	print str     
	print str[0]   
	print str[2:5] 
	print str[2:]  
	print str * 2      # Prints string two times 
	print str + "TEST" # Prints concatenated string 

Output

	Hello World!
	H
	llo
	llo World!
	Hello World!Hello World! 
	

3. LISTS

Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.

The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

Example

	list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] 
	tinylist = [123, 'john'] 
 
	print list          # Prints complete list 
	print list[0]       # Prints first element of the list 
	print list[1:3]     # Prints elements starting from 2nd till 3rd  
	print list[2:]      # Prints elements starting from 3rd element 
	print tinylist * 2  # Prints list two times 
	print list + tinylist # Prints concatenated lists 
	

Output

	['abcd', 786, 2.23, 'john', 70.200000000000003] 
	abcd 
	[786, 2.23]
	[2.23, 'john', 70.200000000000003] 
	[123, 'john', 123, 'john'] 
	['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john'] 
	

4. TUPLES

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as readonly lists.

Example

	tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  ) 
tinytuple = (123, 'john')

print tuple # Prints complete list print tuple[0] # Prints first element of the list print tuple[1:3] # Prints elements starting from 2nd till 3rd print tuple[2:] # Prints elements starting from 3rd element print tinytuple * 2 # Prints list two times print tuple + tinytuple # Prints concatenated lists

Output

	('abcd', 786, 2.23, 'john', 70.200000000000003) 
	abcd 
	(786, 2.23) 
	(2.23, 'john', 70.200000000000003) 
	(123, 'john', 123, 'john') 
	('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john') 
	

5. DICTIONARY

Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).

Example

	dict = {} 
	dict['one'] = "This is one" 
	dict[2]     = "This is two" 
	tinydict = {'name': 'john','code':6734, 'dept': 'sales'} 
	print dict['one']       # Prints value for 'one' key 
	print dict[2]           # Prints value for 2 key 
	print tinydict          # Prints complete dictionary 
	print tinydict.keys()   # Prints all the keys 
	print tinydict.values() # Prints all the values 

Output

	This is one 
	This is two 
	{'dept': 'sales', 'code': 6734, 'name': 'john'}
	['dept', 'code', 'name'] 
	['sales', 6734, 'john']
	


Decision Making

Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions. Decision

TYPE DESCRIPTION SYNTAX
if statements if statement consists of a boolean expression followed by one or more statements. if expression:
    statement(s)
if...else statements if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE. if expression:
    statement(s)
else
    statement(s)
nested if statements You can use one if or else if statement inside another if or else if statement(s).
if expression1: 
   statement(s) 
elif expression2: 
   statement(s) 
elif expression3: 
   statement(s)

Looping

A loop statement allows us to execute a statement or group of statements multiple times.

LOOP TYPE DESCRIPTION SYNTAX EXAMPLE
while loop Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
while expression: 
   statement(s) 
	
count = 0 
while count < 5: 
   print count, " is  less than 5" 
   count = count + 1 
	
for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
for iterating_var in sequence: 
   statements(s) 
	
fruits = ['banana', 'apple',  'mango'] 
for fruit in fruits:        # Second Example 
   print 'Current fruit :', fruit 
	
nested loop You can use one or more loop inside any another while, for or do..while loop.
for iterating_var in sequence: 
   for iterating_var in sequence: 
      statements(s) 
   statements(s)
while expression: while expression: statement(s) statement(s)
i = 2 
while(i < 100): 
   j = 2 
   while(j <= (i/j)): 
      if not(i%j): break 
      j = j + 1 
   if (j > i/j) : print i, " is prime" 
   i = i + 1 
 
print "Good bye!" 
	


Python Methods


String Method

METHOD DESCRIPTION
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
count() Returns the number of times a specified value occurs in a string
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() isdigit()
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
lower() Converts a string into lower case
upper() Converts a string into upper case
replace() Returns a string where a specified value is replaced with a specified value
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case

List Methods

METHOD DESCRIPTION
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of=20 elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

Tuple Methods

METHOD DESCRIPTION
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where it was found

Dictionary Methods

METHOD DESCRIPTION
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary