36
B25

Python Basics

Embed Size (px)

Citation preview

Page 1: Python Basics

B25

Page 2: Python Basics

B25

What will we learn today ?

1. The Python interpreter2. Variables and data-types 3. Arithmetic and logical operators 4. Control flow 5. Loops 6. Data structures 7. Functions 8. Exceptions and Error-handling 9. Modules

Page 3: Python Basics

B25

Python Interpreter$ gedit file.py$ python file.py

or

$python>>>

Page 4: Python Basics

B25

Variablesvariable_name = value

>>> answer = 42

>>> PI = 3.14

>>> team = ‘B25’

>>> truthy = True

>>> falsey = False

>>> nil = None

>>> choice = ‘a’

Page 5: Python Basics

B25 Data Types>>> type(answer)<type ‘int’>>>> type(PI)<type ‘float’>>>> type(team)<type ‘str’>>>> type(truthy)<type ‘bool’>>>> type(falsey)<type ‘bool’>>>> type(nil)<type ‘NoneType’>

Page 6: Python Basics

B25

IndentationIndentationError: expected an indented block Compiles

def spam():

pizza = 12

return pizza

print spam()

def spam():

pizza = 12

return pizza

print spam()

Page 7: Python Basics

B25

CommentsSingle Line comment Multiple Line comment

# I Love Python """I love to sleep, eat and play all day."""

Page 8: Python Basics

B25

Arithmetic Operators• Addition (+)

• Subtraction (-)

• Multiplication (*)

• Division (/)

• Exponentiation (**)

• Modulo (%)

Page 9: Python Basics

B25 Addition>>>pizza = 10>>> burger = 20>>> total_items = pizza +burger>>> print total_items30>>> print 6.7 – 0.76

Page 10: Python Basics

B25 Subtraction>>> income = 287

>>> expenditure= 250

>>> print income – expenditure

27

Page 11: Python Basics

B25 Multiplication>>> print 5 * 3

15

>>> PI = 3.14

>>> print PI * 100

314

Page 12: Python Basics

B25

Division>>> print 10 / 2

5

>>> print 10 / 3

3

>>> print 10 / 3.0

3.3333333333333335

>>> print 10.0 / 3

3.3333333333333335

Page 13: Python Basics

B25

Exponentiation ( ** )# The ** operator raises the first

# number, the base, to the power of the

# second number, the exponent

>>> print 2 ** 10

1024

>>> print 2 ** 0.5

1.4142135623730951

Page 14: Python Basics

B25 Modulo(%) >>> print 3 % 21

>>>y = 10%3>>>print y1

Page 15: Python Basics

B25

>>> caesar = “Et tu, Brute!"

>>> PI = ‘42’

>>> tyrion = “”” I’m a Lannister.

A Lannister always pays his debts.

”””

Strings

Page 16: Python Basics

Indexing In Strings

Indexing

Page 17: Python Basics

B25

OMG facts about Strings>>> print "Awesome” + “India”

AwesomeIndia

>>> print ‘pizza’ * 10

pizzapizzapizzapizzapizzapizzapizzapizzapizzapizza

Page 18: Python Basics

B25

String Methods● capitalize()● count()● index()● isalnum()● istitle()● upper()● find()● strip()● isdigit()● isspace()● lower()● startswidth()● replace()● isupper()● swapcase()● islower()

Page 19: Python Basics

B25 Control Flowvar = 100if var == 200: print “PLUTO" print var

elif var == 100: print "DONALD" print var

else: print "DAISY" print var

OUTPUT:DONALD100

Page 20: Python Basics

B25 Comparisons• Equal to (==)

• Not equal to (!=)

• Less than (<)

• Less than or equal to (<=)

• Greater than (>)

• Greater than or equal to (>=)

Page 21: Python Basics

B25 Booleans★ AND

★ OR

★ NOT

Order of execution:

not and or

Page 22: Python Basics

B25 Loops

While………

def factorial(n): num = 1 while n >= 1: num = num * n n = n - 1 return num

>>>fact(5)120

Page 23: Python Basics

B25

count = 10

while count > 0:

count += 1

Beware Of Loops That Never Ends

Page 24: Python Basics

B25Break Loops Using Breakcount = 0

while True:

print count

count += 1

if count >= 10:

break

Page 25: Python Basics

B25 Loops

For……for <item> in <collection>: <do something>

for letter in 'Python': # First Example print 'Current Letter :', letterCurrent Letter : PCurrent Letter : yCurrent Letter : tCurrent Letter : hCurrent Letter : oCurrent Letter : n

Page 26: Python Basics

B25 Loops

For……...for i in range(5,10): print i

56789

Page 27: Python Basics

B25 Data Structures

Lists….

List = [‘a’,’b’,’c’,’d’]

Numbers = [1,2,3,4]

Page 28: Python Basics

B25 Data Structures

List methods

● cmp(list1, list2)● len(list)● max(list)● min(list)● list(seq)● list.append(obj)● list.count(obj)● list.index(obj)● list.reverse()● list.pop()● list.remove(obj)● list.sort()

Page 29: Python Basics

B25 Data Structures

Dictionary…….

d = {'key1' : 1, 'key2' : 2, 'key3' : 3}

Page 30: Python Basics

B25 Data Structures

Dictionary methods

● clear() ● copy() ● get() ● has_key()● items() ● keys() ● pop() ● update()● values()● del dict_name[key_name]● dict_nme[key_name]=value

Page 31: Python Basics

B25 Functions

Page 32: Python Basics

B25Exceptions And Error Handlingtry:

<to do something>

except <an error>:

<do something different>

finally:

<and always do this>

Page 33: Python Basics

B25 Example>>> while True:... try:... x = int(raw_input("Please enter a number: "))... break... except ValueError:... print "Oops! That was no valid number. Try again..."

Page 34: Python Basics

B25 Importing modulesimport <module_name>

from <module_name> import <module>

from <module_name> import <m1>, <m2>

from <module_name> import <module1> as foo

from <module_name> import *

Page 35: Python Basics

B25 Example>>> import math

>>> print math.sqrt(25)

5

>>> from math import *

>>> sqrt(36)

6

Page 36: Python Basics

B25

THANK YOU