Www.abss.k12.nc.us



Unit 1 – Python language basics, introducing data types, variables, input, functions, operators, conditional statements, loops, and incrementing.Module 2 – FunctionsFunctions are used for code tasks that are intended to be reused. Python allows us to create User Defined Functions and provides many Built-in Functions such as print() and type().Note:? DEFINE a function with PARAMETERS and PASS ARGUMENTS.print() can be called using arguments (or without them) and sends text to standard output, such as the consoleprint() uses Parameters to define the variable arguments that can be passed to the functionprint() defines multiple string/number parameters which means we can send a long list of Arguments to print(), separated by commasprint() can also be called directly with just its name and empty parenthesis and it will return a blank line to standard outputEXAMPLES:??print(“Hello, world!”, “I am sending string arguments to print “)studentAge = 17studentName = “Hiroto Yamaguchi”print(studentName, “ will be in the class for ”, studentAge, “ year old students.”)print(“line 1”) ? ? ?#print function contains 1 argumentprint(“line 2”)? ? ? #print function contains 1 argumentprint()? ? ? ? ? ? ? ? ? ? # line 3 is an empty return – the default when there are no argumentsprint(“line 4”) ? ? ? #print function contains 1 argumentThe print() function can print Integer or string values.print(type())? = returns the data type of the python objects.When using type, the result will display the data type of the information in the parenthesis: str = when python detects a string of characters (numbers, letters, punctuation…. ) in quotesint = when python detects an integer (positive or negative whole number)float = when python detects decimal numbers (i.e:? 3.1569, 0.0, 9.9999, 5.0)print() formatting of strings can be done several ways:? the + and the , are two ways. Using a comma-separating string with print() will output each object separated by a space, by default. If you are combining integer or float with strings you should use the , to avoid errors.Defining Functions:?Define using defUse indentation (4 spaces) – this tells the editor what goes the function and not a regular line of code.Define parametersOptional parametersreturn values (or none) – when the editor gets to return it stops and returns to the main codeFunction scope (basics defaults)Format for defining a function:Function name starts with a letterFunction name contains only letters, numbers or _() follows the Function nameColon follows the () :Code for the Function is indented under the function definition (use 4 spaces for this course)EXAMPLESdef sampleFunction():????#code the function tasks using indention of 4 spacesThe end of the function is denoted by returning to no indentationCalling Functions. Call a simple function using the function name followed by parentheses. For instance, calling print is print().??EXAMPLE: ? this will define and call both the sayHi and threeThree functionsdef sayHi():????print(“Hello there”)????print(“goodbye”)# end of indentions ends the functiondef threeThree():???print(33)sayHi()??? ??? ??? # This is how to call the sayHi function using no argumentsthreeThree()??? ??? # This is how to call the threeThree function using no argumentsFunction Parameters. print() and type() are examples of built-in functions that have parameters defined. type() has a parameter for a Python Object and sends back the type of the object (int, str, float).?An Argument is a value given for a parameter when calling a function. type() is called providing an Argument.Defining Function Parameters:??Parameters are defined inside of the parentheses as part of a function def statementParameters are typically copies of objects that are available for use in function codeEXAMPLE:def sayThis(phrase):??? # phrase is a variable and is the parameter?????print(phrase)??? ??? # the parameter variable phrase will be printedFunctions can have default arguments:Default arguments are used if no argument is suppliedDefault arguments are assigned when creating the parameter listEXAMPLES:def sayThis(phrase = “Hi”):??? #function with default parameter:? “Hi”????print(Phrase)def yellThis(phrase):??? ??? #function defined with NO default parameter, passed from the call argument????print(phrase.upper() = “!”)??? ??? yellThis(“It is time to save the program”)? # call has argument to pass to function: “It is time to save the program”def sayThis(phrase = “Hi”): ? ? ? ? ? def sayThis(phrase = “Hi”):??? # the function is defined with the default parameter: “Hi”????print(phrase)??? ??? ??? sayThis()??? ??? ??? # This call has no argument to pass, so the function will print the default parameter “Hi”sayThis(“Bye”)??? ??? ??? # This call has an argument to pass, so the function will print “Bye”NOTE:? Pass an Argument and Define a Parameter (call statement = argument, def statement = parameter)Functions with Return Valuestype() returns an object typetype() can be called with a float, the return value can be stored in a variable?def? smallestNum(n1, n2, n3)????print min()????return min()RETURN explained: “a function can take some input (usually one or more variables or values) and return some output (usually a single value). For example smallestNum() takes one or more arguments as input and returns the smallest of numbers as output. That is exactly the purpose of the return keyword. Without return, your function returns nothing (technically, it returns an object that is used in Python to represent nothingness, namely none).Not every function needs to return a value. If all you want is to print the number, then you don’t need to return it. But if you want to use the returned value/output inside another calculation or expression, you need to use return.?Think of return as a stop sign, all code after return in a function is ignored and execution jumps to the next coding statement. ”? --Codecademy. For more information visit this link: .EXAMPLE: ? ? ? objectType = type(2.33)Creating a function with a return value:return keyword in a function returns a value AFTER exiting the function. It may help to think of it like if you don’t want to print it, use return in the function.EXAMPLE:? msgDouble returns the string argument repeated two timesdef msgDouble(phrase):??? ??? # Define function called msgDouble with phrase as the parameter??????? double = phrase + “ “ + phrase??? # the variable double is assigned the phrase a space and phrase again??????? return double??? ??? ??? # the return keyword passes the variable double as argument to replace the function call??? ??? msg2x = msgDouble(“let’s go”)? # This statement is executed AFTER the function and return put ‘Phrase space phrase’ in the???? ??? ??? ??? ??? # function msgDouble. Therefore, msg2x will have the value of the function ‘Phrase space Phrase’??? print(msg2x)??? ??? ??? # prints msg2x that was assigned the value from function msgDouble??? Example output = let’s go let’s goEXAMPLE:? A function with return values used in the function??? def msgDbl(phrase):??? ??? ??? ? ? double = phrase + “ “ + phrase??? ? ? return double? print(msgDbl(“What ‘cha doing ”))??? ??? #prints the returned object – the variable msgDbl??? print(type(msgDbl(“What ‘cha doing “)))??? ??? #prints the type of the returned object – the variable msgDblFunctions can have multiple parameters separated by commas.EXAMPLE:??? def makeSchedule(block1, block2):??? ? ? schedule = (“[1st] “ + block1.title() + “, [2nd] “ + block2.title())??? ? ? Return schedule??studentSchedule = makeSchedule(“mathematics”, “history”)??print(“SCHEDULE: “, studentSchedule)Sequence. In programming, sequence refers to the order that code is processed. Objects in Python, such as variables and functions, are not available until they have been processed. Processing sequence flows from the top of a page of code to the bottom. This often means that Function definitions are placed at the beginning of a page of code.EXAMPLE:? the function below: hatColor cannot be accessed since it is initialized after it is called at the bottom of the code.This demonstrates an error (NameError) – the code is executed from top to bottom and this is in the wrong sequence. To correct it just move the top two lines of code to below the Function.NameError:? a common error that occurs when you call an object before it is defined; or misspell a variable or function.???? haveHat = hatAvailable(“green”)? print(“hat available is”, haveHat)??? def hatAvailable(color):???? ? ? hatColors = “black, red, blue, green, white, grey, brown, pink”??? ? ? Return(color.lower() in hatColors)NOTE: an argument or variable is said to be hard coded when assigned a literal or constant value. It is a good habit to avoid creating hard coded values in functions such as:? hatColors = “black, red, blue, green, white, grey, brown, pink”.Hard-Coding is placing data values directly into code. An example of hard-coding from above is haveHat = hatAvailable(“green”) where the argument “green” is hard-coded. BEST PRACTICE is to avoid hard-coding values when possible. Adhering to Best Practices, shown below, will allow changing the data without disturbing the main code and makes code more reusable. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download