SlideShare a Scribd company logo
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

PPTX
Pointers lesson 5 (double pointer, call by value, call_by_reference)
PPTX
Introduction of calculus in programming
PDF
Filter Designing
PPTX
Recursion in c++
PDF
Minimum phase, All pass and Magnitude Squared Function
PPT
First Look at Pointers
PDF
Phase Responce of Pole zero
Pointers lesson 5 (double pointer, call by value, call_by_reference)
Introduction of calculus in programming
Filter Designing
Recursion in c++
Minimum phase, All pass and Magnitude Squared Function
First Look at Pointers
Phase Responce of Pole zero

What's hot (20)

PDF
Java Week6(B) Notepad
PPSX
CS106 Lab 9 - 1D array
PPTX
Control System Homework Help
PPTX
Electrical Engineering Exam Help
PDF
Introduction to Recursion (Python)
PPTX
Asymptotic Analysis in Data Structure using C
PPT
Data Structures- Part5 recursion
PDF
20BCE1734.pdf
PDF
Demonstration on keyword
PPTX
Javascript function
PPTX
Tail Recursion in data structure
PPT
16 subroutine
PPTX
Array and functions
PDF
Python lambda functions with filter, map & reduce function
DOCX
Chapter 5
ZIP
.Net 4.0 Threading and Parallel Programming
PPTX
Evaluation of prefix expression with example
PPTX
Javascript Function
PDF
10. array & pointer
PPSX
CS106 Lab 10 - Functions (passing by value)
Java Week6(B) Notepad
CS106 Lab 9 - 1D array
Control System Homework Help
Electrical Engineering Exam Help
Introduction to Recursion (Python)
Asymptotic Analysis in Data Structure using C
Data Structures- Part5 recursion
20BCE1734.pdf
Demonstration on keyword
Javascript function
Tail Recursion in data structure
16 subroutine
Array and functions
Python lambda functions with filter, map & reduce function
Chapter 5
.Net 4.0 Threading and Parallel Programming
Evaluation of prefix expression with example
Javascript Function
10. array & pointer
CS106 Lab 10 - Functions (passing by value)
Ad

Similar to Lecture4 (20)

PDF
Advanced Web Technology ass.pdf
PDF
Python cheatsheat.pdf
PPTX
Functions, List and String methods
PPTX
ForLoopandUserDefinedFunctions.pptx
PPTX
An Introduction To Python - FOR Loop
PPTX
DATA TYPES IN PYTHON jesjdjdjkdkkdk.pptx
DOCX
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
PPTX
Automation Testing theory notes.pptx
PPTX
Python Details Functions Description.pptx
PDF
Python lecture 05
PPTX
P2 2017 python_strings
PPTX
Recursion part 2
PPTX
function_xii-BY APARNA DENDRE (1).pdf.pptx
PPTX
Introduction to python programming ( part-3 )
PDF
Functions-.pdf
PPTX
python_computer engineering_semester_computer_language.pptx
PPTX
Learn more about the concepts of Data Types in Python
PPTX
Python 101++: Let's Get Down to Business!
PDF
PPT
Python programming unit 2 -Slides-3.ppt
Advanced Web Technology ass.pdf
Python cheatsheat.pdf
Functions, List and String methods
ForLoopandUserDefinedFunctions.pptx
An Introduction To Python - FOR Loop
DATA TYPES IN PYTHON jesjdjdjkdkkdk.pptx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
Automation Testing theory notes.pptx
Python Details Functions Description.pptx
Python lecture 05
P2 2017 python_strings
Recursion part 2
function_xii-BY APARNA DENDRE (1).pdf.pptx
Introduction to python programming ( part-3 )
Functions-.pdf
python_computer engineering_semester_computer_language.pptx
Learn more about the concepts of Data Types in Python
Python 101++: Let's Get Down to Business!
Python programming unit 2 -Slides-3.ppt
Ad

More from Rudy Martinez (18)

PPTX
CS 151Exploration of python
PPTX
CS 151 Graphing lecture
PPTX
CS 151 Classes lecture 2
PPTX
CS 151 Classes lecture
PPTX
CS151 Deep copy
PPTX
CS 151 Standard deviation lecture
PPTX
CS 151 Midterm review
PPTX
Cs 151 dictionary writer
PPTX
CS 151 homework2a
PPTX
CS 151 dictionary objects
PPTX
CS 151 CSV output
PPTX
CS 151 Date time lecture
PPTX
CS151 FIle Input and Output
PPTX
CS151 Functions lecture
PPTX
Lecture01
PPTX
Lecture02
PPTX
Lecture03
PPTX
Lecture01
CS 151Exploration of python
CS 151 Graphing lecture
CS 151 Classes lecture 2
CS 151 Classes lecture
CS151 Deep copy
CS 151 Standard deviation lecture
CS 151 Midterm review
Cs 151 dictionary writer
CS 151 homework2a
CS 151 dictionary objects
CS 151 CSV output
CS 151 Date time lecture
CS151 FIle Input and Output
CS151 Functions lecture
Lecture01
Lecture02
Lecture03
Lecture01

Recently uploaded (20)

PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Lesson notes of climatology university.
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
RMMM.pdf make it easy to upload and study
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
Trump Administration's workforce development strategy
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Classroom Observation Tools for Teachers
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Anesthesia in Laparoscopic Surgery in India
Lesson notes of climatology university.
O7-L3 Supply Chain Operations - ICLT Program
RMMM.pdf make it easy to upload and study
human mycosis Human fungal infections are called human mycosis..pptx
VCE English Exam - Section C Student Revision Booklet
Final Presentation General Medicine 03-08-2024.pptx
Final Presentation General Medicine 03-08-2024.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Orientation - ARALprogram of Deped to the Parents.pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Trump Administration's workforce development strategy
Microbial diseases, their pathogenesis and prophylaxis
GDM (1) (1).pptx small presentation for students
Classroom Observation Tools for Teachers
Chinmaya Tiranga quiz Grand Finale.pdf
Complications of Minimal Access Surgery at WLH
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3

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?