Download presentation
Presentation is loading. Please wait.
1
More on Functions (Part 2)
Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg
2
What are functions? Little pieces of code that we can write and invoke by name Reusable General
3
Functions Take in any number of parameters Possibly compute something
Including no parameters! Possibly compute something Return a value Can be None If no return is specified, returns None
4
Function that takes in no parameters
def answerToEverything(): return 42 This function takes in no parameters It does no computation Just returns a number
5
Function that returns nothing
Let’s take a look at print() >>> result = print(“hi”) >>> print(result) None >>>
6
None None is a special value in Python that represents nothing
The first letter of None must be capitalized – it will turn orange Use it when you have nothing to return Like if one of the parameters was invalid
7
Functions Remember, a function stops running when it hits a return statement Often times it is easier to write something as a function than as a script by itself Let’s look at our old script to find a prime number
8
prime.py number = int(input("Please enter a number greater than 2. ")) isPrime = True #break out condition divisor = 2 while divisor<number and isPrime: if number%divisor==0: print("The number",number,"is divisible by",\ divisor) isPrime=False # Going to break out divisor=divisor+1
9
prime.py (continued) if isPrime: print("That number is prime") else: print("That number is NOT prime")
10
primeAsFunction.py def isPrime(number):
for divisor in range(2,number): if number%divisor==0: return False return True Much smaller!
11
Lab 9 Questions?
12
Exam #2 Same format as Exam #1 Over Chapters 3-5
Does not include functions Study guide now available
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.