Unit 10: Advanced topics in Python Flashcards
In this unit, you will be learning ____________.
In this unit, you will be learning about some of the helpful tools that Python comes with that you can use to create programs that solve all kinds of problems. These functions are available as soon as you load up Python. Unlike modules like the turtle module, you don’t need to import anything first. Our textbook goes over 12 very useful functions. We’re going to discuss some of those that are most important and relevant.
What are some of the math functions?
The abs() function gives you the absolute value of a number which is the value of the number without the positive or the negative sign.
our next function is the bool function, which is short for Boolean. When we learnt about conditional statements, we learnt about how these statements evaluate to “True” or “False”, and then an if statement or a while loop will run based on that result. The bool function can help you find out if a statement is “True” or “False” without having to put it in an if statement or a while loop. This function takes one parameter, which is the statement that you want to evaluate. The most important use of this function for us is that it returns “True” if a variable has something in it or “False” if a variable does not have anything in it.
being able to see whether you variables have data in them can come in handy.
This use of the bool function allows you the make sure that your user entered something when asked.
The next-built in function we’re going to discuss is the float() function. Along with the float function, we have the int function. Int()—> turn user input into a number to use for calculations and other aspects of our program.
Remember, a floating-point number is a decimal number, whereas an integer is a positive or negative whole number. You can use both the float function and the int function to turn a string into a floating-point number and an integer respectively. You can also use the int function to turn a floating-point number into an integer.
The len() function lets you know the length of a list, dictionary, or a string.
min() and max()
list(), range()
sum()
The absolute value of 3 is ______
3
The absolute value of -3 is _______
3
The only parameter that the abs function takes is ________________
The only parameter that the abs function takes is the number of which you’re trying to find the absolute value.
For e.g.
abs(3)
Output:
3
For e.g.
abs(-3)
3
test_variable_1 = “Hello!”
test_variable_2 = “ “
print(bool(test_variable_1))
print(bool(test_variable_2))
What is the output of this?
True
False
Since test_variable_1 has the “Hello!” string in it, the function returned “True” (in this case, “True” tells us that there is something in the variable)
Since test_variable_2 did not have anything in it, the function returned “False” (in this case, “False” tells us there is nothing in the variable).
Does the bool function work for other data types too other than strings?
Yes, this works for other data types, like lists as well.
What is the output of this?
empty_list = [ ]
number_list = [1,2,3,4,5]
print(bool(empty_list))
print(bool(number_list))
False
True
our empty list has nothing in it, so the bool function returned “False”, whereas our list of numbers does have data in it, so the bool function returned “True”.
age = input(“How old are you?”)
while not bool(age):
print(“You need to enter an age. Please try again.”)
age = input(“How old are you?”)
print(“You are “ + str(age) + “ years old!”)
Explain this code
The first line asks the user how old he or she is.
Then we get to a while loop that will run whenever “not bool(age)” is True.
The not keyword means take the opposite Boolean value; so , if you had an expression that evaluates to “True”, the “not” of the expression would be “False” (and, likewise, if you had an expression that evaluates to “False”, the “not” of that expression would be “True”).
So
If age is empty, bool(age) will return False and we want our while loop to run (evaluate to “True”) if age is empty, so we take the opposite of that with “not”. Inside our while loop, we give the user an error message and then ask for the input again.
Since it’s a while loop, these two steps will keep occurring until the user correctly enters some kind of input.
Finally, once a correct input is received, the program prints out the age. This use of the bool function allows you the make sure that your user entered something when asked.
What is the output of this?
float_string = “3.1”
result_1 = float(float_string) + 1
result_2 = int(result_1)
print(result_1)
print(result_2)
4.1
4
string = “I love Python!”
length = len(string)
print(length)
What is the output of this and why?
The output of this is 14.
As expected, this string contains 14 characters. Remember, spaces are included as a character.
We can use a for loop to print out each of the characters in a string. You can refer to a string like it’s a list for this.
string = “I love Python!”
length = len(string)
for count in range(0, length):
print(length)
I
l
o
v
e
p
y
t
h
o
n
What is the output of this?
numbers = [2,9,4]
print(min(numbers))
print(max(numbers))
2
9
you can also put the numbers right into the min and the max functions like this
print(min(2,9,4))
print(max(2,9,4))
You will still get the same output. This is a good time saving trick if you do not need to keep your list of numbers around for something else
list()
range() functions
What are the meaning of each of the above functions?
How can list() and range() be used together?
The list function creates a list from information given to it.
What the range function actually returns is a special thing called an iterator. you can also add a third parameter, called the step. This lets you count “by” the number. You don’t need to add 1, since Python assumes that is the way to count unless stated otherwise by your code.
You can use the list function to store this information in it.
print(list(range(0,7)))
Output:
[0,1,2,3,4,5,6]
Can you count using a negative number?
Yes.
You can also count the other way by using a negative number as the step and reversing the two numbers so that you are starting at a higher number and going to a lower number, like this: print(list(range(7,0,-2)))
What does the sum() function do?
This lets you add up the contents of your list.
Replace some parts of the code with sum() for this code:
def calculate_average(scores):
total = 0
number_of_scores = len(scores)
for count in range(0, number_of_scores):
total = total + scores[count]
average = total/number_of-scores
return average
def calculate_average(scores):
number_of_scores = len(scores)
total = sum(scores)
average = total/number_of-scores
return average
scores = [93,87,98,82]
print(calculate_average(scores))
How do you go into the builtins catalog and help menu?
Open up IDLE and type in the following. Note the two underscores “_” before and after builtins.
> > > dir(__builtins__)
When you press ENTER, you should see a list of all of the built-in functions available to you:
[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ‘BaseException’,…
…‘str’, ‘sum’, ‘super’, ‘tuple’, ‘type’, ‘vars’, ‘zip’]
Now you can use the “help()” function to figure out how to use any of the built-in functions listed. For example, lets look at the min function:
> > > help()
Welcome to Python 3.9’s help utility!
…..
help> min
Press ENTER again and you should see a description of the min() function, including any parameters that you’ll need to include when you call it in your code.
Help on built-in function min in module builtins:
min(…)
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the smallest argument. Basically, this is telling you that you need to include something iterable, like a list, when you call the function min(), and it will return its smallest item. For example:
> > > min([5,18,3,109,1,64,2])
1
When you’re done exploring the built-ins, type “quit” to exit the help menu and return to IDLE.
help> quit
You are now leaving help and returning to the Python interpreter.
…
»>
What is the built-in function for returning the value of a number without the positive or negative sign?
abs(my_variable)
What is the built-in function for taking a string and returning a decimal for arithmetic?
float(my_variable)
What is the built-in function for taking a string and returning a whole number for arithmetic?
int(my_variable)
What is the built-in function that returns True if a variable has something in it or False otherwise?
bool(my_variable)
What is the built-in function for this: keyword that evaluates the opposite of a boolean value (either True or False)?
not bool(my_variable)
What is the built-in function for returning the number of items in a list?
len(my_list)
What is the built-in function for creating a new list?
list(item1,item2,item3)
What is the built-in function to return a special iterator to step through a list?
range()
Create a list of integer values, then sort and reverse the list using built in functions.
Create the reversed list
Your code should look like this
#Create a list
my_list = [22,31,3,5,66,32,9,11]
#Create the sorted list
my_sorted_list = sorted(my_list)
my_reversed_list = sorted(my_list, reverse=True)
print(my_list)
print(my_sorted_list)
print(my_reversed_list)
What are modules?
Modules are a collection of functions, variables, and other things together that you can use to build programs.
What is this module “sys” ,object “stdin”, and the function “readline()” for?
It gives us another way to read in information from our user. (get input from the user)
What is the output of this?
import sys
def say_hi():
print(“What’s your name?”)
user_name = sys.stdin.readline()
print(“Hello, {}”.format(user_name))
say_hi()
What’s your name?
John
Hello, John
What is the module datetime for?
to find out the exact time and date now
What is the output of this?
import datetime
print(datetime.datetime.now())
It depends on when you are coding this. The date and time will be reflected accordingly.
Which of the following correctly uses a Python module to get input from the user?
system.userinput()
sys.stdin.getline()
system.input()
sys.stdin.readline()
sys.stdin.readline()
Which of the following correctly uses Python’s datetime module to get the current date and time?
datetime.now()
datetime.gettime(now)
datetime.datetime.now()
import datetime.now()
datetime.datetime.now()
How can you create our own module?
You can create a module by simply writing Python objects (functions, lists, variables, etc.) inside a program file with .py extension and then save the file in a directory or folder where another Python program can access the module file. It could be in the same folder where the caller program resides or a folder in PYTHONPATH (an environment variable which you can be set to add additional directories where Python will look for modules and packages). PYTHONPATH is out of the scope of this tutorial, so we will only discuss the first option.
Imagine that you would like to create a module called my_calculator to do multiplication, division, addition, and subtraction using two numbers. First, let’s write the following 4 functions in a program called my_calculator.py and save that file into a folder.
def add(num1, num2):
print(“{} + {} = {}”.format(num1,num2, (num1+num2)))
def sub(num1, num2):
print(“{} - {} = {}”.format(num1,num2, (num1-num2)))
def mult(num1, num2):
print(“{} x {} = {}”.format(num1, num2, (num1*num2)))
def div(num1, num2):
print(“{} / {} = {}”.format(num1, num2, (num1/num2)))
my_calculator is now a module that you can use to do mathematical arithmetic operations in another program that imports the my_calculator module.
Now, say you would like to use my_calculator module inside a program file called test_module.py. You would need to write the following Python program and save that file into the same folder where you’ve already saved the my_calculator.py file : ____________________________
import my_calculator
my_calculator.add(4, 5)
my_calculator.sub(10, 2)
my_calculator.div(18, 3)
my_calculator.mult(5, 6)
Using the import statement, you made the module objects or contents available in your program. However, you can’t directly access the functions like
add(4, 5)
sub(10, 2)
div(18, 3)
mult(5, 6)
This is because a module creates a separate namespace (an area where a name is unique and can be used without any ambiguity). By pre-fixing the module name, you can get the access to that module namespace.
If you don’t want to use the module name as prefix using the “.” operator, you will need to import the objects inside the module into your program like this example:
from my_calculator import *
Now you can use those function with any prefix.
add(4, 5)
sub(10, 2)
div(18, 3)
mult(5, 6)
Note that asterisk ‘*’ in the import statement means to import all objects inside the module. This isn’t, however, a recommended approach in a large program because you are importing all those variables and function names into your own program namespace. This could cause a naming conflict unless you know them all well and can be confident there won’t be a conflict. Otherwise, you have a decent chance of overwriting an existing name inadvertently.
A better alternative would be to bring in a few functions that you would like to use from the module. For example: say you would like to use the mult function only. You could import the mult function from the module like the example below and then use that function directly.
from my_calculator import mult
mult(5, 6)
Some of the advantages of creating and using modules in Python are: they enable you to organize your code into smaller pieces that are easier to manage and the code in the modules can be reloaded and rerun as many times as needed, which enables code reuse.
This is one of the way in which you can import module
import module_name
What happens?
Why use it?
Give an example.
What happens?
The whole module is imported, and you can use all its functions and variables.
To call a function, you need to prefix it with the module name (e.g., module_name.function_name()).
Why use it?
Keeps things organized because every function you call is clearly linked to the module.
No risk of naming conflicts since you’re using the module name to differentiate functions.
Example:
python
Copy code
import my_calculator
my_calculator.add(4, 5) # Clear where ‘add’ comes from
my_calculator.sub(10, 2)
This is one of the ways in which you can import module.
from module_name import specific_function
What happens?
Why use it?
Give an example.
What happens?
You import only specific functions or variables that you want from the module.
You don’t need the module name prefix to use the functions.
Why use it?
Makes your code shorter and more readable if you’re only using a few specific functions.
Saves memory if the module is large but you only need some parts of it.
Example:
python
Copy code
from my_calculator import add, sub
add(4, 5) # No need for my_calculator.
sub(10, 2)