introduction to python

38
Introduction To Python Basics, sequences, Dictionaries, Sets

Upload: baabtracom-first-coding-school-in-india

Post on 20-May-2015

338 views

Category:

Technology


3 download

TRANSCRIPT

Page 1: Introduction to python

Introduction To PythonBasics, sequences, Dictionaries, Sets

Page 2: Introduction to python

Python

– Python is an interepted language, which can save you considerable time during program development because no compilation and linking is necessary.

Page 3: Introduction to python

How to install Python

• Download latest version of python and install it on any drive: say D:\python

• Then follow the steps–Got to Control Panel -> System ->

Advanced system settings–Click the Environment

variables... button–Edit PATH and append ;d:\Python to

the end–Click OK. –Open command prompt type

python and enter

Page 4: Introduction to python

C Vs PythonSyntax comparison

Page 5: Introduction to python

Commenting

// comment single line

/* comment multiple lines */

# comment single line

“ ” ” comment multiple lines “ ” ”

C Python

Page 6: Introduction to python

Variables

//Declaring a variable

Int a=10;Char c=‘a’;Float f=1.12;

//Cannot assign multiple values

a=b=4 // Will result error

#No need of prior Declarations

a=10 c=‘a’f=1.12

#Can assign multiple values simultaneously

x = y = z = 10a, b, c = 1, 2, "john"

C Python

Page 7: Introduction to python

OutPut

printf(“Hello baabtra”);

Int a=10,b=25;Printf(“%d %d”,a,b);

Printf(“value of a=%d and b= %d”,a,b)

print(“Hello baabtra”)

a=10b=25print(a,b)

print (“value of a=%d and b= %d” % (a,b))

C Python

Page 8: Introduction to python

InPut

int a;Printf(“Enter the

number”);scanf(“%d”,&a);

a=input(“Enter the number”)

C Python

Page 9: Introduction to python

Arrays

int a[]={12,14,15,65,34};

printf(“%d”, a[3]);

 No Arrays ! Instead Lists

a = [12,14,15,16,65,34,’baabtra’]

C Python

Page 10: Introduction to python

Arrays

int a[]={12,14,15,65,34};

printf(“%d”, a[3]);

 No Arrays ! Instead Lists

a = [12,14,15,16,65,34,’baabtra’]

C Python

[ 12 , 14 , 15 , 16 , 65 , 34 , ’baabtra’ ] 0 1 2 3 4 5 6 -7 -6 -5 -4 -3 -2 -1

Page 11: Introduction to python

Lists in detail

• Print(a[2:5]) # prints 15,16,65• Print(a[-6:-2]) # prints 14,15,16,65• Print(a[4:]) # prints

65,34,baabtra• Print(a[:2]) # prints 12,14,15• a[2] = a[2] + 23; # Lists are

mutable,we can change individual items• a[0:2] = [1, 12] # We can replace a

group of items together• a[0:2] = [] # We can remove

items together• a[:] = [] # Clear the list

Page 12: Introduction to python

Lists in detail

• a.append(25) # adds an element at the end of list

• b =[55,66,77] a.extend(b) a=a+b;

• a.insert(1,99) # Inserts 99 at position 1

• a.pop(0) # pop elements at position 0

# Combines two lists

Page 13: Introduction to python

Strings

char a[]=“baabtra”; a= ‘baabtra’b=“doesn’t”C=“baabtra \”mentoring

partner\””

Strings are character lists, So can be used like any other lists as we discussed earlier

print (a[0])a.append(“m”);

C Python

Page 14: Introduction to python

Strings in detail

• String slicingword=‘hello baabtra’print(word[6:] # prints baabtraword[: 6] # prints ‘hello ‘

word2= ‘good morning’ + word[6:]Print(word2) # prints ‘good

morning baabtra‘

Page 15: Introduction to python

Control structures

• Conditional Control Structures• If• If else• Switch

• Loops• For• While• Do while

Conditional Control Structures• If• If else• Switch

Loops

• For• While• Do while

C Python

Page 16: Introduction to python

If else

int a;Printf(“Enter the

number”);scanf(“%d”,&a);If(a>80)

Printf(“Distiction”);else if(a>60)

Printf(“First class”);else {

Printf(“Poor performance\n”);Printf(“Repeat the exam\n”); }

a=input(“Enter the number”)

if a>80 : print(“Distinction”)

elif a>60 : print(“First Class”)

else : print(“Poor performance”)print(“Repeat the exam”)

C Python

Page 17: Introduction to python

While Loop

int i=0;whil(i<10){

printf(“%d”, i);i=i+1;

}

i=0while i<10: print(i) i=i+1

C Python

Page 18: Introduction to python

For Loop

int i=0;for(i=0;i<10;i++){

printf(“%d”, i);}

It’s quite a bit untraditional . We need to define a range on which loop has to iterate. This can be done usingRange(10,20) // creating a list with elements from 10 to 20

For i in range(10) : print(i) //print numbers up to 10

a=[12,14,16,’baabtra’]For i in a : print(i) //prints 12,14,16,baabtra

C Python

Page 19: Introduction to python

Other Control structure statements

• Break

Eg: If(a%2==0) { Print(“even”); break; }

• BreakThe break statement is allowed only inside a loop body. When break executes, the loop terminates.

Eg: for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x break

C Python

Page 20: Introduction to python

Other Control structure statements

• Continue

for(i=1;i<20;i++){

if(i%2==1) Continue;Print(“%d is even”,i);}

• ContinueThe continue statement is allowed only inside a loop body. When continue executes, the current iteration of the loop body terminates, and execution continues with the next iteration of the loopEg:For i in range(1,20) If i%2==0: continue print(“%d is even” %(i))

C Python

Page 21: Introduction to python

Other Control structure statements

for(i=1;i<20;i++){

if(i%2==1) {}

else Print(“%d is even”,i);

}

• passThe pass statement, which performs no action, can be used when you have nothing specific to do. Eg:if a<10: print(“less than 10”)

elif x>20: pass # nothing to be done in this case

Else: print(“in between 10 and 20”)

C Python

Page 22: Introduction to python

Functions

Int findSum(int a,int b)

{int c;c=a+b;return c

}

d=findSum(10,15);

def findSum(a,b) : return a+b

sum=findSum(112,321)print(sum)

C Python

Page 23: Introduction to python

Task

• Write a simple python program which will have an array variable as below

• a= [50,15,12,4,2]

• Create 3 functions which will take the above array as argument and returns the arithmetic output

–Add() //Outputs 83–Substract() //Outputs 17–Multiply() //Outputs 72000

Page 24: Introduction to python

That was the comparison !

So what’s new in python?

Page 25: Introduction to python

Sequences

Page 26: Introduction to python

Sequences

• A sequence is an ordered container of items, indexed by non-negative integers. Python provides built-in sequence types ,they are:-– Strings (plain and Unicode), // We

already have discussed– Tuples– Lists // We already have

discussed

Page 27: Introduction to python

Tuples

Page 28: Introduction to python

Tuples• A tuple is an immutable ordered sequence of items which may be of different

types. – (100,200,300) # Tuple with three items– (3.14,) # Tuple with one item– ( ) # Empty tuple

• Immutable means we cant change the values of a tuple• A tuple with exactly two items is also often called a pair.

Page 29: Introduction to python

Operation on Tuples

tpl_laptop = ('acer','lenova','hp','TOSHIBA') tpl_numbers = (10,250,10,21,10)

tpl_numbers.count(10) # prints 3tpl_laptop.index('hp') # prints 2

Page 30: Introduction to python

Task

• Create a python program that will accept two tuples as arguments and return the difference between the tuple values,

Page 31: Introduction to python

Dictionaries

Page 32: Introduction to python

Dictionaries

• A dictionary is an arbitrary collection of objects indexed by nearly arbitrary values called keys. They are mutable and, unlike sequences, are unordered.–Eg :{ 'x':42, 'y':3.14, 'z':7 } –dict([[1,2],[3,4]]) # similar to

{1:2,3:4}

Page 33: Introduction to python

Operation on Dictionaries

• dic={'a':1,'b':2,'c':3} – len(dic) # returns 3– del dic['a'] # removes element

with key ‘a’– a in dic # returns ‘True’ .Bur– dic.items() #Displays

elements– for i in dic.iterkeys():

... print i # Returns key– for i in dic. itervalues():

... print i # Return values

Page 34: Introduction to python

Task

• Write a python program with a dictionary variable with key as English word and value as meaning of the word.

• User should be able to give an input value which must be checked whether exist inside the dictionary or not and if it is there print the meaning of that word

Page 35: Introduction to python

Sets

Page 36: Introduction to python

Sets

• Sets are unordered collections of unique (non duplicate) elements. – St= set(‘baabtra calicut’)– print (st) #prints

{‘r’,’u’,’t’,’c’,’b’,’a’,’i’,’l’}

Page 37: Introduction to python

Operation on sets

• st1=set(‘baabtracalicut’)• st2=set(‘baabtra’)– st1.issubset(st2) #Returns

true– st2.issuperset(st1) #Returns

true– st1. remove(‘mentoringpartner') – st1. remove(‘calicut)

Page 38: Introduction to python

Questions?“A good question deserve a

good grade…”