SlideShare a Scribd company logo
1 of 13
CS 151
Lecture 4
Rudy Martinez
CS151 Spring 2019
Goals
● Show how to SSH using NoMachine
● Show how to startup Spyder3
● Explain functions in python3
● Explain range(start, stop, step) function
● Explain __name__ == “__main__”
CS151 Spring 2019
Functions in Python3
Functions , like math, takes an argument(s) and returns zero or more values.
Structure
def funcName(arg1, arg2):
def : keyword to specify define a function
funcName: you can name your function anything but making it self describing
helps. (i.e. isPalindrome)
arg1,arg2: Arguments you pass to the function can be zero or more
CS151 Spring 2019
Functions cont ...
Structure cont…
def funcName(arg1, arg2):
Statements
return( value )
Your function can contain any number of statements to do what ever the function
is designed to do.
return(): This is what you return to the calling program.
CS151 Spring 2019
Example function
def add2numbers(myInt1, myInt2):
# Trivial example
tempInt = myInt1 + myInt2
return(tempInt)
This is trivial and pedantic to show an example, it could easily be written with one
line:
return(myInt1 + myInt2)
However, your programs will most likely not be so simple.
Also there are no error checking, this function assumes you will use it correctly.
This can be a bad assumption and you should check that myInt is actually an
integer.
CS151 Spring 2019
The range function in Python
You can always go right to the source documentation and lookup what a python
function does: https://docs.python.org/3/
Top right hand corner give a search box: range [enter]
class range(start, stop[, step])
start integer, remember we have 0 based indexing.
stop integer, can be an integer, boolean or function (i.e. len(myString))
step what increment or decrement to use, usually 1 or -1 but could be anything.
CS151 Spring 2019
Range example
def printString(myString):
for myIndex in range( 0, len(myString)-1, 1):
print(myString[myIndex])
This function will use a for loop to print from 0 to string length minus 1,
incrementing by +1 on each iteration.
Why -1 on string length?
Let myString = ‘Palindrome’ len(myString) returns 10 not 9
len(myString)-1 returns 9 which is the last character.
Index 0 1 2 3 4 5 6 7 8 9
string P a l i n d r o m e
CS151 Spring 2019
A real example program
A Palindrome is a sentence or word that is the same forward and backward.
String = 123454321
Bad algorithm:
Algorithm for Palindrome:
Reverse the given string and compare to original string
CS151 Spring 2019
A real example program, continued
A Palindrome is a sentence or word that is the same forward and backward.
String = 123454321
Good algorithm:
Algorithm for Palindrome:
Copy original string
Reverse string
Compare each string
If they are equal then return True, else return False.
CS151 Spring 2019
A real example program, continued
String = 123454321
Best algorithm:
Algorithm for Palindrome:
Reverse string
Loop from end of original string and append to a new string
Compare temp string to original string
If they are equal then return True, else return False.
CS151 Spring 2019
Convert to Python
def reverse(myString):
tempString = ‘’ #create an empty string
for myIndex in range(len(myString)-1, -1, -1): # more on this next
tempString += myString[myindex] #copy to new string
return(tempString)
def isPalindrome(myString):
revString = reverse(myString)
if myString == revString:
return(True)
else:
return(False)
#Call isPalindrome
print(isPalindrome(‘123454321’)
CS151 Spring 2019
Explanation
The for loop in reverse may look weird.
for myIndex in range(len(myString)-1, -1, -1):
Remember:
So len(myString) returns 10, but our index is 9 so we subtract one to accomodate
0 based indexing.
We stop at -1, since the for loop stops at 0 not -1, the operator is < not <=
Finally our step is decrementing by 1, so -1
Index 0 1 2 3 4 5 6 7 8 9
String P a l i n d r o m e
CS151 Spring 2019
More Explanation
We do not need to write the reverse function, however, we will see how we can
call reverse from another python program using an import statement.
How can we make this program better?
Error checking?
Whitespace, punctuation removal?

More Related Content

What's hot

CS106 Lab 9 - 1D array
CS106 Lab 9 - 1D arrayCS106 Lab 9 - 1D array
CS106 Lab 9 - 1D arrayNada Kamel
 
Electrical Engineering Exam Help
Electrical Engineering Exam HelpElectrical Engineering Exam Help
Electrical Engineering Exam HelpLive Exam Helper
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)Thai Pangsakulyanont
 
Asymptotic Analysis in Data Structure using C
Asymptotic Analysis in Data Structure using CAsymptotic Analysis in Data Structure using C
Asymptotic Analysis in Data Structure using CMeghaj Mallick
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursionAbdullah Al-hazmy
 
Demonstration on keyword
Demonstration on keywordDemonstration on keyword
Demonstration on keyworddeepalishinkar1
 
Javascript function
Javascript functionJavascript function
Javascript functionLearningTech
 
Tail Recursion in data structure
Tail Recursion in data structureTail Recursion in data structure
Tail Recursion in data structureRumman Ansari
 
16 subroutine
16 subroutine16 subroutine
16 subroutinefyjordan9
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionARVIND PANDE
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel ProgrammingAlex Moore
 
Evaluation of prefix expression with example
Evaluation of prefix expression with exampleEvaluation of prefix expression with example
Evaluation of prefix expression with exampleGADAPURAMSAINIKHIL
 
Javascript Function
Javascript FunctionJavascript Function
Javascript Functionxxbeta
 
10. array & pointer
10. array & pointer10. array & pointer
10. array & pointer웅식 전
 
CS106 Lab 10 - Functions (passing by value)
CS106 Lab 10 - Functions (passing by value)CS106 Lab 10 - Functions (passing by value)
CS106 Lab 10 - Functions (passing by value)Nada Kamel
 

What's hot (20)

Java Week6(B) Notepad
Java Week6(B)   NotepadJava Week6(B)   Notepad
Java Week6(B) Notepad
 
CS106 Lab 9 - 1D array
CS106 Lab 9 - 1D arrayCS106 Lab 9 - 1D array
CS106 Lab 9 - 1D array
 
Control System Homework Help
Control System Homework HelpControl System Homework Help
Control System Homework Help
 
Electrical Engineering Exam Help
Electrical Engineering Exam HelpElectrical Engineering Exam Help
Electrical Engineering Exam Help
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)
 
Asymptotic Analysis in Data Structure using C
Asymptotic Analysis in Data Structure using CAsymptotic Analysis in Data Structure using C
Asymptotic Analysis in Data Structure using C
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
20BCE1734.pdf
20BCE1734.pdf20BCE1734.pdf
20BCE1734.pdf
 
Demonstration on keyword
Demonstration on keywordDemonstration on keyword
Demonstration on keyword
 
Javascript function
Javascript functionJavascript function
Javascript function
 
Tail Recursion in data structure
Tail Recursion in data structureTail Recursion in data structure
Tail Recursion in data structure
 
16 subroutine
16 subroutine16 subroutine
16 subroutine
 
Array and functions
Array and functionsArray and functions
Array and functions
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming
 
Evaluation of prefix expression with example
Evaluation of prefix expression with exampleEvaluation of prefix expression with example
Evaluation of prefix expression with example
 
Javascript Function
Javascript FunctionJavascript Function
Javascript Function
 
10. array & pointer
10. array & pointer10. array & pointer
10. array & pointer
 
CS106 Lab 10 - Functions (passing by value)
CS106 Lab 10 - Functions (passing by value)CS106 Lab 10 - Functions (passing by value)
CS106 Lab 10 - Functions (passing by value)
 

Similar to Lecture4

Assignment 6 as a reference public class ArrExample pr.pdf
Assignment 6 as a reference   public class ArrExample    pr.pdfAssignment 6 as a reference   public class ArrExample    pr.pdf
Assignment 6 as a reference public class ArrExample pr.pdfkksrivastava1
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2docSrikanth
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptxSulekhJangra
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5alish sha
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2Amit Kapoor
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa Thapa
 
Ecs 10 programming assignment 4 loopapalooza
Ecs 10 programming assignment 4   loopapaloozaEcs 10 programming assignment 4   loopapalooza
Ecs 10 programming assignment 4 loopapaloozaJenniferBall44
 
function in python programming languges .pptx
function in python programming languges .pptxfunction in python programming languges .pptx
function in python programming languges .pptxrundalomary12
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxCatherineVania1
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdfNehaSpillai1
 

Similar to Lecture4 (20)

Assignment 6 as a reference public class ArrExample pr.pdf
Assignment 6 as a reference   public class ArrExample    pr.pdfAssignment 6 as a reference   public class ArrExample    pr.pdf
Assignment 6 as a reference public class ArrExample pr.pdf
 
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
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
4. functions
4. functions4. functions
4. functions
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
 
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
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Ecs 10 programming assignment 4 loopapalooza
Ecs 10 programming assignment 4   loopapaloozaEcs 10 programming assignment 4   loopapalooza
Ecs 10 programming assignment 4 loopapalooza
 
function in python programming languges .pptx
function in python programming languges .pptxfunction in python programming languges .pptx
function in python programming languges .pptx
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
 

More from Rudy Martinez

More from Rudy Martinez (18)

CS 151Exploration of python
CS 151Exploration of pythonCS 151Exploration of python
CS 151Exploration of python
 
CS 151 Graphing lecture
CS 151 Graphing lectureCS 151 Graphing lecture
CS 151 Graphing lecture
 
CS 151 Classes lecture 2
CS 151 Classes lecture 2CS 151 Classes lecture 2
CS 151 Classes lecture 2
 
CS 151 Classes lecture
CS 151 Classes lectureCS 151 Classes lecture
CS 151 Classes lecture
 
CS151 Deep copy
CS151 Deep copyCS151 Deep copy
CS151 Deep copy
 
CS 151 Standard deviation lecture
CS 151 Standard deviation lectureCS 151 Standard deviation lecture
CS 151 Standard deviation lecture
 
CS 151 Midterm review
CS 151 Midterm reviewCS 151 Midterm review
CS 151 Midterm review
 
Cs 151 dictionary writer
Cs 151 dictionary writerCs 151 dictionary writer
Cs 151 dictionary writer
 
CS 151 homework2a
CS 151 homework2aCS 151 homework2a
CS 151 homework2a
 
CS 151 dictionary objects
CS 151 dictionary objectsCS 151 dictionary objects
CS 151 dictionary objects
 
CS 151 CSV output
CS 151 CSV outputCS 151 CSV output
CS 151 CSV output
 
CS 151 Date time lecture
CS 151 Date time lectureCS 151 Date time lecture
CS 151 Date time lecture
 
CS151 FIle Input and Output
CS151 FIle Input and OutputCS151 FIle Input and Output
CS151 FIle Input and Output
 
CS151 Functions lecture
CS151 Functions lectureCS151 Functions lecture
CS151 Functions lecture
 
Lecture01
Lecture01Lecture01
Lecture01
 
Lecture02
Lecture02Lecture02
Lecture02
 
Lecture03
Lecture03Lecture03
Lecture03
 
Lecture01
Lecture01Lecture01
Lecture01
 

Recently uploaded

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 

Recently uploaded (20)

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 

Lecture4

  • 2. CS151 Spring 2019 Goals ● Show how to SSH using NoMachine ● Show how to startup Spyder3 ● Explain functions in python3 ● Explain range(start, stop, step) function ● Explain __name__ == “__main__”
  • 3. CS151 Spring 2019 Functions in Python3 Functions , like math, takes an argument(s) and returns zero or more values. Structure def funcName(arg1, arg2): def : keyword to specify define a function funcName: you can name your function anything but making it self describing helps. (i.e. isPalindrome) arg1,arg2: Arguments you pass to the function can be zero or more
  • 4. CS151 Spring 2019 Functions cont ... Structure cont… def funcName(arg1, arg2): Statements return( value ) Your function can contain any number of statements to do what ever the function is designed to do. return(): This is what you return to the calling program.
  • 5. CS151 Spring 2019 Example function def add2numbers(myInt1, myInt2): # Trivial example tempInt = myInt1 + myInt2 return(tempInt) This is trivial and pedantic to show an example, it could easily be written with one line: return(myInt1 + myInt2) However, your programs will most likely not be so simple. Also there are no error checking, this function assumes you will use it correctly. This can be a bad assumption and you should check that myInt is actually an integer.
  • 6. CS151 Spring 2019 The range function in Python You can always go right to the source documentation and lookup what a python function does: https://docs.python.org/3/ Top right hand corner give a search box: range [enter] class range(start, stop[, step]) start integer, remember we have 0 based indexing. stop integer, can be an integer, boolean or function (i.e. len(myString)) step what increment or decrement to use, usually 1 or -1 but could be anything.
  • 7. CS151 Spring 2019 Range example def printString(myString): for myIndex in range( 0, len(myString)-1, 1): print(myString[myIndex]) This function will use a for loop to print from 0 to string length minus 1, incrementing by +1 on each iteration. Why -1 on string length? Let myString = ‘Palindrome’ len(myString) returns 10 not 9 len(myString)-1 returns 9 which is the last character. Index 0 1 2 3 4 5 6 7 8 9 string P a l i n d r o m e
  • 8. CS151 Spring 2019 A real example program A Palindrome is a sentence or word that is the same forward and backward. String = 123454321 Bad algorithm: Algorithm for Palindrome: Reverse the given string and compare to original string
  • 9. CS151 Spring 2019 A real example program, continued A Palindrome is a sentence or word that is the same forward and backward. String = 123454321 Good algorithm: Algorithm for Palindrome: Copy original string Reverse string Compare each string If they are equal then return True, else return False.
  • 10. CS151 Spring 2019 A real example program, continued String = 123454321 Best algorithm: Algorithm for Palindrome: Reverse string Loop from end of original string and append to a new string Compare temp string to original string If they are equal then return True, else return False.
  • 11. CS151 Spring 2019 Convert to Python def reverse(myString): tempString = ‘’ #create an empty string for myIndex in range(len(myString)-1, -1, -1): # more on this next tempString += myString[myindex] #copy to new string return(tempString) def isPalindrome(myString): revString = reverse(myString) if myString == revString: return(True) else: return(False) #Call isPalindrome print(isPalindrome(‘123454321’)
  • 12. CS151 Spring 2019 Explanation The for loop in reverse may look weird. for myIndex in range(len(myString)-1, -1, -1): Remember: So len(myString) returns 10, but our index is 9 so we subtract one to accomodate 0 based indexing. We stop at -1, since the for loop stops at 0 not -1, the operator is < not <= Finally our step is decrementing by 1, so -1 Index 0 1 2 3 4 5 6 7 8 9 String P a l i n d r o m e
  • 13. CS151 Spring 2019 More Explanation We do not need to write the reverse function, however, we will see how we can call reverse from another python program using an import statement. How can we make this program better? Error checking? Whitespace, punctuation removal?