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)