2 Flashcards
Python: The lines within each block ( : ) must be
Indented e.g.
if var_1 == True:
print(“its true”)
break
Python: The function that places a value in the {} placeholder is
str.format(“value”) e.g. print(“my name is {}”.format(“Alen”))
Python: For a while loop, typing “while True:” will cause it to
loop forever, unless you add a “break” e.g.
if var_1 == 5
break
Python: For loops, the statement that will cause the loop to return to the top, without continuing the rest of the loop is called
continue
Python: To iterate/loop on every value in a list, use
for made_up_var in list_var:
print(made_up_var)
Python: Python stripts run in sequence so
Do not try to use a variable that only gets assigned later in the script
Python: For functions with arguments you must
Send in a value or else you will get an error
Python: An argument, with regards to functions, is
A value you pass into the function when you run it. e.g. my_function(argument1, argument2)
Python: You must tell a function what values to return by typing
return var_1, var_2
Python: functions start with the word
def
Python: function names should only use
lower case letters and underscores
Python: To add another if statement after the first one use
elif e.g.
elif var_1 == “SHOW”:
show_list()
continue
Python: After defining a function, to run it you must
call it e.g. my_function(argument)
Python: To import a python library, type
import name_of_library, into the python interpreter or top of script
Python: To call the “choice” method form the “random” library, type
random.choice()
Python: Can you create a new variable inside a function
Yes
Python: It’s recommended to do all the imports
at the beginning of the script
Python: It’s recommended to do the imports
at the beginning of the script
Python: You can imbed if and else commands
inside other if and else commands
Python: To get an automatic list of numbers starting from zero, type
list(range(10))
Python: You cannot reference variables outside of a function
From within the function. You must pass it in.
Python: To assign multiple variables simulaneously, type
var_1, var_2 = “Phil”, “Bill”
Python: Values on the right side of a variable always get
Evaluated first
Python: To insert a list into the middle of another list, type
list_1.insert(4, list_2)
The 4 denotes the index to insert at
Python: To generate a range of numbers, possibly for a loop, type
range(10)
Python: You can concatenate two lists together, without placing the second list within one index, by typing
[1, 2, 3] + [4, 5]
Python: Should you add a colon : after calling, not defining, a function?
No
Python: To add a line to a string, type
\n
Python: To do arithmetic on a variable in a shorter way, type
var += 2
var -= 2
var *= 2
var /= 2
Python: To remove all white space from the beginning and end of a string, type
“My string”.strip()
Python: Strings that are placed in a list must
have “ “ around them. e.g.
[“a”, “b”, “c”]
Python: Strings are
Immutable
Python: Lists are
Mutable
Python: To remove one item from a list by its index, type
del my_list[2]
Python: The del function does not work on
Strings, because they are immutable.
Python: To delete a list item by passing its value, type
my_list.remove(value)
Python: The remove() function only removes
The first instance of the passed value in the list
Python: When you use remove() on a value that does not exist it
throws an exception, so use within try/except
Python: To make a string lower case, type
lower(“STRING”) or “STRING”.lower()
Python: To capitalize the first letter of a string, type
capitalize(“string”) or string.capitalize()
Python: To remove a value from a list by its index and return it, type
my_list.pop(2)
Python: Inputs, input(), that are numbers should
Be converted to int() because input() is a string by default
Python: To return a portion of a list of string, type
my_list[3:4] or “my string”[1:6]
Python: To slice until the end of a string without knowing its length, type
my_string[1:len(my_string)]
Python: Slices, [:], do not alter a list, they
Return a copy of it
Python: To slice a list or string by returning steps that skip, type
my_list[1::2], Add an extra colon
Python: To return a string or list backwards using slice, type
my_string[::-1], make the skipping step a negative, and swap the start and end range [10:1:-1]
Python: Slices that start a range as a negative
Move the start point backwards through the end of the string or list and start slicing from there.
Python: Standard format for a function
my_list = list(range(3))
def first_4(my_iterable): four_arg = my_iterable[:4] return four_arg
first_4(my_list)
Python: Function checklist
The function def ends with :
The function is called somewhere
All of the arguments defined in the function are being passed in
All of the lines are indented the same
The variable referenced in the function are also assigned in the function
It ends with return
Python: Can you delete from the middle of a string?
No
Python: To delete a slice, type
del my_list[1:3]
Python: To replace a slice of a list with new items, type
my_list[4:7] = [“e”, “f”]
Python: The sections of the slice function are
[start:stop:step]
Python: To return the value associate with a key inside a dictionary, type
my_dict[“key_name”]
Python: To create a dictionary, type
my_dict = {“Key”: “Value”, “Key2”: “Value2”}
Python: You cannot return a key and value from a dictionary by its index because
The order changes and the keys and values are not attributed to an index
Python: Can you create a dictionary as a value of a key in another dictionary?
Yes
Python: Can you create lists within lists?
Yes
Python: The append() function is not recommended for concatenating 2 disparate lists because
It places the entirety of the appended list into the very last index of the initial string and does not set the values into individual indexes of the initial list.
Python: To return the value of a key in a dictionary that itself is the value of a key in a superceding dictionary, type
my_dict[“key_name”][“key_name2”]
Python: Returning a value from inside a function does not print it, it
Turns the calling function into that value.
Python: Functions must end with
return
Python: Before saving new code always check presence of
All necessary colons and indentations.
Python: The format for a “for loop” that checks for the presence of each of a lists items in a dictionary and then adds the items that are present to another list, is
present_in_list = []
for item in my_list:
if item in my_dict:
present_in_list.extend(item)
Python: elif requires
a True value test in order to run
Python: else does not require
a test because it runs whenever the test on “if” was False
Python: Returning a value from inside a function does not print it, it
Turns the value of the of the calling function into the returned value. If more than one value it returns as a tuple.
Python: The boolean values True and False must be
capitalized.
Python: To fill placeholders in a string using the format method without knowing which order to put the values, you can assign key names to values by typing
“My name is {name_key} and I am {age_key} years old”.format(age_key=”22”, name_key=”Alen”)
Python: To use the key name placeholders in the format method with the key values are stored in a dictionary, type
my_dict = {“state”: “California”, “name”: “Alen”}
“I am {name} and I live in {state}”.format(**my_dict)
Python: To create a new key for a dictionary, type
my_dict[“new_key_name”] = “value”
Python: To change the value of an existing dictionary key name, type
my_dict[“key_name”] = “new_value”
Python: To delete a key from a dictionary, type
del my_dict[“key_name”]
Python: To add and change values of multiple dict keys at once, type
my_dict.update({“job”: “Teacher”, “age”: “23”, “gender”: “male”})
Python: To create an empty dictionary, type
my_dict = {}
Pandas: To use pandas and be able to call it by a shorter name, type
import pandas as pd
Python: This returns a
def method(): return var_1, var_2, var_3
method()
Tuple
Python: To return a tuple with the index and value from an iterable, type
enumerate(my_iterable)
Python: To unpack an enumerate()d tuple into a “for loop”, type
for tuple in enumerate(my_iterable):
print(“This is item number {} and it is a {}”.format(*tuple))
or
for index, item in enumerate(my_iterable):
print(“This is item number {} and it is a {}”.format(index, item))
or
for tuple in enumerate(my_iterable):
print(“This is item number {} and it is a {}”.format(tuple[1], tuple[2]))
Python: One asterisk in the format function
Unpacks a tuple
Python: To unpack an item tuple into a “for loop”, type
for key, value in my_iterable.items():
print(“This is the key {} and the value is {}”.format(key, value))
Python: You can create a tuple with either
placing a comma between 2 values or tuple()
Python: If a function returns three values you can either
Pack it into one variable or unpack it into three variable seperated by commas.
Python: To capitalize the first letter of every word, type
titlecase(“my_string”)
Python: To create a function that doesn’t need to be passed every parameter because there are defaults, type
def my_function(param_1=”A”, param_2=”B”, param_3=”Var”):
my_function()
IPYNB: To launch the IPython Notebook from the console, type
ipython notebook
Python: To run a python script, type into the console
python3 ~/myfolder/script.py
Python: When using a “for loop” on a dictionay, the “item” variable only takes on the value of
The key, not the key value
Python: To use a “for loop” on a dictionary and have the “item variable” iterate on the dictionaries values instead of the keys, type
for key in my_dict.values():
print(key)
or
for key in my_dict:
print(my_dict[key])
Python: To create a tuple, type
my_tuple = (1, 2, 3)
Python: For tuples, the parenthesis
Aren’t required. Only the commas are required.
Python: A tuple is an
Immutable list that can be packed and unpacked.
Python: You can turn a list into a tuple by typing
my_tuple = tuple(my_iterable)
Python: To return the value at a certain index in a tuple, type
my_tuple[2]
To enter the python interpreter in the cosole, type
python
Python script file names end with
.py
to exit the python Interpreter you type
exit()
To exit the help(word) function, type
q
To look up the attributes and methods of a class use
dir(nameofclass)
To assign a user input to a variable, type
var_1 = input(“Whatever you want the prompt to the user to be?”)
To invoke a newer language you installed in the terminal type
e.g. python3
To create a new text file, type
nano new_name.py
The placeholder for the str.format() method is
{} e.g. “I’m {}, and you are {}”.format(“Alen”, “Mike”)
The if and else function lines must end with
: (also try and except)
The methods that come after the if and else statements must
Be indented the exact same amount. The amount of spaces or tabs doesn’t matter.
A number with a decimal is called a
Float
A number without a decimal is called an
Integer
You can turn a string to an integer and a float with
int(“55”) float(“2.2”)
You can turn a float into an integer, and and integer into a float with
int(5.5) and float(5)
True + False will evaluate to
1 because True has a value of 1 and False has a value of 0
To check if a string is not in a variable string
if not “searchstring” in user_num:
print(“not here”)
To compare if two values are equal use
==
To try running something that might cause errors use
try:
1 / 0
except:
print(“script messed up”)
You can check if a string is in another string or list by typing
“g” in “dog”
This would return True
To get more info on a function, type
Into the interpreter, help(str.split)
To return the length of a list, type
len(my_list)
To return an item in a list by its index, type
my_list[3]
To change the value of one index in a list, type
my_list[3] = “new value”
To seperate all the letters of a string into seperate list items
list(“my string”)
To seperate the words in a string by white space, type
my_string.split()
To join a list with a delimiter, type
“_“.join(my_list)
The extend() method
Appends the second list onto the initial list and returns “None”. The second list remains the same value but the initial list will now contain the additional list indexes.
Console: Servers usually do not have a
GUI
Console: The “~” in the command line stands for
The home directory e.g. users/student/
Console: Usually the first word in the command line is
The username you are signed in as
Console: To list the files in your current directory, type
ls
Console: To list the files in the current directory with more detail, like permissions, type
ls -l
Console: To list all the files in the current directory including the hidden dot files, type
ls -a
Console: To clear the screen, type
clear
Console: to list the files in another directory, type
ls user/student/folder/
Console: “Folders” is synonymous with
Directories
Console: To see your current directory, type
pwd
Console: The home directory (“~”) usually contains the folders
My Documents, Pictures, etc.