ITEP 206 Lesson 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

ITEP 206

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

• The “and” keyword is a logical operator.


• Logical operators are used to combine conditional
statements.
• The return value will only be True if both statements
return True, otherwise it will return False.
Examples: AND

x = (5 > 3 and 5 < 10)


print(x)
Examples: AND

if 5 > 3 and 5 < 10:


print("Both statements are True")
else:
print("At least one of the statements are False")
Logical Operators (and, not, or)

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.
number = 10
if not number == 0:
print ("The number is not equal to zero.")
else:
print("The number is equal to zero.")
Logical Operators (and, not, or)

OR

• The “or” keyword is a logical operator.


• 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.
Examples: OR

x = (5 > 3 or 5 > 10)


print(x)
Examples: OR

if 5 > 3 or 5 > 10:


print("At least one of the statements are True")
else:
print("None of the statements are True")
Python Keywords: as

as

• The as keyword is used to create an alias.


• Create an alias, c, when importing the calendar module,
and now we can refer to the calendar module by using c
instead of calendar.
import calendar as c
print(c.month_name[1])
Python Keywords: assert

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

You can write a message to be written if the code


returns False, check the example below.

x = "hello"

#if condition returns False, AssertionError is raised:


assert x == "goodbye", "x should be 'hello'"
Python Keywords: break

break

• The break keyword is used to break out a for loop, or a


while loop.
Break out of a while loop:
i = 1
End the loop if i is larger than 3: while i < 9:
for i in range(9): print(i)
if i > 3: if i == 3:
break break
print(i) i += 1
Python Keywords: class

class
• The class keyword is used to create a class.
• A class is like an object constructor.

Create an object named p1, using the


Create a class named "Person": class from the example:
class Person:
name = "John" p1 = Person()
age = 36 print(p1.name)
Python Keywords: continue

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.

Create and execute a function:


def my_function():
print("Hello from 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.

Delete an object: Delete a variable: Delete the first item in a list:


class MyClass: x = "hello" x = ["apple", "banana", "cherry"]
name = "John"
del x del x[0]
del MyClass
print(x) print(x)
print(MyClass)
TRIAL
ACTIVITY
1. Check if a number is both greater than 10
and even.
def x (number):
return number > 10 and number % 2 == 0

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 to execute a statement that raises an error, but none of the


defined error types (in this case, a ZeroDivisionError):
try:
x = 1/0
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
except:
print("Something else went wrong")

Write a message if no errors were raised:


x = 1

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 the result of the


comparison "5 is larger
than 6":

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("hello" is not "hello")

print(not(5 == 5))

print(3 not in [1,2,3])


Python Keywords: finally

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.

Print each number from 1 to 8: Loop through all items in a list:


for x in range(1, 9): fruits = ["apple", "banana", "cherry"]
print(x)
for x in fruits:
print(x)
Python Keywords: from

from
• The from keyword is used to import only a specified section from a
module.

Import only the time section from the datetime


module, and print the time as if it was 15:00:
from datetime import time

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"

#execute the function:


myfunction()

#x should now be global, and accessible in the global scope.


print(x)
Python Keywords: if

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.

Print "YES" if x is larger than 6, otherwise print "NO":


Print "YES" if x larger than 3: x = 5
x = 5 if x > 6:
if x > 3: print("YES")
print("YES") else:
print("NO")
Python Keywords: import

import
• The import keyword is used to import modules.

Import the datetime module and display the


current date and time:

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"]

if "banana" in fruits: for x in fruits:


print("yes") print(x)
Python Keywords: is

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.

Create a function that adds 10 to any number you send:


x = lambda a : a + 10

print(x(5))

A lambda function with three arguments:


x = lambda a, b, c : a + b + c

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.

If you do a boolean if test, what will happen? Is None True or


False:
Assign the value None to a variable: x = None
x = None
if x:
print("Do you think None is True?")
print(x) elif x is False:
print ("Do you think None is False?")
else:
print("None is not True, or False, None is just None...")
Python Keywords: nonlocal

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

Using the pass keyword in an if statement:


Using the pass keyword in a class definition: a = 33
class Person: b = 200
pass if b > a:
pass
Python Keywords: raise

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.

Raise an error and stop the program if x is lower than 0:


x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

Raise a TypeError if x is not an integer:


x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")
Python Keywords: return

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 the result of the comparison "7 is larger than


6":
print(7 > 6)
Examples: true
Other comparisons that returns True:
print(5 < 6)

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("hello" is not "goodbye")

print(not(5 == 7))

print(4 not in [1,2,3])


Python Keywords: try

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.

Print x as long as x is less than 9:


x = 0

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.

Print x as long as x is less than 9:


x = 0

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.

You might also like