EXAM 3 Flashcards
(17 cards)
- What is a function? The syntax for writing a function in Python?
def function_name(parameters):
# code block
return result # optional
Ex.
def greet(name):
print(“Hello,”, name)
Formal parameters and actual parameters must match in _______, ________, and _________.
number, order, and type
What is a keyword argument? How to call a function with mixed keyword and positional arguments?
Keyword Argument: Specifies which argument the value is passed to
def greet(name, greeting):
print(greeting, name)
greet(“Alice”, greeting=”Hello”)
What are the two types of functions? Does a void function have a return statement?
Void Function: Simply executes the statements it contains and then terminates.
Value-Return Functions: Executes the statements it contains, and then it
returns a value back to the statement that called it.
A void function does NOT have a return statement.
How do you call a function from the main function in the same program? How do you call a function from another module?
def main():
greet(“Dennis”)
def greet(name):
print(“Hello,”, name)
main()
What is a list? How to create a list?
A list is an object that contains multiple data items
myList = [item1, item2, etc.]
What is scope? local variable vs. global variable
Scope: the part of a program in which a
variable may be accessed
Local Variable: variable that is assigned a value inside a function
Global Variable: created by assignment
statement written outside all the functions
pass by value vs. pass by reference
Pass by value: The value of the variable is
passed to the function.
Pass by reference: For mutable types like list, the object itself is passed.
What are the values in a list called? What is the position of a value in a list called?
Values = elements
Position = index
Using sample as your list name, how can you represent the length of the list?
size = len(my_list)
Find min/max number in list integers
min del list[i]
and max functions: built-in functions that
returns the item that has the lowest or highest
value in a list
Cube function and test in main:
def cube(x):
return x ** 3
def main():
print(cube(3)) # Output: 27
main()
Three modes to open a file and their differences:
r: To read the file
w: To write in the file
a: To append the file
Open the text file elements to write to? Does it need to exist? Close it.
f = open(“elements.txt”, “w”)
f.write(“Hello\n”)
f.close()
- Open nobleGrades to read from? Does it need to exist?
f = open(“nobleGrades.txt”, “r”)
data = f.read()
f.close()
The file NEEDS to exist!!!!
- How do you write a class in Python? How to create an instance of a class?
class Dog:
def __init__(self, name):
self.name = name
def bark(self): print("Woof!", self.name)
Create instance
my_dog = Dog(“Buddy”)
my_dog.bark()