ITEP 206 Lesson 2
ITEP 206 Lesson 2
ITEP 206 Lesson 2
INTEGRATIVE PROGRAMMING
TECHNOLOGIES 1
LESSON 2
The Python 33 Keywords
The Python 33 Keywords
Python has a set of keywords that are reserved words that cannot be
used as variable names, function names, or any other identifiers.
Logical Operators (and, not, or)
AND
NOT
OR
as
assert
• The assert keyword is used when debugging code.
• The assert keyword lets you test if a condition in your code
returns True, if not, the program will raise an AssertionError.
x = "hello"
#if condition returns True, then nothing happens:
assert x == "hello"
#if condition returns False, AssertionError is raised:
assert x == "goodbye"
Examples: assert
x = "hello"
break
class
• The class keyword is used to create a class.
• A class is like an object constructor.
continue
• The continue keyword is used to end the current iteration in a for loop
(or a while loop), and continues to the next iteration.
Skip the iteration if the variable Use the continue keyword in a while loop:
i is 3, but continue with the i = 0
next iteration: while i < 9:
for i in range(9): i += 1
if i == 3: if i == 3:
continue continue
print(i) print(i)
Python Keywords: def
def
• The def keyword is used to create, (or define) a function.
my_function()
Python Keywords: del
del
• The del keyword is used to delete objects. In Python everything is an
object, so the del keyword can also be used to delete variables, lists, or
parts of a list etc.
print (______(8))
print (______(7))
1. Check if a number is both greater than 10
and even.
def number (number):
return number > 10 and number % 2 == 0
print (number(8))
print (number(7))
2. Verify if a person’s age is between 18 and
65, inclusive, and they have a valid driver’s
license
def x (age, has_license):
return 18 <= age <= 65 and has_license
age = 25
has_license = True
print (______(_____, _______))
______ = 16
has_license = False
print (_______(_____,has_license))
2. Verify if a person’s age is between 18 and
65, inclusive, and they have a valid driver’s
license
def x (age, has_license):
return 18 <= age <= 65 and has_license
age = 25
has_license = True
print (x(age, has_license))
age = 16
has_license = False
print (x(age,has_license))
3. Determine if a string contains both the
letter ‘a’ and the letter ‘b’.
def x(input_string):
return 'a' in ________ and 'b' in ____________
string1 = "banana"
string2 = "apple"
string3 = "kiwi"
print (____(_______))
print (____(_______))
print (____(_______))
3. Determine if a string contains both the
letter ‘a’ and the letter ‘b’.
def x(input_string):
return 'a' in input_string and 'b' in input_string
string1 = "banana"
string2 = "apple"
string3 = "kiwi"
print (x(string1))
print (x(string2))
print (x(string3))
4. Confirm if a student's grade is greater than or
equal to 70 and less than or equal to 100.
def passing_grade (grade):
return 70 <= ____ <= 100
grade1 = 80
grade2 = 65
print(________(_______))
print(________(_______))
4. Confirm if a student's grade is greater than or
equal to 70 and less than or equal to 100.
def passing_grade (grade):
return 70 <= grade <= 100
grade1 = 80
grade2 = 65
print(passing_grade(grade1))
print(passing_grade(grade2))
Python Keywords: elif
elif
• The elif keyword is used in conditional statements (if statements), and is
short for else if.
Print "YES" if the variable i is a positive number, print "WHATEVER" if i is 0, otherwise
print "NO":
for i in range(-5, 5):
if i > 0:
print("YES")
elif i == 0:
print("WHATEVER")
else:
print("NO")
Python Keywords: except
except
• The except keyword is used in try...except blocks. It defines a block of
code to run if the try block raises an error.
• You can define different blocks for different error types, and blocks to
execute if nothing went wrong
If the statement raises an error Write one message if it is a NameError, and another if it is an TypeError:
x = "hello"
print "Something went wrong":
try: try:
x > 3 x > 3
except: except NameError:
print("You have a variable that is not defined.")
print("Something went except TypeError:
wrong") print("You are comparing values of different type")
Examples: except
try:
x > 10
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
else:
print("The 'Try' code was executed without raising any errors!")
Python Keywords: false
false
• The False keyword is a Boolean value, and result of a comparison
operation.
• The False keyword is the same as 0 (True is the same as 1).
print(5 > 6)
Examples: false
Other comparisons that returns False:
print(5 > 6)
print(4 in [1,2,3])
print("hello" is "goodbye")
print(5 == 6)
print(5 == 6 or 6 == 7)
print(5 == 6 and 6 == 7)
print(not(5 == 5))
finally
• The finally keyword is used in try...except blocks. It defines a block of
code to run when the try...except...else block is final.
• The finally block will be executed no matter if the try block raises an
error or not.
• This can be useful to close objects and clean up resources.
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")
Python Keywords: for
for
• The for keyword is used to create a for loop.
• It can be used to iterate through a sequence, like a list, tuple, etc.
from
• The from keyword is used to import only a specified section from a
module.
x = time(hour=15)
print(x)
Python Keywords: global
global
• The global keyword is used to create global variables from a no-global
scope, e.g. inside a function.
Declare a global variable inside a function, and use it outside the function:
#create a function:
def myfunction():
global x
x = "hello"
if
• The if keyword is used to create conditional statements (if statements),
and allows you to execute a block of code only if a condition is True.
import
• The import keyword is used to import modules.
import datetime
x = datetime.datetime.now()
print(x)
Python Keywords: in
in
• The in keyword has two purposes:
• The in keyword is used to check if a value is present in a sequence (list,
range, string etc.).
• The in keyword is also used to iterate through a sequence in a for loop:
Check if "banana" is present in the list: Loop through a list and print the items:
fruits = ["apple", "banana", "cherry"] fruits = ["apple", "banana", "cherry"]
is
• The is keyword is used to test if two variables refer to the same object.
• The test returns True if the two objects are the same object.
• The test returns False if they are not the same object, even if the two objects are 100% equal.
• Use the == operator to test if two variables are equal.
Check if two objects are the same object: Test two objects that are equal, but not the same
x = ["apple", "banana", "cherry"] object:
x = ["apple", "banana", "cherry"]
y = x
y = ["apple", "banana", "cherry"]
print(x is y)
print(x is y)
Python Keywords: lambda
lambda
• The lambda keyword is used to create small anonymous functions.
• A lambda function can take any number of arguments, but can only have one expression.
• The expression is evaluated, and the result is returned.
print(x(5))
print(x(5, 6, 2))
Python Keywords: none
none
• The None keyword is used to define a null value, or no value at all.
• None is not the same as 0, False, or an empty string. None is a data type of its own
(NoneType) and only None can be None.
nonlocal
• The nonlocal keyword is used to work with variables inside nested functions, where the
variable should not belong to the inner function.
• Use the keyword nonlocal to declare that the variable is not local.
Make a function inside a function, which uses the
Same example as above, but without the nonlocal
variable x as a non local variable:
keyword:
def myfunc1():
def myfunc1():
x = "John"
x = "John"
def myfunc2():
def myfunc2():
nonlocal x
x = "hello"
x = "hello"
myfunc2()
myfunc2()
return x
return x
print(myfunc1())
print(myfunc1())
Python Keywords: pass
pass
• The pass statement is used as a placeholder for future code.
• When the pass statement is executed, nothing happens, but you avoid getting an error when
empty code is not allowed.
• Empty code is not allowed in loops, function definitions, class definitions, or in if statements.
Create a placeholder for future code: Using the pass keyword in a function definition:
for x in [0, 1, 2]: def myfunction():
pass 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.
if x < 0:
raise Exception("Sorry, no numbers below zero")
return
• The return keyword is to exit a function and return a value.
Exit a function and return the sum: Statements after the return line will not be
def myfunction(): executed:
return 3+3 def myfunction():
return 3+3
print(myfunction()) print("Hello, World!")
print(myfunction())
Python Keywords: true
true
• The True keyword is a Boolean value, and result of a comparison operation.
• The True keyword is the same as 1 (False is the same as 0).
print(2 in [1,2,3])
print(5 is 5)
print(5 == 5)
print(5 == 5 or 6 == 7)
print(5 == 5 and 7 == 7)
print(not(5 == 7))
try
• The try keyword is used in try...except blocks. It defines a block of code test if it contains any
errors.
• You can define different blocks for different error types, and blocks to execute if nothing
went wrong
Try a block of code, and decide what to to if it Raise an error and stop the program
raises an error: when there is an error in the try block:
try: try:
x > 3 x > 3
except: except:
print("Something went wrong") Exception("Something went wrong")
Python Keywords: while
while
• The while keyword is used to create a while loop.
• A while loop will continue until the statement is false.
while x < 9:
print(x)
x = x + 1
Python Keywords: while
while
• The while keyword is used to create a while loop.
• A while loop will continue until the statement is false.
while x < 9:
print(x)
x = x + 1
Python Keywords: yield
yield
• The yield keyword is used to return a list of values from a function.
• Unlike the return keyword which stops further execution of the function, the yield keyword
continues to the end of the function.
• When you call a function with yield keyword(s), the return value will be a list of values, one
for each yield.
Return three values from a function:
def myFunc():
yield "Hello"
yield 51
yield "Good Bye"
x = myFunc()
for z in x:
print(z)
End
Thank you!!!
ITEP 206
Laboratory 2
Create a simple program using the following python
keywords.