SlideShare a Scribd company logo
Python workshop intro_string (1)
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 workshop intro_string (1)
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
Python workshop intro_string (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

More Related Content

PDF
Codigos
PDF
The Ring programming language version 1.5.1 book - Part 21 of 180
PDF
Numbers obfuscation in Python
PDF
Debugging: A Senior's Skill
PDF
Data Visualization — Le funzionalità matematiche di Sage per la visualizzazio...
PPTX
2017 02-07 - elastic & spark. building a search geo locator
PDF
Music as data
Codigos
The Ring programming language version 1.5.1 book - Part 21 of 180
Numbers obfuscation in Python
Debugging: A Senior's Skill
Data Visualization — Le funzionalità matematiche di Sage per la visualizzazio...
2017 02-07 - elastic & spark. building a search geo locator
Music as data

What's hot (20)

PDF
FNT 2015 PDIS CodeEU - Zanimljiva informatika - 02 Djordje Pavlovic - Live_ch...
PDF
Taming Asynchronous Transforms with Interstellar
PDF
Text Mining using Regular Expressions
PPTX
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
PDF
PyLecture2 -NetworkX-
PDF
Class 7a: Functions
PDF
10 template code program
PDF
F# delight
PDF
Neotool (using py2neo from the command line)
PDF
Functional Pattern Matching on Python
PDF
Some Pry Features
PDF
The Ring programming language version 1.5.2 book - Part 45 of 181
PDF
Python utan-stodhjul-motorsag
PDF
AJUG April 2011 Raw hadoop example
PPT
Number
PDF
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
PDF
Queue in swift
PDF
Python Numpy Source Codes
PDF
Beyond javascript using the features of tomorrow
FNT 2015 PDIS CodeEU - Zanimljiva informatika - 02 Djordje Pavlovic - Live_ch...
Taming Asynchronous Transforms with Interstellar
Text Mining using Regular Expressions
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
PyLecture2 -NetworkX-
Class 7a: Functions
10 template code program
F# delight
Neotool (using py2neo from the command line)
Functional Pattern Matching on Python
Some Pry Features
The Ring programming language version 1.5.2 book - Part 45 of 181
Python utan-stodhjul-motorsag
AJUG April 2011 Raw hadoop example
Number
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
Queue in swift
Python Numpy Source Codes
Beyond javascript using the features of tomorrow
Ad

Similar to Python workshop intro_string (1) (20)

PPT
Python study material
PDF
COMPUTER SCIENCE SUPPORT MATERIAL CLASS 12.pdf
PDF
Python intro
PPTX
Python Workshop - Learn Python the Hard Way
PPT
Python course in_mumbai
PPT
Python course in_mumbai
PPT
From Operators to Arrays – Power Up Your Python Skills for Real-World Coding!
PPT
Python programming unit 2 -Slides-3.ppt
PDF
Intro to Python
PDF
Sessisgytcfgggggggggggggggggggggggggggggggg
PDF
Python bootcamp - C4Dlab, University of Nairobi
PDF
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
PPTX
Python Workshop
PPTX
Python PPT2
PPT
Python
PPTX
Learning python
PPTX
Learning python
PPTX
Learning python
Python study material
COMPUTER SCIENCE SUPPORT MATERIAL CLASS 12.pdf
Python intro
Python Workshop - Learn Python the Hard Way
Python course in_mumbai
Python course in_mumbai
From Operators to Arrays – Power Up Your Python Skills for Real-World Coding!
Python programming unit 2 -Slides-3.ppt
Intro to Python
Sessisgytcfgggggggggggggggggggggggggggggggg
Python bootcamp - C4Dlab, University of Nairobi
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
Python Workshop
Python PPT2
Python
Learning python
Learning python
Learning python
Ad

Recently uploaded (20)

PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
RMMM.pdf make it easy to upload and study
PPTX
Cell Types and Its function , kingdom of life
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Lesson notes of climatology university.
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Institutional Correction lecture only . . .
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Presentation on HIE in infants and its manifestations
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Final Presentation General Medicine 03-08-2024.pptx
VCE English Exam - Section C Student Revision Booklet
RMMM.pdf make it easy to upload and study
Cell Types and Its function , kingdom of life
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Anesthesia in Laparoscopic Surgery in India
Lesson notes of climatology university.
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Institutional Correction lecture only . . .
Microbial disease of the cardiovascular and lymphatic systems
Module 4: Burden of Disease Tutorial Slides S2 2025
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
A systematic review of self-coping strategies used by university students to ...
O7-L3 Supply Chain Operations - ICLT Program
GDM (1) (1).pptx small presentation for students
202450812 BayCHI UCSC-SV 20250812 v17.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Presentation on HIE in infants and its manifestations
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student

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 enclosed in 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-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
  • 16. 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 + ".")
  • 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 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
  • 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 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.
  • 22. 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
  • 24. Control Structures if condition: statements while condition: 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