Python Fundamentals Flashcards
What are Python files called?
Python modules
Python files have a .py extension
How do you write a single line comment in Python?
Pound sign: # comment
Correct syntax is a space between pound and text
How do you write multiline comment in Python?
””” Triple Quotes “””
This is most often used in function or class documentation.
How do you use string interpolation rather than the string format function?
name = “Python”
machine = “HAL”
f”Nice to meet you {name}. I am {machine}”
Note: You must put the f in front to let the interpreter know you want to use string interpolation.
What does Python use in lieu of curly braces for code blocks?
Indentations to indicate blocks of code.
What is the equality operator in Python?
Double equals ==
What has a Truthy value?
Any number other than 0
A string as long as it is not an empty string
What has a Falsy value?
The number 0
The keyword None
What is a list like?
How do you define a list?
A list is very similar to an array in other languages. It is even indexed the same.
You define a list by adding empty square brackets to a variable name:
student_names = []
What is the separator for a list?
The comma: student_names = [“Mark”, “Katarina”, “Jessica”]
How do you access list elements?
Use bracket notation:
student_names[0] == “Mark”
list name, then index.
How do you access the last item in a list?
You would use a -1 index.
student_names[-1] == “Jessica”
Second to last would be -2, and so on…
Note: Doesn’t work on a zero index going backwards. No such thing as neg. zero.
How do you append an item to a list?
Use the .append() function:
student_names.append(“Homer”)
How do you check to see if an item is in a list?
You just write the following:
“Mark” in student_names
This will evaluate to True
How do you see how many items are in a list?
Use the len() function: len(student_names) == 4
Can use len for other items, not just exclusive to lists.
How do you delete an element in a list?
use the del keyword:
del student_names[2]
Note: Elements in list will shift to the left.
If you wanted to slice the first element out of a list, how would you do that?
Use the following syntax:
student_names[1:]
This skips the first element and returns everything else.
Note: This will not modify the list, just temporarily ignore elements. The list is still intact
If you want to skip the first 2, you use [2:] and so on…
How do you ignore the first and last elements in a list?
Use the following syntax:
student_names[1:-1]
Remember, the last element is not zero indexed because you can’t have a negative zero number, so it’s -1
Note: This will not modify the list, just temporarily ignore elements. The list is still intact
What are the 2 main loops in Python?
For Loop
While Loop
What is the general syntax of a For loop?
for name in student_names:
print(“Student name is {0}”.format(name))
Note the colon at the end of the line “:” - very important
“name” can be any variable: x, name, boo, whatever…it just represents each item in the list that is being iterated over.
read as: for every “name” in the student_names list, do this…
Works like a foreach loop in other languages.
How do you use the range function?
Syntax:
x = 0
for index in range(10):
x += 10
print(“The value of x is {0}”.format(x))
range(10) would mean “I want to execute this code ten times”.
The index and (10) numbers are index numbers [0, 1, 2…10]
Range supports more arguments:
range(5, 10): Start at 5 and end at 10 [5, 6, 7, 8, 9]
range(5, 10, 2): Start at 5, end at 10, but increment by 2 [5, 7, 9]
What keyword do you use to stop the program execution at any point in your loop?
You use the break keyword:
ex:
for name in student_names:
if name == “Homer”:
print(“Found him! “ + name)
break
print(“Currently testing “ + name)
Break will exit the loop when the criteria tests true.
When would you use the continue keyword?
When you want to skip an item in your loop.
Ex.
for name in student_names:
if name == “Bort”:
continue
print(“Found him! “ + name)
print(“Currently testing “ + name)
This will skip the name “Bort” in the list and continue through each iteration.
It says “stop executing code and continue onto the next iteration”
How do you increment in a while loop?
x += 1
This will increment by 1
+= 2 will increment by two, and so on…
What is the general syntax for a while loop?
x = 0
while x < 10:
print(“Count is {0}”.format(x))
x += 1
While checks the condition before entering the loop.
You need to include a manual increment (x += 1)
What is a Dictionary?
Allows you to easily store data in Key/Value pairs.
Similar to JSON
Syntax:
student = {
“name”: “Mark”,
“student_id”: 15163
“feedback”: None
}
How do you group multiple dictionaries together?
You would create a list of dictionaries:
ex.
all_students = [
{“name”: “Mark”, “student_id”: 15163},
{“name”: “Katarina”, “student_id”: 63112},
{“name”: “Jessica”, “student_id”: 30021}
]
How do you access data from a dictionary?
You would use bracket notation:
student[“name”] == “Mark”
Here, “name” is the key, and “Mark” is the value of the key/value pair.
How would you prevent a KeyError when accessing a key in a dictionary that may not exist?
You would provide a default value if the key was missing:
student.get(“last_name”, “Unknown”) == “Unknown”
If last_name doesn’t exist in the dictionary, then instead of throwing an error it will return “Unknown”
How do you display all the keys in a dictionary?
How about all the values?
student. keys()
student. values()
Will give you a list of all the keys or all the values in a dictionary.
How do you change the value of a key/value pair in a dictionary?
student[“name”] = “James”
Just a simple assignment of a new value to the key.
How do you delete a key in a dictionary?
del student[“name”]
This deletes the entire key and shifts everything to the left.
Explain how to do error handling in Python
Use Try / Except code blocks:
try:
last_name = student[“last_name”]
except KeyError:
print(“Error finding last_name”)
print(“This code executes!”)
Try runs the code, and if the exception happens, it gives a graceful way of handling the error, so the code can continue running. Otherwise, the program will stop where the error happened.
When doing exception handling, how do you chain exceptions together to check for more than one exception?
You just put one after another, like this:
try:
last_name = student[“last_name”]
numbered_last_name = 3 + last_name
except KeyError:
print(“Error finding last_name”)
except TypeError:
print(“I can’t add these two together!”)
print(“This code executes!”)
In error handling, how do you handle errors that you don’t know about?
You use except Exception to catch unknown errors:
try:
last_name = student[“last_name”]
numbered_last_name = 3 + last_name
except KeyError:
print(“Error finding last_name”)
except TypeError:
print(“I can’t add these two together!”)
except Exception:
print(“Unknown error”)
What if you want to know the exact error message when you are exception handling? How do you show the error?
Do the following:
try:
last_name = student[“last_name”]
numbered_last_name = 3 + last_name
except KeyError:
print(“Error finding last_name”)
except TypeError as error:
print(“I can’t add these two together!”)
print(error)
This will print out the exact error message for you.
When should you use exception handling?
Most of the time, when you are writing to a file, you should use exception handling.
Also, if you feel a certain piece of code has a tendency to fail, wrap it in a try…except block.
Most often failure occurs around user input.
What is the function syntax in Python?
def functionname(argument):
block of code
Remember:
- def keyword
- () parenthesis
- Colon:
- No trailing function close characters…just indentation
What does the return keyword do in a function?
It returns the result of a function run, whatever that may be.
The result can be further used in other parts of the program.
Contrasted with print() function, which just prints the result to the console and nothing else.
What is a function argument?
How many arguments can you have?
Data that you can pass to the function when it is run
def add\_student(name): students.append(name)
You can have zero, one, many, or variable number of arguments for each function.
How do you set a default value for an argument?
You would add it to the argument in the function definition:
def add\_student(name, **student\_id=332**): students.append(name)
add_student(“Mark”, 332)
The addition of the =332 is the default value.
What are named arguments?
Simply a way to make your code clearer by adding the argument name to your value when you call the function:
add_student(name=”Mark”, student_id=332)
Not necessary to do, but it makes your code more readable.
How do you define a function with a variable number of arguments?
def var_args(name, *args)
*args allows you to put any number of arguments in the function call and Python won’t complain.
How do you use Keyword Arguments?
You can define arguments when you call them and it will become a key/value pair for each argument.
This creates a dictionary.
def var\_args(name, \*\*kwargs): print(name) print(kwargs)
var_args(name, a=12, b=10)
print(kwargs) would return a dictionary {a:12, b:10}
Note: You drop the asterisks when you use the kwargs code.
How do you prompt for user input?
Use the input function:
student_name = input(“Enter student name: “)
This will prompt the user and assign the result to the student_name variable.
What is a closure?
A closure is when a nested function has access to the variables in the outer function.
What happens if you use the open function in write mode to write to a file?
f = open(“students.txt”, “w”)
It will overwrite whatever is in the file.
If you simply want to add to the file, you would use the “a” parameter instead. This will append to the file.
Why do you need to use the .close() function after each file operation?
To prevent memory leaks
To indicate to the OS that the file is no longer in use
Some OS put a lock on a file while it is in use. Using close() will release the file.
What is the keyword used to define a class?
The class keyword
class Student:
below, all the functions and variables associated with this class.
Note: The class name is always Capitalized.
What are functions in a class called?
Methods
They are essentially the same thing.
How do you create a new instance of a class?
Use this general syntax:
student1 = Student()
Explain what the self keyword is in relation to Python classes.
self refers to the class or variable itself.
When an object is instantiated, it refers to the object itself (the current instance of the class.)
When you define a class method, the first argument always has to be self:
class Student: def add\_student(**self,** name, student\_id=332): student = {"name": name, "student\_id": student\_id} students.append(student)
However, you do not have to pass the self argument when you call the method.
What is the constructor method in Python?
It’s a special method which gets executed every time you create a new instance of a class.
by default, it’s hidden, but we can create our own constructor and customize the instantiation behavior.
How do you customize the class constructor method?
You define a method with the name __init__
class Student: def \_\_init\_\_(self, name, student\_id=332): student = {"name": name, "student\_id": student\_id} students.append(student)
Now, when this is called, it will require the name argument and the student_id argument.
Get the idea?
What do you need to remember when creating a class method?
When you define a class method, the first argument always has to be self:
class Student: def add\_student(self, name, student\_id=332): student = {"name": name, "student\_id": student\_id} students.append(student)
However, you do not have to pass the self argument when you call the method.
Explain what a Class Attribute is
Simply data that can be accessed from all methods in a class.
The variables are available throughout the entire instance, even when defining the methods. They are aware of any attributes in the instance.
Springfield Elementary would be an example of a class attribute:
class Student:
school_name = “Springfield Elementary”
def __init__(self, name, student_id=332):
self. name = name
self. student_id = student_id
students. append(self)
def \_\_str\_\_(self): return "Student " + self.name
It is available to every method within the class to use.
What if you want certain attributes to be the same across all instances of a class?
You can use a static variable.
school_name is an example of a static variable.
class Student:
school_name = “Springfield Elementary”
def __init__(self, name, student_id=332):
self. name = name
self. student_id = student_id
students. append(self)
def \_\_str\_\_(self): return "Student " + self.name
def get\_name\_capitalize(self): return self.name.capitalize()
def get\_school\_name(self): return self.school\_name
If you define a method based on a class attribute, what do you need to add?
You need to add self when defining methods based on class attributes:
def get\_school\_name(self): return self.school\_name
Explain class inheritance
Class inheritance means that you can create a second class that inherits all of the attributes and methods from the parent class.
syntax:
class HighSchoolStudent(Student):
This will inherit everything from the Student class
How do you override attributes or methods of a parent class in an inherited class?
You can just define it anew in the derived class:
class HighSchoolStudent(Student):
school_name = “Springfield High School”
In the Student class, school_name was something different.
You can override the behavior of the parent methods in an inherited class by simply defining the same method as in the parent class and use it in the inherited class.
In an inherited class, can you override the derived method but still keep using the parent method as well?
Yes, you would use the super() keyword
def get\_name\_capitalize(self): original\_value = **super().get\_name\_capitalize()** return original\_value + "-HS"
in this code, we pull the original .get_name_capitalize() method and add something to it without having to rewrite the entire method.
When you break your program up into different modules or if you are using a third party library, how do you import it into your main python program?
You can use the import keyword:
from module_name import *
The asterisk means “import everything” (Sometimes this isn’t the best strategy…it can result in namespace issues)
You can import individual classes or functions or methods as well instead of everything by listing them explicitly.
What is the most popular Python framework?
django
It powers sites like Instagram, Pinterest, the Onion, NASA, and others.
What is a GET request?
When you fetch a web page or web element
What is a POST request?
When you send data to a web server
ex. Submitting a form
What are Python virtual environments?
Virtual environments allow you to set up independent Python environments.
For ex:
You cannot have two Django environments installed on same machine…you’ll get a version conflict. With virtual environments, however, you can have both versions of Django on your machine and they don’t care about each other. They are completely isolated from one another.
How do you install the virtual environments module?
How do you create a new virtual environment?
From command line:
You install virtual environments using pip
command: pip install virtualenv
Create a virtual environment:
virtualenv <env_name></env_name>
How do you specify the Python version you want your virtual environment to use?
Command:
virtualenv –python=python2.7 <env_name></env_name>
–python is a flag
How do you activate your virtual environment?
command:
$source /bin/activate
If successful, prompt will be prefixed with the virtual env name:
(env_name) $
If you install packages using pip in a certain virtual environment, are they active anywhere else?
No. They are only installed to the single virtual environment.
They will not be active anywhere else, not even the global Python environment.
How do you exit a virtual environment?
Simply type this command:
deactivate
How do you use PyCharm to set up virtual environments?
In PyCharm settings, search for “interpreter options”
What is a breakpoint?
How do you set a breakpoint in PyCharm?
Line in our code that when reached will pause execution of the program and allow you to inspect the programming environment.
In PyCharm, you just click to the right of the line number and a breakpoint will be set.
What program can you use to create executable files for your Python program?
Software is called pyinstaller.
How to use it:
pip install pyinstaller
navigate to path where Python code lives
type pyinstaller main.pi (whatever your main file is) and hit Enter
Pyinstaller takes care of associated modules and packages them.
You can use the –onefile flag if you want to package just one file