L Python PDF
L Python PDF
with Python
1
Brief History of Python
Invented in the Netherlands, early 90s
by Guido van Rossum
Named after Monty Python
Open sourced from the beginning
Considered a scripting language, but is
much more
Scalable, object oriented and functional
from the beginning
Used by Google from the beginning
Increasingly popular
The Python tutorial is good!
The Basics
Hello World
Syntax:
print "Message"
print Expression
Prints the given text message or expression value on the console, and
moves the cursor down to the next line.
print Item1, Item2, ..., ItemN
Prints several messages and/or expressions on the same line.
Examples:
print "Hello, world!"
age = 45
print "You have", 65 - age, "years until retirement"
Output:
Hello, world!
You have 20 years until retirement
8
Documentation
• Python provides no braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation,
which is rigidly enforced.
• The number of spaces in the indentation is variable, but all statements within
the block must be indented the same amount. For example −
if True:
print "True"
else:
print "False“
However, the following block generates an error −
• if True: print "Answer" print "True" else: print "Answer" print "False"
Naming Rules
• Names are case sensitive and cannot start with a
number. They can contain letters, numbers, and
underscores.
bob Bob _bob _2_bob_ bob_2 BoB
• There are some reserved words:
and, assert, break, class, continue,
def, del, elif, else, except, exec,
finally, for, from, global, if,
import, in, is, lambda, not, or,
pass, print, raise, return, try,
while
Naming conventions
The Python community has these recommend-ed
naming conventions
•joined_lower for functions, methods and, attributes
•joined_lower or ALL_CAPS for constants
•StudlyCaps for classes
•camelCase only to conform to pre-existing
conventions
•Attributes: interface, _internal, __private
Variables
• Are not declared, just assigned
• The variable is created the first time you assign it
a value
• Are references to objects
• Type information is with the object, not the
reference
• Everything in Python is an object
Variables
Syntax:
>>> x = 'hello'
>>> x = x + ' there'
>>> x
'hello there'
Strings
string: A sequence of text characters in a program.
Strings start and end with quotation mark " or apostrophe ' characters.
Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
25
Indexes
Characters in a string are numbered with indexes starting at 0:
Example:
name = "P. Diddy"
index 0 1 2 3 4 5 6 7
character P . D i d d y >>> s = '012345'
>>> s[3]
'3'
Accessing an individual character of a string: >>> s[1:4]
variableName [ index ]
'123'
Example: >>> s[2:]
print name, "starts with", name[0] '2345'
Output: >>> s[:4]
P. Diddy starts with P '0123'
>>> s[-2]
'4'
26
String properties
len(string) - number of characters in a string
(including spaces)
str.lower(string) - lowercase version of a string
str.upper(string) - uppercase version of a string
Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print big_name, "has", length, "characters"
Output:
MARTIN DOUGLAS STEPP has 20 characters
27
List
• Compound data types.
• A list contains items separated bycommas
and enclosed within square brackets []..
• items belonging to a list can be of different
data type.
List Example
• list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
• tinylist = [123, 'john']
• print list # Prints complete list
• ['abcd', 786, 2.23, 'john', 70.200000000000003]
• print list[0] # Prints first element of the list
• abcd
• print list[1:3] # Prints elements starting from 2nd till 3rd
• [786, 2.23]
• print list[2:] # Prints elements starting from 3rd element
• [2.23, 'john', 70.200000000000003]
• print tinylist * 2 # Prints list two times print
• [123, 'john', 123, 'john']
• print list + tinylist # Prints concatenated lists
• ['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
Tuples
• Another sequence data type that is similar to
the list.
• A tuple consists of a number of values
separated by commas.
• 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 read-only lists.
List vs Tuple
• tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
• list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
• print tinydict
– # Prints com plete dictionary
• print tinydict.keys()
– # Prints all the keys
• print tinydict.values()
– # Prints all the values
Dictionary Example
>>> s={'a' : 1 , 'b' :2}
>>> s.keys()
dict_keys(['b', 'a'])
>>> s.values()
dict_values([2, 1])
>>> s['a']
1
Data Type Summary
40
Control Flow: if
if statement: Executes a group of statements only if a certain
condition is true. Otherwise, the statements are skipped.
Syntax:
if condition:
statements
Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is accepted."
41
if/else
if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
Syntax:
if condition:
statements
else:
statements
Example:
gpa = 1.4
if gpa > 2.0:
print "Welcome to Mars University!"
else:
print "Your application is denied."
In file ifstatement.py
Range Test
Or
if(Time>=3 and Time<=5)
A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 3.45 or y == “Hello”:
x=x+1
y = y + “ World” # String concat.
print x
print y
while
while loop: Executes a group of statements as long as a condition is True.
good for indefinite loops (repeat an unknown number of times)
Syntax:
while condition:
statements
Example:
number = 1
while number < 200:
print number,
number = number * 2
Output:
1 2 4 8 16 32 64 128
46
While Loops
>>> import whileloop
x=1 1
while x < 10 : 2
print x 3
x=x+1 4
5
6
In whileloop.py
7
8
9
>>>
In interpreter
The Loop Else Clause
• The optional else clause runs only if the loop exits
normally (not by break)
x=1
~: python whileelse.py
while x < 3 : 1
print x 2
x=x+1 hello
else: Run from the command line
print 'hello'
In whileelse.py
The Loop Else Clause
x=1
while x < 5 :
print x
x=x+1 ~: python whileelse2.py
break 1
else :
print 'i got here'
whileelse2.py
For Loop
for letter in 'Python': # First Example
print 'Current Letter :', letter
while i<=n :
fact=fact*i
i=i+1
else:
print("Factorial of ", n, " is ", fact)