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
Ad

Recommended

Codigos
Codigos
Brian Joseff
 
The Ring programming language version 1.5.1 book - Part 21 of 180
The Ring programming language version 1.5.1 book - Part 21 of 180
Mahmoud Samir Fayed
 
Numbers obfuscation in Python
Numbers obfuscation in Python
delimitry
 
Debugging: A Senior's Skill
Debugging: A Senior's Skill
Milton Lenis
 
Data Visualization — Le funzionalità matematiche di Sage per la visualizzazio...
Data Visualization — Le funzionalità matematiche di Sage per la visualizzazio...
Andrea Lazzarotto
 
2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator
Alberto Paro
 
Music as data
Music as data
John Vlachoyiannis
 
Strings
Strings
Marieswaran Ramasamy
 
FNT 2015 PDIS CodeEU - Zanimljiva informatika - 02 Djordje Pavlovic - Live_ch...
FNT 2015 PDIS CodeEU - Zanimljiva informatika - 02 Djordje Pavlovic - Live_ch...
Педагошко друштво информатичара Србије
 
Taming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with Interstellar
Jens Ravens
 
Lists
Lists
Marieswaran Ramasamy
 
Text Mining using Regular Expressions
Text Mining using Regular Expressions
Rupak Roy
 
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
Alberto Paro
 
PyLecture2 -NetworkX-
PyLecture2 -NetworkX-
Yoshiki Satotani
 
Class 7a: Functions
Class 7a: Functions
Marc Gouw
 
10 template code program
10 template code program
Bint EL-maghrabi
 
F# delight
F# delight
priort
 
Neotool (using py2neo from the command line)
Neotool (using py2neo from the command line)
Nigel Small
 
Functional Pattern Matching on Python
Functional Pattern Matching on Python
Daker Fernandes
 
Some Pry Features
Some Pry Features
Yann VERY
 
The Ring programming language version 1.5.2 book - Part 45 of 181
The Ring programming language version 1.5.2 book - Part 45 of 181
Mahmoud Samir Fayed
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
niklal
 
AJUG April 2011 Raw hadoop example
AJUG April 2011 Raw hadoop example
Christopher Curtin
 
Number
Number
mussawir20
 
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
Shift Conference
 
Queue in swift
Queue in swift
joonjhokil
 
Python Numpy Source Codes
Python Numpy Source Codes
Amarjeetsingh Thakur
 
Beyond javascript using the features of tomorrow
Beyond javascript using the features of tomorrow
Alexander Varwijk
 
Python course
Python course
Евгений Сазонов
 
Python study material
Python study material
Satish Nagabhushan
 

More Related Content

What's hot (20)

FNT 2015 PDIS CodeEU - Zanimljiva informatika - 02 Djordje Pavlovic - Live_ch...
FNT 2015 PDIS CodeEU - Zanimljiva informatika - 02 Djordje Pavlovic - Live_ch...
Педагошко друштво информатичара Србије
 
Taming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with Interstellar
Jens Ravens
 
Lists
Lists
Marieswaran Ramasamy
 
Text Mining using Regular Expressions
Text Mining using Regular Expressions
Rupak Roy
 
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
Alberto Paro
 
PyLecture2 -NetworkX-
PyLecture2 -NetworkX-
Yoshiki Satotani
 
Class 7a: Functions
Class 7a: Functions
Marc Gouw
 
10 template code program
10 template code program
Bint EL-maghrabi
 
F# delight
F# delight
priort
 
Neotool (using py2neo from the command line)
Neotool (using py2neo from the command line)
Nigel Small
 
Functional Pattern Matching on Python
Functional Pattern Matching on Python
Daker Fernandes
 
Some Pry Features
Some Pry Features
Yann VERY
 
The Ring programming language version 1.5.2 book - Part 45 of 181
The Ring programming language version 1.5.2 book - Part 45 of 181
Mahmoud Samir Fayed
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
niklal
 
AJUG April 2011 Raw hadoop example
AJUG April 2011 Raw hadoop example
Christopher Curtin
 
Number
Number
mussawir20
 
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
Shift Conference
 
Queue in swift
Queue in swift
joonjhokil
 
Python Numpy Source Codes
Python Numpy Source Codes
Amarjeetsingh Thakur
 
Beyond javascript using the features of tomorrow
Beyond javascript using the features of tomorrow
Alexander Varwijk
 
Taming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with Interstellar
Jens Ravens
 
Text Mining using Regular Expressions
Text Mining using Regular Expressions
Rupak Roy
 
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
Alberto Paro
 
Class 7a: Functions
Class 7a: Functions
Marc Gouw
 
F# delight
F# delight
priort
 
Neotool (using py2neo from the command line)
Neotool (using py2neo from the command line)
Nigel Small
 
Functional Pattern Matching on Python
Functional Pattern Matching on Python
Daker Fernandes
 
Some Pry Features
Some Pry Features
Yann VERY
 
The Ring programming language version 1.5.2 book - Part 45 of 181
The Ring programming language version 1.5.2 book - Part 45 of 181
Mahmoud Samir Fayed
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
niklal
 
AJUG April 2011 Raw hadoop example
AJUG April 2011 Raw hadoop example
Christopher Curtin
 
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
Shift Conference
 
Queue in swift
Queue in swift
joonjhokil
 
Beyond javascript using the features of tomorrow
Beyond javascript using the features of tomorrow
Alexander Varwijk
 

Similar to Python workshop intro_string (1) (20)

Python course
Python course
Евгений Сазонов
 
Python study material
Python study material
Satish Nagabhushan
 
COMPUTER SCIENCE SUPPORT MATERIAL CLASS 12.pdf
COMPUTER SCIENCE SUPPORT MATERIAL CLASS 12.pdf
rajkumar2792005
 
Python intro
Python intro
Abhinav Upadhyay
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Python course in_mumbai
Python course in_mumbai
vibrantuser
 
Python course in_mumbai
Python course in_mumbai
vibrantuser
 
Python programming unit 2 -Slides-3.ppt
Python programming unit 2 -Slides-3.ppt
geethar79
 
Intro to Python
Intro to Python
Daniel Greenfeld
 
Sessisgytcfgggggggggggggggggggggggggggggggg
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobi
krmboya
 
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
rohithzach
 
Python Workshop
Python Workshop
Assem CHELLI
 
Python PPT2
Python PPT2
Selvakanmani S
 
Python
Python
Kumar Gaurav
 
Intro
Intro
Daniel Greenfeld
 
Learning python
Learning python
Hoang Nguyen
 
Learning python
Learning python
Harry Potter
 
Learning python
Learning python
Tony Nguyen
 
Learning python
Learning python
Luis Goldster
 
COMPUTER SCIENCE SUPPORT MATERIAL CLASS 12.pdf
COMPUTER SCIENCE SUPPORT MATERIAL CLASS 12.pdf
rajkumar2792005
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Python course in_mumbai
Python course in_mumbai
vibrantuser
 
Python course in_mumbai
Python course in_mumbai
vibrantuser
 
Python programming unit 2 -Slides-3.ppt
Python programming unit 2 -Slides-3.ppt
geethar79
 
Sessisgytcfgggggggggggggggggggggggggggggggg
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobi
krmboya
 
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
rohithzach
 
Ad

Recently uploaded (20)

Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
RAKESH SAJJAN
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
Communicable Diseases and National Health Programs – Unit 9 | B.Sc Nursing 5t...
Communicable Diseases and National Health Programs – Unit 9 | B.Sc Nursing 5t...
RAKESH SAJJAN
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
“THE BEST CLASS IN SCHOOL”. _
“THE BEST CLASS IN SCHOOL”. _
Colégio Santa Teresinha
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
jutaydeonne
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
RAKESH SAJJAN
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
Communicable Diseases and National Health Programs – Unit 9 | B.Sc Nursing 5t...
Communicable Diseases and National Health Programs – Unit 9 | B.Sc Nursing 5t...
RAKESH SAJJAN
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
jutaydeonne
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
Ad

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