Python Keywords Flashcards
Python3 familiarity
and
a logical operator
x = 5
print(x > 3 and x < 10) # both must be True
as
To create an alias
import numpy as np
assert
The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError.
Write a message if the condition is False:
x = “hello”
#if condition returns False, AssertionError is raised: assert x == "goodbye", "x should be 'hello'"
break
End the loop if i is larger than 3:
for i in range(9):
if i > 3:
break
print(i)
class
To define a class
**class** Person: def \_\_init\_\_(self, name, age): self.name = name self.age = age
p1 = Person(“John”, 36)
p1 # (John, 36)
continue
To continue to the next iteration
for i in range(9):
if i == 3: # 3 is skipped
continue
print(i) # (0,1,2,4,5,6,7,8)
def
To define function
def my_function():
print(“Hello from a function”)
my_function()
del
To delete an object
thislist = [“apple”, “banana”, “cherry”]
del thislist[0] # removes apple
print(thislist)
thislist = [“apple”, “banana”, “cherry”]
del thislist # deletes entire list
elif
Used in conditional statements, The elif is short for else if.
a = 33 b = 33
if b > a:
print(“b is greater than a”)
elif a == b:
print(“a and b are equal”)
else:
print(‘this’)
else
Used in conditional statements
catches anything which isn’t caught by the preceding conditions.
a = 200 b = 33
if b > a:
print(“b is greater than a”)
elif a == b:
print(“a and b are equal”)
else:
print(“a is greater than b”)
except
Used with exceptions, what to do when an exception occurs.
The except block lets you handle the error.
try:
print(x) # not defined
except:
print(“An exception occurred, define your vaiables!”)
False
Boolean value, result of comparison operations
a = 200 b = 33
if b > a: # True
print(“b is greater than a”)
else: # False
print(“b is not greater than a”)
finally
Used with exceptions, a block of code that will be executed no matter if there’s an exception or not.
The finally block will always be executed, no matter if the try block raises an error or not:
try:
x > 3
except:
print(“Something went wrong”)
else:
print(“Nothing went wrong”)
finally:
print(“The try…except block is finished”)
for
To create a for loop
fruits = [“apple”, “banana”, “cherry”]
for x in fruits:
print(x)
from
To import specific parts of a module
from collections import OrderedDict
a = [1,2,2,3,4,4,5,5,5]
res = list(OrderedDict.fromkeys(a))
print(res)
global
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
To create a global variable inside a function, you can use the global keyword
def myfunc(): **global** x x = "fantastic"
myfunc()
print(“Python is “ + x)
if
To make a conditional statement
a = 33 b = 200
if b > a: # conditional True or False
print(“b is greater than a”)
import
To import a module into a project
import pandas as pd
import numpy as np
in
Membership operators are used to test if a sequence is presented in an object:
fruits = [“apple”, “banana”, “cherry”]
for x in fruits:
if x == ‘banana’:
break
print(x)
is
Identity operator are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location
x = 27
y = ‘27’
x is y # False
lambda
lambda arguments : expression
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
None
The None keyword is used to define a null value, or no value at all.
x = None
if x:
print(“Do you think None is True?”)
elif x is False:
print (“Do you think None is False?”)
else:
print(“None is not True, or False, None is just None…”)
nonlocal
Make a function inside a function, which uses the variable x as a non local variable:
def myfunc1(): x = "John" def myfunc2(): **nonlocal** x x = "hello" myfunc2() return x
print(myfunc1())
not
The not keyword is a logical operator.
The return value will be True if the statement(s) are not True, otherwise it will return False.
x = False
print(not x) # True
or
Logical operators are used to combine conditional statements.
The return value will be True if one of the statements return True, otherwise it will return False.
x = (5 > 3 or 5 > 10) # either can be True
print(x)
pass
A null statement, a statement that will do nothing.
Python functions can’t be empty
def my\_function(): **pass**
raise
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
x <= -1
if x raise Exception(“Sorry, no numbers below zero”)
return
To exit a function and return a value.
Exit a function and return the sum:
def myfunction(): **return** 3+3
print(myfunction())
True
Boolean value, result of comparison operations.
x is not y
print(x) # True
try
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
These exceptions can be handled using the try statement:
try:
print(x)
except:
print(“An exception occurred”)
while
With the while loop we can execute a set of statements as long as a condition is true.
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
with
Used to simplify exception handling
using with statement
with open(‘file_path’, ‘w’) as file:
file.write(‘hello world !’)
yield
To end a function, returns a generator
An infinite generator function that prints # next square number. It starts with 1
def nextSquare():
i = 1;
An Infinite loop to generate squares
while True:
yield i*i
i += 1 # Next execution resumes
from this point
is not
Identity operator are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location
x = 27 y = '27'
x is not y #True
not in
Membership operators are used to test if a sequence is presented in an object:
a = [1,2,2,3,4,4,5,5,5] res = []
for num in a:
if num not in res:
res.append(num)
print(res)
Truthy or Falsie
bool(0)
Falsie
Truthy or Falsie
bool(1)
Truthy
Truthy or Falsie
bool([])
Falsie
Truthy or Falsie
bool(‘’ ‘)
Falsie
Given Truthy or Falsie, sum this code
True + 5 + True
7
Given Truthy or Falsie, sum this code
True - False - False + True
2
Given Truthy or Falsie, sum this code
True * 4
4