Text Size
Text Size
Exit Full Screen
Python3 Editor
Show
Source Code
View Source Code in Full Screen
#------------------------------------------------------- # Functions #------------------------------------------------------- # Functions are used to define specific behaviors in your code. They are useful for helping make your code more readable # by abstracting details from the overall program. # For example, if you are making a text-based turn-based game, human vs. computer, # you might have a function for the human's turn and a function for the computer's turn. # In the main part of the program, you wouldn't see the exact functionality for these turns, # but you would know when they occur in the sequence of instructions because of their function calls. # NOTE: In Java, functions are called "methods" because they belong to a class definition. # Some programming languages, like Python and C++, don't necessarily need a class to hold all their functions. # A function is called a function when not in a class and called a method when defined inside a class. #------------------------------------------------------------------------------------------------------ # Defining and Calling Functions #------------------------------------------------------------------------------------------------------ # In Python, define a function using the keyword "def". General format looks like this: # def functionName(param1, param2): # code here # A "parameter" is a variable in a function definition. They represent values that a function needs # so that it can properly execute its algorithm. # When you call that function (use it in your code), you would need to also include values for its parameters. # Those actual values you pass to the function are called "arguments". # EXAMPLE: A function that takes 2 number parameters, a and b, and returns their sum. def add(a, b): return a + b # A return statement is an instruction in a function that returns a value. # Return statements are indicated by the keyword "return". # You can have as many return statements as you need in your function, or none at all. They are not necessary for all functions. # They are necessary if your function is getting a value that you need to use in the rest of your code. a = int(input('Enter a number: ')) b = int(input('Enter another number: ')) c = add(a, b) # "call" the function using its name, followed by parentheses, and list all arguments inside d = c * 2 print('{} + {} = {}'.format(a, b, c)) print('{} * 2 = {}'.format(c, d)) print() # However, when the function executes a return statement, it immediately stops executing the rest of the code. # For example, if you have a return statement inside a loop, even if there are more iterations in the loop, # once it executes the return statement, the function will stop running. # EXAMPLE: A function that iterates through each character in a string to look for spaces. # It returns True if a space is found and false otherwise. def hasSpace(s): for c in s: if c.isspace(): return True print(c, end='-') return False spaces = hasSpace('Hello World') # output: H-e-l-l-o- print("\nHas a space?", spaces) # output: Has a space? True spaces2 = hasSpace('Bananas') # output B-a-n-a-n-a-s- print("\nHas a space?", spaces2) # output: Has a space? False print() # You can tell by the output from line 60 that the program stops after it finds the space and does not continue # to print out the space followed by a dash. # The output on line 62 shows the whole string and, from line 63, you can see it returned False. # That means that for the string 'Bananas' the function executed the entire loop and made it to the final return statement. # Functions don't need to have parameters. Even without parameters, you ALWAYS need the parentheses # after the name when you define or call the function. def printStory(): print('Once upon a time, there was a dragon living in a cave.') print('The dragon was lonely and spent many days staring at the') print('faraway kingdom, wishing for friends.') print('He decided to fly around and look for some,') print('eventually finding a village.') print('But everyone screamed when they saw him. Some tried attacking him.') print('He tried to protect himself by burning up their weapons,') print('But he just burned down their houses and injured them.') print('So the dragon went back home to his lonely cave.') print('A few weeks later, people in shiny armor approached his cave.') print('He was excited and stood up to greet his new friends.') print('He stepped out of the cave to show off his fire-breathing skills.') print('Instead they started attacking him.') print('The End.') printStory() print() #---------------------------------------------------------------------------------------------------------- # Global and Local Variables #---------------------------------------------------------------------------------------------------------- # There are two kinds of variables in your projects: global and local variables. # Local variables are variables scoped to the block of code in which they were defined. # Global variables are variables scoped to the entire file's code and can be accessed throughout. # These are especially important when using functions. # EXAMPLE: You have an integer variable x and you want to add 5 to its value in a function. x = 2 # pass it as a parameter so it knows what the current value is def change1(num): return num + 5 x = change1(x) # to change the value of the same variable, pass it to the function and store the result back in original value print('x =', x) # declare in the function that you want it to use the global variable x (defined outside the function) x = 2 def change2(): global x x += 5 change2() print('x =', x) print() # Important to note: you do not have to declare data collections (like lists and dictionaries) as global unless you plan # to set them equal to a whole new list/dictionary. If you are only changing values in the list by their indices/keys, then # it will work on the global variable, since these are passed by reference, NOT by value. lst = [6, 2, 4, 1, 7] def changeList(): lst[2] = 205 changeList() print('lst =', lst) # If you comment out the line "global lst" below, you will see that the output shows the list hasn't changed. # It needs to be global to change the address in memory it points to to the new list. def changeList2(): global lst lst = [100, 98, 80] changeList2() print('lst =', lst) print() #---------------------------------------------------------------------------------------------------------- # Built-in Functions #---------------------------------------------------------------------------------------------------------- # Python has a log of built-in functions that can be used throughout your program to do common operations. # You have actually been using some of these built-in functions since the beginning of this class. # print(), input(), int(), float(), str(), len(), dict(), tuple(), list(), set(), type() are all built-in functions # There are some others that are useful as well, though I will only show a couple in this lesson. # When you do the challenges, read them closely as some of the built-in functions cannot be used to solve some of them # or else they can be solved without writing an algorithm (which is the point of some of the challenges). # Read the documentation for built-in functions here: https://docs.python.org/3.6/library/functions.html a = abs(-475) # returns the absolute value of a given number print('abs(-475) =', a) # bool(x) converts the value of x to a boolean. If the value is 0 or None, then it is False, otherwise, it is True b = bool('Hello') print("bool('Hello') =", b) print("bool(None) =", bool(None)) print("bool(0) =", bool(0)) print("bool(1) =", bool(1)) print() # pow(a, b) calculates the value of a^b c = pow(3, 4) print('pow(3, 4) =', c) pi = 3.1415926535 # round(x, y) returns the value of x rounded to y number of digits precision after the decimal point d = round(pi, 4) print('d =', d) lst = [6, 3, 7, 1, 9, 2] print('lst =', lst) print('min(lst) =', min(lst)) print('max(lst) =', max(lst)) print() #----------------------------------------------------------------------------------------------------------- # Libraries/Modules #----------------------------------------------------------------------------------------------------------- # Libraries are a collection of modules (files) full of functions that are already defined # and can be used in your own projects. # Most programming languages have standard libraries, which are libraries that come pre-packaged with the # language when you install it onto your computer. # Some of Python's standard library modules include: random, math, time, datetime, os, sys # There are 3 ways to import functions from a module: # import moduleName -- ALL functions imported, but must be called as: moduleName.functionName() # from moduleName import functionName -- imports only functions listed after the import statement # imported functions are called only with their name: functionName() # from moduleName import * -- imports ALL functions from module, and they are called with only their function name #-------------------------------------------------------------------------------------------- # The random Module #-------------------------------------------------------------------------------------------- # Read more about the random module here: https://docs.python.org/3.6/library/random.html # This module is used to generate pseudo-random values. import random # You can use random.seed() to set the generator's seed value. # If you set it to the a flat number, then the random values generated will always be the same. random.seed(5) n = random.randint(1, 50) print('n =', n) # since the seed was set to 5, this always produces 40 # If you leave the parentheses empty when you call random.seed(), then it uses the current time. So each value will be different. random.seed() n1 = random.randint(1, 50) # randomly generates an integer between 1 and 50, including both 1 and 50 print('n1 =', n1) n2 = random.randrange(1, 50, 2) # randomly generates an element from the selected range(start, stop, skip) print('n2 =', n2) # works like the range() function. includes start, excludes stop, skips by the skip value n3 = random.random() # randomly generates a float between 0.0 and 1.0, including 0.0, excluding 1.0 print('n3 =', n3) fruits = ['apple', 'banana', 'orange', 'lemon', 'lime', 'kiwi', 'peach', 'plum'] f = random.choice(fruits) # selects a random value from the collection passed as a parameter print('f =', f) random.shuffle(fruits) # shuffles the values in the list passed as a parameter print('fruits =', fruits) print() # If you've ever taken a Statistics course, you may know that there are various distributions for values. # This library has functions for those, like uniform(), triangular(), and gauss(). #-------------------------------------------------------------------------------------------- # The math Module #-------------------------------------------------------------------------------------------- # Read more about the math module here: https://docs.python.org/3.6/library/math.html # This module has all the math functions that may or may not have an operator character defined for them. import math # There are 5 constants defined for the library that you can use. print('pi =', math.pi) # PI print('e =', math.e) # e print('tau =', math.tau) # equal to 2 * PI print('inf =', math.inf) # infinity. Use -math.inf for negative infinity print('nan =', math.nan) # nan stands for "Not a Number" print() # inf and nan are available so you can have a number type associated to a value that is not a number, # which would avoid certain errors when using different operations # You can use various functions to round numbers to the nearest integer. print(math.ceil(math.pi)) # rounds up print(math.floor(math.pi)) # rounds down print() # other useful functions print('5! =', math.factorial(5)) print('sqrt(2) =', math.sqrt(2)) # math.sqrt(x) computes the square root of x print('3^4 =', math.pow(3, 4)) # math.pow(x, y) computes x^y print('e^3 =', math.exp(3)) # math.exp(x) computes e^x print('ln(7) =', math.log(7)) # math.log(x) is the natural log, ln(x) print('log(7, 10) =', math.log(7, 10)) # math.log(x, b) computes log base b of x, or log(x)/log(b) print('log2(7) =', math.log2(7)) # math.log2(x) computes log base 2 of x. Usually more accurate than log(x, 2) print('log10(7) =', math.log10(7)) # math.log10(x) computes log base 10 of x. Usually more accurage than log(x, 10) print() # trig functions print('math.cos(1) =', math.cos(1)) # computes math.cos(x) where x is in radians print('math.sin(1) =', math.sin(1)) # computes math.sin(x) where x is in radians print('math.tan(1) =', math.tan(1)) # computes math.tan(x) where x is in radians # There are also functions for arc cosine (acos), arc sin (asin), and arc tan (atan) and all corresponding hyperbolic functions print('23 degrees =', math.radians(23), 'radians') print('1.2 radians =', math.degrees(1.2), 'degrees') print()
CS110_Lesson6_Notes.py
( around 221 lines Python3 code )
Published By:
Mentor Sabrina
Created on
2020-11-16T14:17:39Z
Python3 Editor
- an
OYOclass
application,
own your own class today
.
Run
Result
Status:
Program is not running