SlideShare a Scribd company logo
Unit 4
Condition Statements If/else
Use of return, user input and strings
By Alex Cheung
2
Math commands
from math import *
Function name Description
abs(value) absolute value
ceil(value) rounds up
cos(value) cosine, in radians
degrees(value) convert radians to degrees
floor(value) rounds down
log(value, base) logarithm in any base
log10(value) logarithm, base 10
max(value1, value2, ...) larger of two (or more) values
min(value1, value2, ...) smaller of two (or more) values
radians(value) convert degrees to radians
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
tan(value) tangent
Constant Description
e 2.7182818...
pi 3.1415926...
3
Returning values
def name(parameters):
statements
...
return expression
– Python doesn't require you to declare that your function
returns a value; you just return something at its end.
>>> def ftoc(temp):
... tempc = 5.0 / 9.0 * (temp - 32)
... return tempc
>>> ftoc(98.6)
37.0
4
input : Reads a string from the user's keyboard.
– reads and returns an entire line of input *
* NOTE: Older v2.x versions of Python handled user input differently.
These slides are about the modern v3.x of Python and above.
input
>>> name = input("Howdy. What's yer name?")
Howdy. What's yer name? Paris Hilton
>>> name
'Paris Hilton'
5
• to read numbers, cast input result to an int or float
– If the user does not type a number, an error occurs.
– Example:
age = int(input("How old are you? "))
print("Your age is", age)
print(65 - age, "years to retirement")
Output:
How old are you? 53
Your age is 53
12 years to retirement
input
6
if
if condition:
statements
– Example:
gpa = float(input("What is your GPA? "))
if gpa > 2.0:
print("Your application is accepted.")
7
if/else
if condition:
statements
elif condition:
statements
else:
statements
– Example:
gpa = float(input("What is your GPA? "))
if gpa > 3.5:
print("You have qualified for the honor roll.")
elif gpa > 2.0:
print("Welcome to Mars University!")
else:
print("Your application is denied.")
8
if ... in
if value in sequence:
statements
– The sequence can be a range, string, tuple, or list (seen later)
– Examples:
x = 3
if x in range(0, 10):
print("x is between 0 and 9")
letter = input("What is your favorite letter? ")
if letter in "aeiou":
print("It is a vowel!")
9
Logical Operators
Operator Example Result
and (2 == 3) and (-1 < 5) False
or (2 == 3) or (-1 < 5) True
not not (2 == 3) True
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
10
Exercise
• Write a program that reads two employees' hours and
displays each employee's total and the overall total.
– Cap each day at 8 hours.
Employee 1: How many days? 3
Hours? 6
Hours? 12
Hours? 5
Employee 1's total hours = 19 (6.33 / day)
Employee 2: How many days? 2
Hours? 11
Hours? 6
Employee 2's total hours = 14 (7.00 / day)
Total hours for both = 33
11
Strings
• Accessing character(s):
variable [ index ]
variable [ index1:index2 ]
– index2 exclusive
– index1 or index2 can be
omitted (goes to end of string)
index 0 1 2 3 4 5 6 7
or -8 -7 -6 -5 -4 -3 -2 -1
character P . D i d d y
>>> name = "P. Diddy"
>>> name[0]
'P'
>>> name[7]
'y'
>>> name[-1]
'y'
>>> name[3:6]
'Did'
>>> name[3:]
'Diddy'
>>> name[:-2]
'P. Did'
12
String Methods
>>> name = "Martin Douglas Stepp"
>>> name.upper()
'MARTIN DOUGLAS STEPP'
>>> name.lower().startswith("martin")
True
>>> len(name)
20
Java Python
length len(str)
startsWith, endsWith startswith, endswith
toLowerCase, toUpperCase upper, lower,
isupper, islower,
capitalize, swapcase
indexOf find
trim strip
13
for Loops and Strings
• A for loop can examine each character in a string in order.
for name in string:
statements
>>> for c in "booyah":
... print c
...
b
o
o
y
a
h
14
Formatting Text
"format string" % (parameter, parameter, ...)
• Placeholders insert formatted values into a string:
– %d an integer
– %f a real number
– %s a string
– %8d an integer, 8 characters wide, right-aligned
– %08d an integer, 8 characters wide, padding with 0s
– %-8d an integer, 8 characters wide, left-aligned
– %12f a real number, 12 characters wide
– %.4f a real number, 4 characters after decimal
– %6.2f a real number, 6 total characters wide, 2 after decimal
>>> x = 3; y = 3.14159; z = "hello"
>>> print "%-8s, %04d is close to %.3f" % (z, x, y)
hello , 0003 is close to 3.142
15
Strings and Integers
• ord(text) - Converts a string into a number.
– ord("a") is 97
– ord("b") is 98
– Uses standard mappings such as ASCII and Unicode.
• chr(number) - Converts a number into a string.
– chr(97) is "a"
– chr(99) is "c"
16
Basic cryptography
• Rotation cipher - shift each letter by some fixed amount
– Caesar cipher - shift each letter forward by 3
"the cake is a lie" becomes
"wkh fdnh lv d olh"
• Substitution cipher - transform each letter into another
– not a linear shift; uses some kind of letter mapping
– similar to "cryptogram" or "cryptoquip" games in newspaper
17
Exercise
• Write a program that "encrypts" a secret message with a
Caesar cipher, shifting the letters of the message by 3:
– e.g. "Attack" when rotated by 1 becomes "cwwcfn"
– If you have time, make the program able to undo the cipher.
– Can you write a function that works for a substitution cipher?

More Related Content

Similar to Python 04-ifelse-return-input-strings.pptx

Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa Thapa
 
CBSE XII COMPUTER SCIENCE STUDY MATERIAL BY KVS
CBSE XII COMPUTER SCIENCE STUDY MATERIAL BY KVSCBSE XII COMPUTER SCIENCE STUDY MATERIAL BY KVS
CBSE XII COMPUTER SCIENCE STUDY MATERIAL BY KVS
Gautham Rajesh
 
Intro to tsql unit 10
Intro to tsql   unit 10Intro to tsql   unit 10
Intro to tsql unit 10
Syed Asrarali
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
introduction to c programming and C History.pptx
introduction to c programming and C History.pptxintroduction to c programming and C History.pptx
introduction to c programming and C History.pptx
ManojKhadilkar1
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
PhanMinhLinhAnxM0190
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
RohitSindhu10
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
AkashdeepBhattacharj1
 
Python.pptx
Python.pptxPython.pptx
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
Arturo Herrero
 
Ch2
Ch2Ch2
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
AnishaJ7
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
Golden Julie Jesus
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questions
YashJain47002
 
Csci101 lect08a matlab_programs
Csci101 lect08a matlab_programsCsci101 lect08a matlab_programs
Csci101 lect08a matlab_programs
Elsayed Hemayed
 
Ejercicios de estilo en la programación
Ejercicios de estilo en la programaciónEjercicios de estilo en la programación
Ejercicios de estilo en la programación
Software Guru
 
Python programming unit 2 -Slides-3.ppt
Python programming  unit 2 -Slides-3.pptPython programming  unit 2 -Slides-3.ppt
Python programming unit 2 -Slides-3.ppt
geethar79
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
Srikanth
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
ManjeeraBhargavi Varanasi
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
Koen Handekyn
 

Similar to Python 04-ifelse-return-input-strings.pptx (20)

Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
 
CBSE XII COMPUTER SCIENCE STUDY MATERIAL BY KVS
CBSE XII COMPUTER SCIENCE STUDY MATERIAL BY KVSCBSE XII COMPUTER SCIENCE STUDY MATERIAL BY KVS
CBSE XII COMPUTER SCIENCE STUDY MATERIAL BY KVS
 
Intro to tsql unit 10
Intro to tsql   unit 10Intro to tsql   unit 10
Intro to tsql unit 10
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
introduction to c programming and C History.pptx
introduction to c programming and C History.pptxintroduction to c programming and C History.pptx
introduction to c programming and C History.pptx
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Ch2
Ch2Ch2
Ch2
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questions
 
Csci101 lect08a matlab_programs
Csci101 lect08a matlab_programsCsci101 lect08a matlab_programs
Csci101 lect08a matlab_programs
 
Ejercicios de estilo en la programación
Ejercicios de estilo en la programaciónEjercicios de estilo en la programación
Ejercicios de estilo en la programación
 
Python programming unit 2 -Slides-3.ppt
Python programming  unit 2 -Slides-3.pptPython programming  unit 2 -Slides-3.ppt
Python programming unit 2 -Slides-3.ppt
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
 

Recently uploaded

Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
Pravash Chandra Das
 
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStrDeep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
saastr
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfNunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
flufftailshop
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!
GDSC PJATK
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 

Recently uploaded (20)

Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
 
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStrDeep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfNunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 

Python 04-ifelse-return-input-strings.pptx

  • 1. Unit 4 Condition Statements If/else Use of return, user input and strings By Alex Cheung
  • 2. 2 Math commands from math import * Function name Description abs(value) absolute value ceil(value) rounds up cos(value) cosine, in radians degrees(value) convert radians to degrees floor(value) rounds down log(value, base) logarithm in any base log10(value) logarithm, base 10 max(value1, value2, ...) larger of two (or more) values min(value1, value2, ...) smaller of two (or more) values radians(value) convert degrees to radians round(value) nearest whole number sin(value) sine, in radians sqrt(value) square root tan(value) tangent Constant Description e 2.7182818... pi 3.1415926...
  • 3. 3 Returning values def name(parameters): statements ... return expression – Python doesn't require you to declare that your function returns a value; you just return something at its end. >>> def ftoc(temp): ... tempc = 5.0 / 9.0 * (temp - 32) ... return tempc >>> ftoc(98.6) 37.0
  • 4. 4 input : Reads a string from the user's keyboard. – reads and returns an entire line of input * * NOTE: Older v2.x versions of Python handled user input differently. These slides are about the modern v3.x of Python and above. input >>> name = input("Howdy. What's yer name?") Howdy. What's yer name? Paris Hilton >>> name 'Paris Hilton'
  • 5. 5 • to read numbers, cast input result to an int or float – If the user does not type a number, an error occurs. – Example: age = int(input("How old are you? ")) print("Your age is", age) print(65 - age, "years to retirement") Output: How old are you? 53 Your age is 53 12 years to retirement input
  • 6. 6 if if condition: statements – Example: gpa = float(input("What is your GPA? ")) if gpa > 2.0: print("Your application is accepted.")
  • 7. 7 if/else if condition: statements elif condition: statements else: statements – Example: gpa = float(input("What is your GPA? ")) if gpa > 3.5: print("You have qualified for the honor roll.") elif gpa > 2.0: print("Welcome to Mars University!") else: print("Your application is denied.")
  • 8. 8 if ... in if value in sequence: statements – The sequence can be a range, string, tuple, or list (seen later) – Examples: x = 3 if x in range(0, 10): print("x is between 0 and 9") letter = input("What is your favorite letter? ") if letter in "aeiou": print("It is a vowel!")
  • 9. 9 Logical Operators Operator Example Result and (2 == 3) and (-1 < 5) False or (2 == 3) or (-1 < 5) True not not (2 == 3) True Operator Meaning Example Result == equals 1 + 1 == 2 True != does not equal 3.2 != 2.5 True < less than 10 < 5 False > greater than 10 > 5 True <= less than or equal to 126 <= 100 False >= greater than or equal to 5.0 >= 5.0 True
  • 10. 10 Exercise • Write a program that reads two employees' hours and displays each employee's total and the overall total. – Cap each day at 8 hours. Employee 1: How many days? 3 Hours? 6 Hours? 12 Hours? 5 Employee 1's total hours = 19 (6.33 / day) Employee 2: How many days? 2 Hours? 11 Hours? 6 Employee 2's total hours = 14 (7.00 / day) Total hours for both = 33
  • 11. 11 Strings • Accessing character(s): variable [ index ] variable [ index1:index2 ] – index2 exclusive – index1 or index2 can be omitted (goes to end of string) index 0 1 2 3 4 5 6 7 or -8 -7 -6 -5 -4 -3 -2 -1 character P . D i d d y >>> name = "P. Diddy" >>> name[0] 'P' >>> name[7] 'y' >>> name[-1] 'y' >>> name[3:6] 'Did' >>> name[3:] 'Diddy' >>> name[:-2] 'P. Did'
  • 12. 12 String Methods >>> name = "Martin Douglas Stepp" >>> name.upper() 'MARTIN DOUGLAS STEPP' >>> name.lower().startswith("martin") True >>> len(name) 20 Java Python length len(str) startsWith, endsWith startswith, endswith toLowerCase, toUpperCase upper, lower, isupper, islower, capitalize, swapcase indexOf find trim strip
  • 13. 13 for Loops and Strings • A for loop can examine each character in a string in order. for name in string: statements >>> for c in "booyah": ... print c ... b o o y a h
  • 14. 14 Formatting Text "format string" % (parameter, parameter, ...) • Placeholders insert formatted values into a string: – %d an integer – %f a real number – %s a string – %8d an integer, 8 characters wide, right-aligned – %08d an integer, 8 characters wide, padding with 0s – %-8d an integer, 8 characters wide, left-aligned – %12f a real number, 12 characters wide – %.4f a real number, 4 characters after decimal – %6.2f a real number, 6 total characters wide, 2 after decimal >>> x = 3; y = 3.14159; z = "hello" >>> print "%-8s, %04d is close to %.3f" % (z, x, y) hello , 0003 is close to 3.142
  • 15. 15 Strings and Integers • ord(text) - Converts a string into a number. – ord("a") is 97 – ord("b") is 98 – Uses standard mappings such as ASCII and Unicode. • chr(number) - Converts a number into a string. – chr(97) is "a" – chr(99) is "c"
  • 16. 16 Basic cryptography • Rotation cipher - shift each letter by some fixed amount – Caesar cipher - shift each letter forward by 3 "the cake is a lie" becomes "wkh fdnh lv d olh" • Substitution cipher - transform each letter into another – not a linear shift; uses some kind of letter mapping – similar to "cryptogram" or "cryptoquip" games in newspaper
  • 17. 17 Exercise • Write a program that "encrypts" a secret message with a Caesar cipher, shifting the letters of the message by 3: – e.g. "Attack" when rotated by 1 becomes "cwwcfn" – If you have time, make the program able to undo the cipher. – Can you write a function that works for a substitution cipher?