Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
L6 - Loops.pptx
1. Python Data Types,
Keywords
Elo A. Ogardo, MSCS
Course Lecturer
Portions of this page are reproduced from work created and shared by Google and used according to terms described in
the Creative Commons 3.0 Attribution License.
Lesson 5
1
2. Python Data Types
The variable a holds integer value five and we did not define its type. Python interpreter will automatically interpret
variables a as an integer type.
Python enables us to check the type of the variable used in the program. Python provides us the type() function,
which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking its type.
2
3. Standard data types
A variable can hold different types of values. For example, a person's name must be stored as a string whereas its id
must be stored as an integer.
Python provides various standard data types that define the storage method on each of them. The data types
defined in Python are given below.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
3
4. Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python Numbers data-type.
Python provides the type() function to know the data-type of the variable. Similarly, the isinstance() function is used
to check an object belongs to a particular class.
Python creates Number objects when a number is assigned to a variable.
4
5. Python supports three types of numeric data.
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has no restriction on the
length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate upto 15 decimal
points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary
parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc.
5
6. Sequence Type
The string can be defined as the sequence of characters represented in the quotation marks. In Python, we can use
single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in functions and operators to perform
operations in the string.
In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+" python"
returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python Python'.
6
8. List
Python Lists are similar to arrays in C. However, the list can contain data of
different types. The items stored in the list are separated with a comma (,)
and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The
concatenation operator (+) and repetition operator (*) works with the list
in the same way as they were working with the strings.
8
9. Tupple
A tuple is similar to the list in many ways. Like lists, tuples also contain the
collection of the items of different data types. The items of the tuple are
separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value
of the items of a tuple.
9
10. Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an
associative array or a hash table where each key stores a specific value.
Key can hold any primitive data type, whereas value is an arbitrary Python
object.
The items in the dictionary are separated with the comma (,) and
enclosed in the curly braces {}.
10
11. Boolean
Boolean type provides two built-in values, True and False. These values
are used to determine the given statement true or false. It denotes by the
class bool. True can be represented by any non-zero value or 'T' whereas
false can be represented by the 0 or 'F'.
11
12. Set
Python Set is the unordered collection of the data type. It is iterable,
mutable(can modify after creation), and has unique elements. In set, the
order of the elements is undefined; it may return the changed sequence
of the element. The set is created by using a built-in function set(), or a
sequence of elements is passed in the curly braces and separated by the
comma. It can contain various types of values.
12
13. Python Keywords
Python keywords are unique words reserved with defined meanings and functions that we can only apply for
those functions. You'll never need to import any keyword into your program because they're permanently present.
Python's built-in methods and classes are not the same as the keywords. Built-in methods and classes are
constantly present; however, they are not as limited in their application as keywords.
Assigning a particular meaning to Python keywords means you can't use them for other purposes in our code.
You'll get a message of SyntaxError if you attempt to do the same. If you attempt to assign anything to a built-in
method or type, you will not receive a SyntaxError message; however, it is still not a smart idea.
13
14. In distinct versions of Python, the preceding keywords might be changed. Some extras may be introduced, while
others may be deleted. By writing the following statement into the coding window, you can anytime retrieve the
collection of keywords in the version you are working on.
By calling help(), you can retrieve a list of currently offered keywords:
14
15. In distinct versions of Python, the preceding keywords might be changed. Some extras may be introduced, while
others may be deleted. By writing the following statement into the coding window, you can anytime retrieve the
collection of keywords in the version you are working on.
By calling help(), you can retrieve a list of currently offered keywords:
15
16. In distinct versions of Python, the preceding keywords might be changed. Some extras may be introduced, while
others may be deleted. By writing the following statement into the coding window, you can anytime retrieve the
collection of keywords in the version you are working on.
By calling help(), you can retrieve a list of currently offered keywords:
16
17. How to Identify Python Keywords
Python's keyword collection has evolved as new versions were introduced. The await and async keywords, for
instance, were not introduced till Python 3.7. Also, in Python 2.7, the words print and exec constituted keywords;
however, in Python 3+, they were changed into built-in methods and are no longer part of the set of keywords. In
the paragraphs below, you'll discover numerous methods for determining whether a particular word in Python is a
keyword or not.
Write Code on a Syntax Highlighting IDE
There are plenty of excellent Python IDEs available. They'll all highlight keywords to set them apart from the rest
of the terms in the code. This facility will assist you in immediately identifying Python keywords during coding so
that you do not misuse them.
Verify Keywords with Script in a REPL
There are several ways to detect acceptable Python keywords plus know further regarding them in the Python
REPL.
Look for a SyntaxError
Lastly, if you receive a SyntaxError when attempting to allocate to it, name a method with it, or do anything else
with that, and it isn't permitted, it's probably a keyword. This one is somewhat more difficult to see, but it is still a
technique for Python to tell you if you're misusing a keyword.
17
18. Python Keywords and Their Usage
The following sections categorize Python keywords under the headings based on their frequency of use. The first
category, for instance, includes all keywords utilized as values, whereas the next group includes keywords
employed as operators. These classifications will aid in understanding how keywords are employed and will assist
you in arranging the huge collection of Python keywords.
A few terms mentioned in the segment following may be unfamiliar to you. They're explained here, and you must
understand what they mean before moving on:
The Boolean assessment of a variable is referred to as truthfulness. A value's truthfulness reveals if the value of
the variable is true or false.
In the Boolean paradigm, truth refers to any variable that evaluates to true. Pass an item as an input to bool() to
see if it is true. If True is returned, the value of the item is true. Strings and lists which are not empty, non-zero
numbers, and many other objects are illustrations of true values.
False refers to any item in a Boolean expression that returns false. Pass an item as an input to bool() to see if it is
false. If False is returned, the value of the item is false. Examples of false values are " ", 0, { }, and [ ].
18
19. Value Keywords: True, False, None
These keywords are typed in lowercase in conventional computer languages (true and false); however, they are
typed in uppercase in Python every time. In Python script, the True Python keyword represents the Boolean true
state. False is a keyword equivalent to True, except it has the negative Boolean state of false.
True and False are those keywords that can be allocated to variables or parameters and are compared directly.
19
20. The None Keyword
None is a Python keyword that means "nothing." None is known as nil, null, or undefined in different computer
languages.
If a no_return_function returns nothing, it will simply return a None value. None is delivered by functions that do
not meet a return expression in the program flow. Consider the following scenario:
20
22. The and keyword
The Python keyword and determines whether both the left-hand side and right-hand side operands and are true
or false. The outcome will be True if both components are true. If one is false, the outcome will also be False:
22
23. The or keyword
The or keyword in Python is utilized to check if, at minimum, 1 of the inputs is true. If the first argument is true,
the or operation yields it; otherwise, the second argument is returned:
23
24. The not keyword
The not keyword in Python is utilized to acquire a variable's contrary Boolean value:
The not keyword is employed to switch the Boolean interpretation or outcome in conditional sentences or other
Boolean equations. Not, unlike and, and or, determines the specific Boolean state, True or False, afterward returns
the inverse.
24
25. The in keyword
The in keyword of Python is a robust confinement checker, also known as a membership operator. If you provide it
an element to seek and a container or series to seek into, it will give True or False, depending on if that given
element was located in the given container:
25
26. The is keyword
In Python, it's used to check the identification of objects. The == operation is used to determine whether two
arguments are identical. It also determines whether two arguments relate to the unique object.
When the objects are the same, it gives True; otherwise, it gives False.
26
27. Iteration Keywords: for, while, break, continue
The for Keyword
The for loop is by far the most popular loop in Python. It's built by blending two Python keywords. They are for and in, as
previously explained.
The while Keyword
Python's while loop employs the term while and functions similarly to other computer languages' while loops. The block
after the while phrase will be repeated repeatedly until the condition following the while keyword is false.
The break Keyword
If you want to quickly break out of a loop, employ the break keyword. We can use this keyword in both for and while
loops.
The continue Keyword
You can use the continue Python keyword if you wish to jump to the subsequent loop iteration. The continue keyword, as
in many other computer languages, enables you to quit performing the present loop iteration and go on to the
subsequent one.
27
28. Exception Handling Keywords
try: This keyword is designed to handle exceptions and is used in conjunction with the keyword except to handle
problems in the program. When there is some kind of error, the program inside the "try" block is verified, but the
code in that block is not executed.
except: As previously stated, this operates in conjunction with "try" to handle exceptions.
finally: Whatever the outcome of the "try" section, the "finally" box is implemented every time.
raise: The raise keyword could be used to specifically raise an exception.
assert: This method is used to help in troubleshooting. Often used to ensure that code is correct. Nothing occurs if
an expression is interpreted as true; however, if it is false, "AssertionError" is raised. An output with the error,
followed by a comma, can also be printed.
28