python basics
TRANSCRIPT
B25
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
B25
Python Interpreter$ gedit file.py$ python file.py
or
$python>>>
B25
Variablesvariable_name = value
>>> answer = 42
>>> PI = 3.14
>>> team = ‘B25’
>>> truthy = True
>>> falsey = False
>>> nil = None
>>> choice = ‘a’
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’>
B25
IndentationIndentationError: expected an indented block Compiles
def spam():
pizza = 12
return pizza
print spam()
def spam():
pizza = 12
return pizza
print spam()
B25
CommentsSingle Line comment Multiple Line comment
# I Love Python """I love to sleep, eat and play all day."""
B25
Arithmetic Operators• Addition (+)
• Subtraction (-)
• Multiplication (*)
• Division (/)
• Exponentiation (**)
• Modulo (%)
B25 Addition>>>pizza = 10>>> burger = 20>>> total_items = pizza +burger>>> print total_items30>>> print 6.7 – 0.76
B25 Subtraction>>> income = 287
>>> expenditure= 250
>>> print income – expenditure
27
B25 Multiplication>>> print 5 * 3
15
>>> PI = 3.14
>>> print PI * 100
314
B25
Division>>> print 10 / 2
5
>>> print 10 / 3
3
>>> print 10 / 3.0
3.3333333333333335
>>> print 10.0 / 3
3.3333333333333335
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
B25 Modulo(%) >>> print 3 % 21
>>>y = 10%3>>>print y1
B25
>>> caesar = “Et tu, Brute!"
>>> PI = ‘42’
>>> tyrion = “”” I’m a Lannister.
A Lannister always pays his debts.
”””
Strings
Indexing In Strings
Indexing
B25
OMG facts about Strings>>> print "Awesome” + “India”
AwesomeIndia
>>> print ‘pizza’ * 10
pizzapizzapizzapizzapizzapizzapizzapizzapizzapizza
B25
String Methods● capitalize()● count()● index()● isalnum()● istitle()● upper()● find()● strip()● isdigit()● isspace()● lower()● startswidth()● replace()● isupper()● swapcase()● islower()
B25 Control Flowvar = 100if var == 200: print “PLUTO" print var
elif var == 100: print "DONALD" print var
else: print "DAISY" print var
OUTPUT:DONALD100
B25 Comparisons• Equal to (==)
• Not equal to (!=)
• Less than (<)
• Less than or equal to (<=)
• Greater than (>)
• Greater than or equal to (>=)
B25 Booleans★ AND
★ OR
★ NOT
Order of execution:
not and or
B25 Loops
While………
def factorial(n): num = 1 while n >= 1: num = num * n n = n - 1 return num
>>>fact(5)120
B25
count = 10
while count > 0:
count += 1
Beware Of Loops That Never Ends
B25Break Loops Using Breakcount = 0
while True:
print count
count += 1
if count >= 10:
break
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
B25 Loops
For……...for i in range(5,10): print i
56789
B25 Data Structures
Lists….
List = [‘a’,’b’,’c’,’d’]
Numbers = [1,2,3,4]
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()
B25 Data Structures
Dictionary…….
d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
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
B25 Functions
B25Exceptions And Error Handlingtry:
<to do something>
except <an error>:
<do something different>
finally:
<and always do this>
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..."
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 *
B25 Example>>> import math
>>> print math.sqrt(25)
5
>>> from math import *
>>> sqrt(36)
6
B25
THANK YOU