KEMBAR78
Python workshop intro_string (1) | PPT
Popular Python Usage
 Google.com,Google.co.in, Google.de, Google.co.uk, Google.co.jp,
Google.com.hk, Google.com.br, Google.fr, Google.ru
 Google Groups, Gmail, and Google Maps
 Youtube.com
 Yahoo Maps, Groups
 Shopzilla
 Walt Disney Feature Animation
 NASA
 Red Hat
 Nokia
 Reddit
 Quora
 Site of the USA Central Intelligence Agency (CIA) is powered by Python.
Python Success Stories
 YouTube.com
"Python is fast enough for our site and allows us to produce maintainable
features in record times, with a minimum of developers," said Cuong Do,
Software Architect, YouTube.com.
 Google
"Python has been an important part of Google since the beginning, and remains
so as the system grows and evolves. Today dozens of Google engineers use
Python, and we're looking for more people with skills in this language." said
Peter Norvig, director of search quality at Google, Inc.
Python Basics

No
datatype???
Cooolllll !!!!!

>>> x=3
>>> x
3

# Assignment Operator

>>>x=“ccs”
>>>x
‘ccs’
>>> print(“Hello, world")
Hello, world

# Print function to print

>>> # this is a comment

# Comment
Numbers
>>> x = 12**2
144

# Power

>>> d=5/2
>>> d
2.5

# Division
# Real value output

>>> d=5//2
>>> d
2

# truncates fractional part in division

>>> x, y = 2, 3
>>> x
2
>>> y
3

# Multiple assignment

>>> 0<x<=4
True

# Relational Operator
Bitwise Operators
>>> 2<<1

# Left Shift

4
>>> 25>>1

# Right Shift

12
>>>x=2
>>> x|1

# Bit-wise OR

3
>>> ~x

# 1's Complement

-3
>>> y=12
>>> x^y
14

# Bit-wise XOR
String
 Are enclosed in single quotes ‘....’ or double quotes “...”
  is used to escape quotes
 Strings are immutuable
String Operations
>>>"hello"+"world"

# concatenation

"helloworld"
>>>"hello"*3

# repetition

"hellohellohello“
>>>"hello"[0]

# indexing

"h"
>>>"hello"[-1]

# (from end)

"o”
>>>"hello"[1:4]

# slicing

"ell"
>>> len("hello")

# size

5
>>> "hello" < "jello"
True

# comparison
String Operations (contd...)
>>> "e" in "hello"
True
>>> a = 'abcde'
>>> 'c' in a
True
>>> 'cd' in a
True
>>> 'ac' in a
False

# search
Example String Operations
>>> str=”string”
>>> str[0]
's'
>>> str[-1]
'g'
>>> str[0:]
'string'
>>> str[:-1]
'strin'
>>> len(str)
6
>>> str[:6]
'string'
>>> str[:]
'string'
String Immutability
>>> l1 = “Demo String”
>>> l2 = l1

# Both l1, l2 will refer to same reference,
l1

>>> l2 = l1[:]

# Independent copies, two references
String Built-in Functions
 s.capitalize()

# Copy of s with only the first character capitalized

 s.title()

# Copy of s; first character of each word capitalized

 s.center(width)

# Center s in a field of given width

 s.count(sub)

# Count the number of occurrences of sub in s

 s.find(sub)

# Find the first position where sub occurs in s

 s.join(list)

# Concatenate list of strings into one large string
using s as separator

 s.ljust(width)

# Like center, but s is left-justified
String Built-in Functions (contd...)
 s.lower()

# Copy of s in all lowercase letters

 s.lstrip()

# Copy of s with leading whitespace removed

 s.replace(oldsub, newsub)

# Replace occurrences of oldsub in s with
newsub

 s.rfind(sub)

# Like find, but returns the right-most
position

 s.rjust(width)

# Like center, but s is right-justified

 s.rstrip()

# Copy of s with trailing whitespace removed

 s.split()

# Split s into a list of substrings

 s.upper()

# Copy of s; all characters converted to
uppercase
Some Other Built-in Functions
>>> name=input("Enter name please")
Enter name please
Karam
>>> print("Hello", name)
Hello Karam

#input

>>> eval("12+13")
25
>>> eval("123")
123
>>> x = eval(input("Enter a number "))
Enter a number 3.14
>>> print x
3.14

#eval

>>> type (x)
<class, 'float'>

#type
Example
Given the month number, print the name of month. Names of all months are contained
in a string.
>>>months = "JanFebMarAprMayJunJulAugSepOctNovDec"
>>>n = eval(input("Enter a month number (1-12): "))
>>>pos = (n-1) * 3
>>>monthAbbrev = months[pos:pos+3]
>>>print ("The month abbreviation is", monthAbbrev + ".")
Int vs eval
>>> int("05")
5
>>> eval("05")
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
eval("05")
File "<string>", line 1
05
^
SyntaxError: invalid token
A leading 0 used to be used for base 8 (octal) literals in Python.
>>> value = 3.14
>>> str(value)
'3.14'
>>> print("The value is", str(value) + ".")
The value is 3.14.
Type Conversions

Function

Meaning

float(<expr>)

Convert expr to a floating point value

int(<expr>)

Convert expr to an integer value

str(<expr>)

Return a string representation of expr

eval(<string>)

Evaluate string as an expression
Ord, chr Functions
 The ord function returns the numeric (ordinal) code of a
single character.
 The chr function converts a numeric code to the corresponding
character.
>>> ord("A")
65
>>> ord("a")
97
>>> chr(97)
'a'
>>> chr(65)
'A'
Format Function
>>> "Hello {0} {1}, you may have won ${2}" .format("Mr.", "Smith", 10000)
'Hello Mr. Smith, you may have won $10000'
>>> 'This int, {0:5}, was placed in a field of width 5'.format(7)
'This int, 7, was placed in a field of width 5'
>>> 'This int, {0:10}, was placed in a field of witdh 10'.format(10)
'This int,
10, was placed in a field of witdh 10'

>>> 'left justification: {0:<5}'.format("Hi!")
'left justification: Hi! ’
>>> 'right justification: {0:>5}'.format("Hi!")
'right justification: Hi!’
>>> 'centered: {0:^5}'.format("Hi!")
'centered: Hi! '
Exercise
1. Input the date in mm/dd/yyyy format (dateStr)
(Hint): Split dateStr into month, day, and year strings. Convert the month
string into a month number.Use the month number to lookup the month
name. Create a new date string in the form “Month Day, Year”. Output the
new date string

2. A program to convert a sequence of Unicode numbers into a string of text.
Shallow Copy
 Assignment manipulates references
x = y

#does not make a copy of y

x = y

#x and y refer to the same object

 Very useful; but beware!
 Example:
>>> a = 1
>>> b = a
>>> a=a+1
>>>a
2
>>> print b
1
Control Structures
if condition:
statements

while condition:
statements

[elif condition:
statements] ...
else:

for var in sequence:
statements

statements
break
continue
Example Function
def gcd(a, b):
"greatest common divisor"
while a != 0:
a, b = b%a, a

# parallel assignment

return b
>>> gcd.__doc__
'greatest common divisor'
>>> gcd(12, 20)
4

Python workshop intro_string (1)

  • 2.
    Popular Python Usage Google.com,Google.co.in, Google.de, Google.co.uk, Google.co.jp, Google.com.hk, Google.com.br, Google.fr, Google.ru  Google Groups, Gmail, and Google Maps  Youtube.com  Yahoo Maps, Groups  Shopzilla  Walt Disney Feature Animation  NASA  Red Hat  Nokia  Reddit  Quora  Site of the USA Central Intelligence Agency (CIA) is powered by Python.
  • 3.
    Python Success Stories YouTube.com "Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers," said Cuong Do, Software Architect, YouTube.com.  Google "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. Today dozens of Google engineers use Python, and we're looking for more people with skills in this language." said Peter Norvig, director of search quality at Google, Inc.
  • 5.
    Python Basics No datatype??? Cooolllll !!!!! >>>x=3 >>> x 3 # Assignment Operator >>>x=“ccs” >>>x ‘ccs’ >>> print(“Hello, world") Hello, world # Print function to print >>> # this is a comment # Comment
  • 6.
    Numbers >>> x =12**2 144 # Power >>> d=5/2 >>> d 2.5 # Division # Real value output >>> d=5//2 >>> d 2 # truncates fractional part in division >>> x, y = 2, 3 >>> x 2 >>> y 3 # Multiple assignment >>> 0<x<=4 True # Relational Operator
  • 7.
    Bitwise Operators >>> 2<<1 #Left Shift 4 >>> 25>>1 # Right Shift 12 >>>x=2 >>> x|1 # Bit-wise OR 3 >>> ~x # 1's Complement -3 >>> y=12 >>> x^y 14 # Bit-wise XOR
  • 8.
    String  Are enclosedin single quotes ‘....’ or double quotes “...”  is used to escape quotes  Strings are immutuable
  • 9.
    String Operations >>>"hello"+"world" # concatenation "helloworld" >>>"hello"*3 #repetition "hellohellohello“ >>>"hello"[0] # indexing "h" >>>"hello"[-1] # (from end) "o” >>>"hello"[1:4] # slicing "ell" >>> len("hello") # size 5 >>> "hello" < "jello" True # comparison
  • 10.
    String Operations (contd...) >>>"e" in "hello" True >>> a = 'abcde' >>> 'c' in a True >>> 'cd' in a True >>> 'ac' in a False # search
  • 11.
    Example String Operations >>>str=”string” >>> str[0] 's' >>> str[-1] 'g' >>> str[0:] 'string' >>> str[:-1] 'strin' >>> len(str) 6 >>> str[:6] 'string' >>> str[:] 'string'
  • 12.
    String Immutability >>> l1= “Demo String” >>> l2 = l1 # Both l1, l2 will refer to same reference, l1 >>> l2 = l1[:] # Independent copies, two references
  • 13.
    String Built-in Functions s.capitalize() # Copy of s with only the first character capitalized  s.title() # Copy of s; first character of each word capitalized  s.center(width) # Center s in a field of given width  s.count(sub) # Count the number of occurrences of sub in s  s.find(sub) # Find the first position where sub occurs in s  s.join(list) # Concatenate list of strings into one large string using s as separator  s.ljust(width) # Like center, but s is left-justified
  • 14.
    String Built-in Functions(contd...)  s.lower() # Copy of s in all lowercase letters  s.lstrip() # Copy of s with leading whitespace removed  s.replace(oldsub, newsub) # Replace occurrences of oldsub in s with newsub  s.rfind(sub) # Like find, but returns the right-most position  s.rjust(width) # Like center, but s is right-justified  s.rstrip() # Copy of s with trailing whitespace removed  s.split() # Split s into a list of substrings  s.upper() # Copy of s; all characters converted to uppercase
  • 15.
    Some Other Built-inFunctions >>> name=input("Enter name please") Enter name please Karam >>> print("Hello", name) Hello Karam #input >>> eval("12+13") 25 >>> eval("123") 123 >>> x = eval(input("Enter a number ")) Enter a number 3.14 >>> print x 3.14 #eval >>> type (x) <class, 'float'> #type
  • 16.
    Example Given the monthnumber, print the name of month. Names of all months are contained in a string. >>>months = "JanFebMarAprMayJunJulAugSepOctNovDec" >>>n = eval(input("Enter a month number (1-12): ")) >>>pos = (n-1) * 3 >>>monthAbbrev = months[pos:pos+3] >>>print ("The month abbreviation is", monthAbbrev + ".")
  • 17.
    Int vs eval >>>int("05") 5 >>> eval("05") Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> eval("05") File "<string>", line 1 05 ^ SyntaxError: invalid token A leading 0 used to be used for base 8 (octal) literals in Python. >>> value = 3.14 >>> str(value) '3.14' >>> print("The value is", str(value) + ".") The value is 3.14.
  • 18.
    Type Conversions Function Meaning float(<expr>) Convert exprto a floating point value int(<expr>) Convert expr to an integer value str(<expr>) Return a string representation of expr eval(<string>) Evaluate string as an expression
  • 19.
    Ord, chr Functions The ord function returns the numeric (ordinal) code of a single character.  The chr function converts a numeric code to the corresponding character. >>> ord("A") 65 >>> ord("a") 97 >>> chr(97) 'a' >>> chr(65) 'A'
  • 20.
    Format Function >>> "Hello{0} {1}, you may have won ${2}" .format("Mr.", "Smith", 10000) 'Hello Mr. Smith, you may have won $10000' >>> 'This int, {0:5}, was placed in a field of width 5'.format(7) 'This int, 7, was placed in a field of width 5' >>> 'This int, {0:10}, was placed in a field of witdh 10'.format(10) 'This int, 10, was placed in a field of witdh 10' >>> 'left justification: {0:<5}'.format("Hi!") 'left justification: Hi! ’ >>> 'right justification: {0:>5}'.format("Hi!") 'right justification: Hi!’ >>> 'centered: {0:^5}'.format("Hi!") 'centered: Hi! '
  • 21.
    Exercise 1. Input thedate in mm/dd/yyyy format (dateStr) (Hint): Split dateStr into month, day, and year strings. Convert the month string into a month number.Use the month number to lookup the month name. Create a new date string in the form “Month Day, Year”. Output the new date string 2. A program to convert a sequence of Unicode numbers into a string of text.
  • 22.
    Shallow Copy  Assignmentmanipulates references x = y #does not make a copy of y x = y #x and y refer to the same object  Very useful; but beware!  Example: >>> a = 1 >>> b = a >>> a=a+1 >>>a 2 >>> print b 1
  • 24.
    Control Structures if condition: statements whilecondition: statements [elif condition: statements] ... else: for var in sequence: statements statements break continue
  • 25.
    Example Function def gcd(a,b): "greatest common divisor" while a != 0: a, b = b%a, a # parallel assignment return b >>> gcd.__doc__ 'greatest common divisor' >>> gcd(12, 20) 4

Editor's Notes