Function & modules lesson 31 to 38 Python Core

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Return statement

Certain functions, such as int or str, return a value that can be used later.

Comments

Comments are annotations to code used to make it easier to understand. They don't affect how code is run.

Function Argument

Lesson 33

Returning from Function

Lesson 34.1

Comments & Docstrings

Lesson 35

Function as Object

Lesson 36

Modules

Lesson 37.1

Note >> Return Function

The return statement cannot be used outside of a function definition.

Parentheses Note>>

The words in front of the parentheses are function names, and the comma-separated values inside the parentheses are function arguments.

From

These take the form from module_name import var, and then var can be used as if it were defined normally in your code.

Error

This code will throw an error because the variable is defined inside the function and can be referenced only there.

As

This is mainly used when a module or object has a long or confusing name.

The Standard Library & pip

lesson 38.1

parentheses code example

print("Hello world!") range(2, 20) str(12) range(10, 20, 3)

def my_func(): print("spam") print("spam") print("spam") my_func()

spam spam spam

def shout(word): """ Print a word with an exclamation mark following it. """ print(word + "!") shout("spam")

spam!

octothorpe

(otherwise known as a number sign or hash symbol: #). All text after it on that line is ignored.

x = 365 y = 7 # this is a comment print(x % y) # find the remainder # print (x // y) # another comment

1

from math import sqrt as square_root print(square_root(100))

10.0

def print_sum_twice(x, y): print(x + y) print(x + y) print_sum_twice(5, 8)

13 13

What is the highest number this function prints if called? def print_numbers(): print(1) print(2) return print(4) print(6)

2

def multiply(x, y): return x * y a = 4 b = 7 operation = multiply print(operation(a, b))

28

How many arguments are in this function call? range(0, 100, 5) Reason: The second parameter is the upper limit (in this case = 100), but 100 is not included. so if you run this code: for i in range(0,10): print(i, end=', ') # output is: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, So if the upper limit has to be included you have to say: for i in range(0,10 + 1): print(i, end=', ') # output is: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

3

from math import pi print(pi)

3.141592653589793

def add(x, y): return x + y def do_twice(func, x, y): return func(func(x, y), func(x, y)) a = 5 b = 10 print(do_twice(add, a, b))

30

What is the result of this code? def print_double(x): print(2 * x) print_double(3) 2 x 3 = 6 for print_double = 3 you plug in x for 3 thus equal 6

6

import random for i in range(5): value = random.randint(1, 6) print(value)

6 2 5 4 1

def max(x, y): if x >=y: return x else: return y print(max(4, 7)) z = max(8, 5) print(z)

7 8

def function(variable): variable += 1 print(variable) function(7) print(variable)py

8 Traceback (most recent call last): File "file0.py", line 6, in <module> print(variable) NameError: name 'variable' is not defined

def add_numbers(x, y): total = x + y return total print("This won't be printed") print(add_numbers(4, 5))

9

Function value

Although they are created differently from normal variables, functions are just like any other kind of value.

What is the output of this code? import math as m print(math.sqrt(25)) 25 An error occurs 5

An Error Occurs

parentheses

Any statement that consists of a word followed by information in parentheses is a function call.

Arguments note:

As you can see, the argument is defined inside the parentheses.

Do_twice

As you can see, the function do_twice takes a function as its argument and calls it in its body.

Docstrings

Docstrings (documentation strings) serve a similar purpose to comments, as they are designed to explain code.

Note: Docstrings

Docstrings (documentation strings) serve a similar purpose to comments, as they are designed to explain code.

Dry Principle

For a large programming project to be successful, it is essential to abide by the Don't Repeat Yourself, or DRY, principle.

arguments function

Functions can also be used as arguments of other functions.

my_func

Here is an example of a function named my_func. It takes no arguments, and prints "spam" three times. It is defined, and then called.

What error is caused by importing an unknown module? UnknownModuleError ModuleError ImportError

ImportError

Function

In addition to using pre-defined functions, you can create your own functions by using the def statement.

pip note:

It's important to enter pip commands at the command line, not the Python interpreter

Python Package Index (PyPI).

Many third-party Python modules are stored on the Python Package Index (PyPI).

Modules:

Modules are pieces of code that other people have written to fulfill common tasks, such as generating random numbers, performing mathematical operations, etc.

Code after Return Function

Once you return a value from a function, it immediately stops being executed. Any code after the return statement will never happen.

What does PyPI stand for? Python Package Installer Python Package Index Python Project Index

Python Package Index

Note: Python Comments

Python doesn't have general purpose multi-line comments, as do programming languages such as C.

Note: Standard library

Python's extensive standard library is one of its main strengths as a language.

What is the output of this code? def shout(word): return word + "!" speak = shout output = speak("shout") print(output) speak! word! shout!

Shout!

Note: Parameter & Arguments

Technically, parameters are the variables in a function definition, and arguments are the values put into parameters when functions are called.

What name is given to Python's preinstalled modules? Unix The Standard Library import

The Standard Library

import

The basic way to use a module is to add import module_name at the top of your code, and then using module_name.var to access functions and values with the name var in the module.

Def Note>>

The code block within every function starts with a colon (:) and is indented.

Note >>>

The code uses the randint function defined in the random module to print 5 random numbers in the range 1 to 6.

Note >>

The example above assigned the function multiply to a variable operation. Now, the name operation can also be used to call the function.

hello() def hello(): print("Hello world!") ----------------------------------------- Correct version def hello(): print("Hello world!") hello()

Traceback (most recent call last): File "file0.py", line 1, in <module> hello() NameError: name 'hello' is not defined -------------------------- Hello world!

Can a docstring contain multiple lines of text? No Yes

Yes

Code reuse

a very important part of programming in any language.

Fill in the blanks to define a function that prints "Yes", if its parameter is an even number, and "No" otherwise. ____ even(x): if x%2 == 0: _____("Yes") __________ print("No")

def even(x): if x%2 == 0: print("Yes") else: print("No")

Fill in the blanks to define a function named hello: _______ hello()___ print("Hi!")

def hello(): print("Hi !")

Fill in the blanks to define a function that takes two arguments and prints their multiplication. _____print_mult(x, y)__ print(x *_____ )

def print_mult(x, y): print(x *y )

Rearrange the code to declare a function sayHi() and call it. def sayHi(): print("Hi!") sayHi()

def sayHi(): print("Hi!") sayHi()

Fill in the blanks to define a function that compares the lengths of its arguments and returns the shortest one. def shortest_string(x, y): if len(x) <= _____(y): _______ x else: _______ y

def shortest_string(x, y): if len(x) <= len (y): return x else: return y

Fill in the blanks to pass the function "square" as an argument to the function "test": ____square(x): return x * x def test(func, x)__ print(func(x)) test(__________, 42)

def square(x): return x * x def test(func, x) : print(func(x)) test(square, 42)

Following the DRY principle makes the code: easier to maintain bad and repetitive loop forever

easier to maintain

Fill in the blanks to import only the sqrt and cos functions from the math module: _____ math import______ cos

from math import sqrt, cos -------------------------- sqrt with comma ,

Fill in the blanks to import the math module. _______math

import math

Which module is being used in this code? import math num = 10 print (math.sqrt(num)) math sqrt num

math

def print_with_exclamation(word): print(word + "!") print_with_exclamation("spam") print_with_exclamation("eggs") print_with_exclamation("python")

spam! eggs! python!

Standard Library

standard library, and contains many useful modules. Some of the standard library's useful modules include

LIST of Standard Library

string, re, datetime, math, random, os, multiprocessing, subprocess, socket, email, json, doctest, unittest, pdb, argparse and sys.

Wet Principle

which stands for Write Everything Twice, or We Enjoy Typing.

Fill in the blank to comment out the text: x = 8 _____printing x print(x)

x = 8 # printing x print(x)


Set pelajaran terkait

Certmaster Learn for A+ CORE 1 (Exam 220-1101) Flash Cards

View Set

Lecture 19: Altruism/Kin Identification

View Set

PATHOPHYSIOLOGY and PHARMACOLOGY Alzheimer's Disease (AD)

View Set

Improving Sentence Structure, Part 4

View Set

Geometry Chapter 7 Theorems and Postulates

View Set