You are on page 1of 17

Introduction to Python

Hemanta Bhattarai CDP,TU July 19, 2013

2 Special thanks to Saroj Dhakal, who helped me to correct the errors. Any suggestion are heartly welcomed

Contents
1 General Introduction: 2 Simple calculations: 2.1 Assignments to variables: 2.2 Print data: . . . . . . . . 2.3 Input data: . . . . . . . . 2.4 Simple calculation: . . . . 2.5 List: . . . . . . . . . . . . 5 7 7 7 8 8 9

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

3 Logical operation: 11 3.1 Relational operation: . . . . . . . . . . . . . . . . . . . . . . . . . 11 3.2 Logical operation: . . . . . . . . . . . . . . . . . . . . . . . . . . 11 4 Control statments: 5 Functions: 6 File Handeling: 13 15 17

CONTENTS

Chapter 1

General Introduction:
Python is versatile programming language which can be used in dierent elds like economics, computer science, physics, statistics, mathematics e.t.c.

Why python: Open Source Many packages can be found. Used in many universites for research purpose Easy to code

Where to code: Code can be written in IDE which helps us in lling up syntax Code can be written in text editor and save in .py extension. Its good to write in gedit coz it helps to point out syntax error by change in color

How to execute the code: In IDE there is run option so we can easily execute the code Run terminal (Cltr T) and execute the code by typing python <path of the code (.py) le >

Here we will write code in gedit Use terminal to execute the code
5

CHAPTER 1. GENERAL INTRODUCTION:

Chapter 2

Simple calculations:
2.1 Assignments to variables:

We can assign data to variable by simply writing a=2 The data type can be integer, oat, strings e.t.c. To know the data type we can use function type e.g type(a) We can assign strings by a=Hello

2.2

Print data:

First program to print is print(hello welcome to computing world) If we want to print assigned data a=2 print a simple program for assignment and printing a=2 b=3 print a+b In other way a=2 b=3 print (The sum is %g)%(a+b) %g for integers %f for oats %s for strings Or in other way print (The sum is),a+b 7

8 Dierent data types %g %f %c %s integer float complex number string

CHAPTER 2. SIMPLE CALCULATIONS:

2.3

Input data:

If we to want user to input data then we use input or raw input

Input data as a string: a=raw_input("Enter you name") type(a) age=raw_input("Enter your age") type(age) Input data as a integer or oat b=input("Enter you age") type(b)

2.4

Simple calculation:

Add two number and print the sum a=2 b=3 sum=a+b print a+b print "The sum of ",a, "and", b, "is", sum print("The sum of %g and %g is %g"%(a,b,sum)) Ask user to enter two number m and n and print result mn , m/n ,m n and reminder of m/n m=input(Enter first number) n=input(Enter second number) power=m**n prod=m*n div=m/n div2=float(m)/n

2.5. LIST:

reminder=m%n # % operator is called modulo operator print "The m^n is", power print "The product is", prod print "The division is ",div,div2 print "The remider is ",reminder

2.5

List:

Dene a list age=[10,20,30,40,50,60] Dierent operation of list age.apppend(79) age.pop() age.insert(2,100) age.remove(30) age.index(79) age.count(50) age.sort() age.reverse() # add data at last of list # prints data at last index Note: Index starts from 0 # list.insert(i,x) insert data x in i index of list #list.remove(x) removes all the data x from list #list.index(x) gives index of the data x #list.count(x) gives the count of data x in list #list.sort() sorts the list in ascending order #list.reverse() reverses the list # a list is defined with variable name age

10

CHAPTER 2. SIMPLE CALCULATIONS:

Chapter 3

Logical operation:
3.1 Relational operation:

These operators gives the relation (like greater, smaller, equal and not equal) between two data Symbols for the relational operators a<b a>b a >= a <= a == a !=

b b b b

# gives True if correct else gives False

3.2

Logical operation:

This operation executes certain segment of program if true and other segment if false. Syntax: if <condition>: statments elif <conditions>: statements elif <conditions>: statements else: statements Example 1: To check if a number is odd or even 11

12

CHAPTER 3. LOGICAL OPERATION: a=input("Enter a number") if a%2==0: print"the number is even" else: print "the number is odd" Example 2: To determine the division of students if marks and total marks is given marks=input("Enter your marks") total=input("Enter your total marks") per=(float(marks)/total)*100 #calculating the percentage if per > 100: print "Invalid entry" elif per<=100 and per>=75: print"Distinction" elif per<75 and per>=65: print"First division" elif per<65 and per>=55: print"Second division" else: print"Third division" Example 3:Check if the age is between 18 and 40. age=input("Enter your age") if age<18 or age>40: print "The age is out of limit" else: print"The age is in the limit"

Chapter 4

Control statments:
These are the statemts that controls the ow of the program during execution. for loop while loop For loop Syntax: for <var> in <list>: <statements>

# First it sets index=0 and at succesive iteration it increases index by 1 and checks if # if true executes <statements> else leaves the loop Example: Print number from 50 to 100 with the interval of 7 for var in range(50,100,7): print var

# range(start, end, dx), makes a list from start to end with interval of dx # range(end), makes a list starting from 0 to end with interval of 1 # range(star, end), makes a list starting from start and ending on end.

While loop: Syntax: while <condtion>: <statements> # checks the conditon if true executes statements else jumps out of loop 13

14

CHAPTER 4. CONTROL STATMENTS: Example: Print all the even numbers from 1 to 50 counter=1 while counter<=50: if counter%2==0: print counter counter=counter+1 Nested loop: If we place a control statements as the statement of other control statement then it is called nested loop. Here one loop is nested inside other loop. for <var> in list1: for <var> in list2: <statements> #Nested for loop

********************************************************************************** while <condition>: while <condition>: <statements>

#Nested while loop

********************************************************************************** for <var> in list1: while <condition>: <statements>

#While nested in for loop

**********************************************************************************

while <condtion>: for <var> in list: <statements>

#for nested in while loop

********************************************************************************** Example:Dene a 22 matrix.Find the sum of all the elements mat=[[2,3],[6,7]] #Define 2X2 matrix, nested list sum=0 for i in range(2): for j in range(2): sum=sum+mat[i][j] print "The sum of elements of matrix is", sum

Chapter 5

Functions:
In built functions: There are several in-built function in python which can be exported from dierent packages like numpy, pylab, scipy etc. There are several maths functions which can be used during programming like sin() cos() sinh() cosh() exp() asin() acos() log() sqrt()

These funtions are dened in math.py le so we must import this le in programming. import math from math import sin y=math.sin(3.14) x=sin(3.14) User dened function: It will be trobulsome to debug a huge program so the program is divided into dierent segments by dening user dened functions. So it is highly recommended to make UDF for all the programs so we will be habituated to this. Syntax: def function_name(function_arguments): <statements> <statements> ............ ............ ............ return <value> 15

16 Example: Simple function for add def add(a,b): c=a+b return c #save as add.py format.

CHAPTER 5. FUNCTIONS:

import sys sys.path.append(<path-of-folder-containing-the-function-file-or-module>) import add def main(): a=2;b=4 sum=add.add(a,b) print "The average is ",sum main() Example: UDF to nd factorial of given number def factorial(n): fact=1 i=1 while i<=n: fact=fact*i i=i+1 return fact

Chapter 6

File Handeling:
Some time the data from the program must be saved in the .dat or .txt format. Some time data must be read from .dat and .txt format. And to read and write data in a le is called le handeling. To open le: file=open(<file-name>,operation) example file=open(data.txt,w) There are dierent operation possible like read, write and append e.t.c. Read Write Append To write to a le file.write(data) r w a

17

You might also like