Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

1 Python Keywords

The document provides an overview of Python keywords, explaining their reserved nature and usage in programming. It covers various categories of keywords including logical, iteration, conditional, structure, and return keywords, along with examples of their implementation in code. Additionally, it highlights the importance of keywords like 'import', 'from', 'def', 'class', and 'lambda' in Python programming.

Uploaded by

adrianjudebl
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

1 Python Keywords

The document provides an overview of Python keywords, explaining their reserved nature and usage in programming. It covers various categories of keywords including logical, iteration, conditional, structure, and return keywords, along with examples of their implementation in code. Additionally, it highlights the importance of keywords like 'import', 'from', 'def', 'class', and 'lambda' in Python programming.

Uploaded by

adrianjudebl
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

LEARNING ACTIVITIES

Students will learn the different Python keywords and its


usage.
Python Keywords

▪ Keywords in Python are


reserved words that can not
be used as a variable name,
function name, or any other
identifier.
List of Keywords in Python
Getting the List of all Python keywords

We can also get all the keyword names using the below
code.

import keyword
# printing all keywords at once using "kwlist()"
print("The list of keywords is : ")
print(keyword.kwlist)
Output:
The list of keywords are:

['False', 'None', 'True', 'and', 'as',


'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']
Let’s discuss each keyword in detail
with the help of good examples.

▪ True, False, None Keyword in Python


▪ True: This keyword is used to represent a boolean true. If a
statement is true, “True” is printed.
▪ False: This keyword is used to represent a boolean false. If a
statement is false, “False” is printed.
▪ None: This is a special constant used to denote a null value
or a void. It’s important to remember, 0, any empty
container(e.g. empty list) does not compute to None.
▪ It is an object of its datatype – NoneType. It is not possible to
create multiple None objects and can assign them to
variables.
True, False, and None Use in Python

▪ False is 0, and True is 1.


▪ True + True + True is 3.
▪ True + False + False is 1.
▪ None isn’t equal to 0 or an empty list
([]).
print(False == 0) Output:
True
print(True == 1)
True
3
1
print(True + True + True)
False
print(True + False + False
False)

print(None == 0)
print(None == [])
The truth table for “and” is
depicted below.

3 and 0 return 0
3 and 10 return 10
10 or 20 or 30 or 10 or 70
returns 10
The expression x and y first
evaluates x; if x is false, its value
is returned; otherwise, y is
evaluated and the resulting value
is returned.

The expression x or y first


evaluates x; if x is true, its value
is returned; otherwise, y is
evaluated and the resulting value
The truth table for “or” is depicted
below.

3 or 0 returns 3
3 or 10 returns 3
0 or 0 or 3 or 10 or 0 returns 3

not: This logical operator inverts the


truth value. The truth table for “not” is
depicted below.
in: This keyword is used to check if a
container contains a value. This
keyword is also used to loop through
the container.
is: This keyword is used to test object
identity, i.e to check if both the
objects take the same memory
The provided code demonstrates
various Python operations:

▪ Logical Operations:
'or' returns ‘True' when at least one operand is ‘True'.
'and' returns ‘True' only when both operands are ‘True'.
'not' negates the operand.
▪ Python “in” Keyword:
It checks if ‘s’ is in the string ‘geeksforgeeks’ and prints accordingly.
It loops through the string’s characters.
▪ Python “is” Keyword:
▪ It checks if two empty strings (‘ ‘) are identical (returns ‘True').
▪ It checks if two empty dictionaries ({}) are identical (returns ‘False').
print(True or False)
Output:
print(False and True)
True
print(not True) False
if 's' in 'geeksforgeeks’: False
s is part of geeksforgeeks
print("s is part of geeksforgeeks")
geeksforgeeks
else: True
print("s is not part of geeksforgeeks") False

for i in 'geeksforgeeks’:
print(i, end=" ")
print("\r")

print(' ' is ' ')


print({} is {})
Iteration Keywords – for, while, break, continue in Python

▪ for: This keyword is used to control flow and for looping.


▪ while: Has a similar working like “for”, used to control
flow and for looping.
▪ break: “break” is used to control the flow of the loop.
The statement is used to break out of the loop and
passes the control to the statement following
immediately after loop.
▪ continue: “continue” is also used to control the flow of
code. The keyword skips the current iteration of the loop
but does not end the loop.
The code includes a for loop and a while loop:

For Loop: Iterates from 0 to 9, printing numbers. It


breaks when 6 is encountered.
While Loop: Initializes i to 0 and prints numbers from 0
to 9. It skips printing when i is 6 and continues to the next
iteration.
#forloop
for i in range(10):
print(i, end=" ")
if i == 6:
break
print()

#whileloop
i=0
while i < 10:
if i == 6:
i += 1
continue
else:
Output

0123456
012345789
Conditional keywords in Python- if,
else, elif

▪ if : It is a control statement for decision


making. Truth expression forces control to
go in “if” statement block.
▪ else : It is a control statement for
decision making. False expression forces
control to go in “else” statement block.
▪ elif : It is a control statement for decision
making. It is short for “else if“
if, else, and elif keyword use in Python

▪ The code checks the value of the variable i:

If ‘i' is 10, it prints “i is 10”.


If ‘i' is 20, it prints “i is 20”.
If ‘i' is neither 10 nor 20, it prints “i is not present.” In this
case, it will print “i is 20” because the value of i is 20.
CODE

i = 20
Output
if (i == 10): i is 20
print("i is 10")
elif (i == 20):
print("i is 20")
else:
print("i is not
present")
Structure Keywords in Python : def,
class, with, as, pass, lambda

Python def
def keyword is used to declare user defined functions.

def keyword in Python


The code defines a function named fun using the def
keyword. When the function is called using fun(), it prints
“Inside Function.”
This code demonstrates the use of the def keyword to
define and call a function in Python.
CODE

def fun():
Output
print("Inside Inside Function
Function")
fun()
class in Python

class keyword is used to declare user defined classes.

Class Keyword in Python


This code defines a Python class named Dog with two
class attributes, attr1 and attr2, and a method fun that
prints these attributes. It creates an object Rodger from
the Dog class, accesses the class attributes, and calls the
method. When executed, it prints the values of attr1 and
`attr2, and the method displays these values, resulting in
the output shown.
CODE

class Dog:
Output
attr1 = "mammal" mammal
attr2 = "dog" I'm a mammal
def fun(self): I'm a dog
print("I'm a", self.attr1)
print("I'm a", self.attr2)

Rodger = Dog()
print(Rodger.attr1)
Rodger.fun()
With in Python

▪ with keyword is used to wrap the execution of block of


code within methods defined by context manager.
▪ This keyword is not used much in day to day programming.
With Keyword in Python
This code demonstrates how to use the with statement to
open a file named 'file_path' in write mode ('w'). It writes the
text 'hello world !' to the file and automatically handles the
opening and closing of the file. The with statement is used
for better resource management and ensures that the file is
properly closed after the block is executed.
CODE

# using with statement


with open('file_path', 'w') as file:
file.write('hello world !')
as in Python

▪ as keyword is used to create the alias for the module


imported. i.e giving a new name to the imported
module. E.g import math as mymath.

▪ as Keyword In Python
▪ This code uses the Python math module, which has
been imported with the alias gfg. It calculates and prints
the factorial of 5. The math.factorial() function is used
to calculate the factorial of a number, and in this case,
it calculates the factorial of 5, which is 120.
CODE

import math as gfg


Output
120

print(gfg.factorial(5
))
pass in Python

▪ pass is the null statement in python. Nothing happens


when this is encountered. This is used to prevent
indentation errors and used as a placeholder.

▪ Pass Keyword in Python


▪ The code contains a for loop that iterates 10 times with
a placeholder statement ‘pass', indicating no specific
action is taken within the loop.
CODE

n = 10
for i in range(n):

# pass can be used as placeholder


# when code is to added later
pass
Lambda in Python

▪ Lambda keyword is used to make inline returning


functions with no statements allowed internally.

▪ Lambda Keyword in Python


▪ The code defines a lambda function g that takes an
argument x and returns x cubed. It then calls this
lambda function with the argument 7 and prints the
result. In this case, it calculates and prints the cube of
7, which is 343.
CODE

# Lambda keyword
g = lambda x: x*x*x

print(g(7))

OUTPUT:
343
Return Keywords in Python- Return, Yield

▪ return : This keyword is used to


return from the function.
▪ yield : This keyword is used like
return statement but is used to
return a generator.
▪ The ‘return' keyword is used to return a final result
from a function, and it exits the function immediately.
▪ In contrast, the ‘yield' keyword is used to create a
generator, and it allows the function to yield multiple
values without exiting.
▪ When ‘return' is used, it returns a single value and ends
the function, while ‘yield' returns multiple values one at
a time and keeps the function’s state.
Import, From in Python

▪ import : This statement is used to include


a particular module into current program.

▪ from : Generally used with import, from is


used to import particular functionality
from the module imported.
Import, From Keyword use in Python

▪ The ‘import' keyword is used to import


modules or specific functions/classes from
modules, making them accessible in your code.
▪ The ‘from' keyword is used with ‘import' to
specify which specific functions or classes you
want to import from a module.
▪ In your example, both approaches import the
‘factorial' function from the ‘math' module,
allowing you to use it directly in your code.
CODE

# import keyword
Output
from math import factorial 3628800
import math 3628800

print(math.factorial(10))

# from keyword
print(factorial(10))

You might also like