Python Basics Flashcards
What is running file in Jupyter?
A file is considered a running file until you shut it down
What is Jupyter?
Python allows you to communicate with the computer with the help of a specific software or application: Jupyter
It is a server-client application that allows you to edit your code through a web browser
It’s not a text editor that opens a new window everytime with different codes bits
Access and leave a cell
Enter + Escape
Execute line to output field
Ctrl + Enter
Can output line be modified?
No
Execute line to output field + new cell
Shift + Enter
Copy/Paste cells
Select cells (so no cursor appears in input)
With C, X and V you can copy, cut and paste
With arrow keys you can move up and down
Asterisk sign in input cell?
Can appear in the input cell –> Meaning the code takes too long
Can be stopped with the stop symbol in the viewport
Insert markdown cell
&
Convert cell from markdown to code cell and vice versa
M
Y
When using a capital in variable, for example Y instead of y, what will happen?
Will lead to an error
Assign values to x and y
x,y = (1,2)
Parentheses are not obligatory but is for readability
When you just want to print an output
print()
Number functions. Name 2
Int() –> Integer –> Will round of to integer value
float() –> Float –> Convert to decimal
With this function you can ask what type the variable is
type
How are booleans written?
Booleans need to be written in CAPITAL LETTERS
String variables how to write?
Use single or double quotes
When printing a string it will give the output without quotes
Convert number into text
str() function
Print number + text
print( str(x) + ‘Dollars’ )
Do you need to specify a variable type?
As opposed to other programming languages, Python can automatically guess the type of data you are entering –> It always knows the type of variable
When to use double quotes?
Best for working with strings since you can have single quote in your text
Two ways to add strings together
Plus sign
Trailing comma: print(‘Red’,’car’) > Will add a space
A way to include a quote in string
Backslash before the quote
What to do when 16/3 leads to ‘5’
Try:
float(16) / 3
or:
16.0
What to do when not having enough space in the line?
In that case you can use backslash \ to continue the line onto the next line without breaking the code
Difference = and ==
With = you can set a value
With == you can check if that value is true or false
What is returned: “Friday”[4]
‘a’
In Python we start from the 0 character and then start counting upwards
What to do when lines are part of a function?
When lines are part of a function you must apply indentation to it
Same goes vice versa
Indent goes with using tab
Give the order of operators for AND, NOT, OR
Order of operators
NOT
AND
OR
Example:
True and not True –> not True will be processed first
False or not True and True –> Leads to False
True and not True or True –> Leads to True because right part is True
What can be written instead of == and !=
is, and is not
What is used as elseif statement?
elif statement
Write a function steps
Start with ‘def’
Add name of function
Then parentheses with optional parameters
End with a colon
Indent and write body on next line
Call function
Name of function with parentheses and possible arguments
Use of return in function
A function always needs something in return –> Write this in the body
Can be used only once in a function!
Variable in function
A function can have a local variable that can be defined in the code block:
Write the name of the function followed by = sign
Define the variable after the = sign
Variable can then be used in the return command
How to deal with nested functions?
You can call a function within another function
In the return section of the second function you call the first function
Are parameters order sensitive?
The parameters are order-sensitive. If you do write them in a different order then give them a value in the arguments: (b=3, a=10, c=4)
Returns nr of elements (length) in a word for example
len()
Returns float of x, rounded to y decimal points. When y is not defined that rounds to 0
round(x,y)
To the power of with base of x to the power of y
pow(x,y)
Creating a list?
Like creating an array –> Use straight brackets
Use quotation marks ‘ ‘ around elements
Retrieve from list
print (Participants[1])
Use the index number and it will retrieve that entry
List: Find last entry and before last entry
Last entry –> [-1]
Before last –> [-2]
List: Delete entry
del Participants[2]
How to invoke a certain method?
object.method()
Use dot operator to call on/invoke a certain method
How to add something to a list?
Append
Participants.append(“name”)
How to extend a list with multiple list entries?
It takes one argument so of it’s multiple list entries, put it in a list first
Participants.extend([‘Name1’, ‘Name2’])
How to use variables in string?
You can write the variable without quotation marks like Participants[0]
len(Participants) –> leads to amount of entries in the list
How does slicing work?
Take out the 2nd and 3rd entry from a list
Participants[1:3] –> So from 1 til 3
Participants[:2] –> Get the first two elements –> 0 til 2
Participants[4:] –> From the fourth til the end
Participants[-2:] –> From the for last onward
How to find the index number?
Index
Participants.index(“Maria”) –> Gives the index number
Best put in variable before printing
How to nest a list?
Nested lists
Bigger_List = [List1, List2]
How to sort numbers and strings?
Sort()
Numbers = [1,2,3,4,5]
Numbers.sort()
–> Will put it in order
Sort in reverse?
Sort in reverse order:
Numbers.sort(reverse=True)
Tuples vs List
Tuples cannot be changed or modified
You cannot append or delete elements
You can place a tuple in a list and then each tuple becomes an element in the list
Create tuple?
x = (40, 41, 41)
Values are packing into a tuple
Tuple assignment
a,b,c = 1, 4, 6
(age, years_of_school) = “30,17”.split(‘ , ‘)
Results in?
age = 30
years_of_school = 17
Tuples as return in a function
New variables from function can be returned one after the other in the form of a tuple: (X,Y)
Return from tuple?
x[0] –> Return first entry in tuple
What is a dictionary? How to declare it? How to retrieve info?
Dictionary
Another way of storing data –> Like object in JS
Used with curly braces {}
Declaring dictionary
dict = {‘k1’:”cat”, ‘k2’:”dog”}
Retrieve –> Single or double quotes
dict[‘k1’]
dict[“k3”]
Replace value in dictionary?
Replacing value
dict[‘k2’] = ‘squirrel’
Fill dictionary after declaring?
Start with name1 = {}
Fill in the rest with name1[‘key1] = ‘Value1’
Fill in the rest with name1[‘key2] = ‘Value2’
Etc
get method()
What if key is not in dictionary?
Name1.get(‘key1’) –> Returns value
When key is not in the dictionary –> Python will return None
For loop syntax
for n in listname1:
print (n)
How to order loop in single line:
Order loop in single line:
print (n, end = “ “)
Will result in a comma and empty space after each entry
While loop syntax?
While loop
x = 0
while x <= 20:
print (x, end = “ “)
x = x + 2 –> Incrementing
Note when not applying a counter it will result in an infinite loop!
Explain range function
range(start, stop, step)
start –> First number in the list
stop –> Last value +1
step –> Distance between each two consecutive values
Stop value is required
Start, step values are optional!
When start value not given it will be replaced with 0
And step value will be equal to 1 when not given
Use range in a list
list(range(10)) –> Will output all integers from 0 to 9 in a list
With step value –> list(range(1,20,2))
Use range in loop
for x in range(20):
x then goes over every entry in the range
Iterate over dictionay
You can iterate over a dictionary starting from the first key to the last
You can retrieve the values with dict[i] for example
Describe object & class
Every object belongs to some class
The class defines the rules for creating that object
Example: A bike is an object of the bike-makers class
Other names for object and attributes
Object is sometimes called instance
Attributes are sometimes called properties
Is a List an object?
The list that we created earlier is an object belonging to the list class
The attributes are the data types: floats
Methods that can be applied to these floats are .extend() or .index()
What is a module?
Prewritten code containing functions and classes
Goal of module is to not having to rewrite all the code
A package consists of various modules
Sometimes people call a package a library
How to import the sqrt function?
from math import sqrt as s
call –> s(36)
Results in 6.0
Renaming imported modules?
import math as m
m.sqrt(49)
Result: 7.0