0% found this document useful (0 votes)
107 views45 pages

Lecture 3 - Variables, Datatypes and Operatiors in Python PDF

The document discusses good programming practices, variables, data types, and operators in Python. It covers topics like using consistent indentation, avoiding deeply nested code, and limiting line lengths. It also defines variables as storage locations for information, and lists the main data types as numbers, strings, lists, tuples, and dictionaries. Finally, it describes common arithmetic operators like addition, subtraction, and multiplication.

Uploaded by

malvin muthoni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
107 views45 pages

Lecture 3 - Variables, Datatypes and Operatiors in Python PDF

The document discusses good programming practices, variables, data types, and operators in Python. It covers topics like using consistent indentation, avoiding deeply nested code, and limiting line lengths. It also defines variables as storage locations for information, and lists the main data types as numbers, strings, lists, tuples, and dictionaries. Finally, it describes common arithmetic operators like addition, subtraction, and multiplication.

Uploaded by

malvin muthoni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 45

Lecture 3 – Variables, Datatypes and

Operators in Python.

BBT 4211 - BCOM – Kurui Daniel


Content

• Good programming Practices


• Programming Errors
• Variables
• Data types
• Operators

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 2


Good Programming practices
• In programming, best practices are encouraged.
• This is to enable easy understanding, maintaining and debugging
of code.
• Think of a newly appointed s/w developer in a company

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 3


Good Programming practices cont’d
• Use consistent indentation
Indentation is very important in python. It is part of its syntax. The best style, is a
consistent style. Once you start competing in large projects you’ll immediately
understand the importance of consistent code styling.

• Follow the DRY Principle


DRY stands for “Don’t Repeat Yourself.
The same piece of code should not be repeated over and over again.

• Avoid Deep Nesting


Too many levels of nesting can make code harder to read and follow.
For example:

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 4


Good Programming practices cont’d

Can be
written as

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 5


Good Programming practices cont’d

• Limit line length


Long lines are hard to read. It is a good practice to avoid writing
horizontally long lines of code.
• File and folder structure
You should avoid writing all of your code in one of 1-2 files. That won’t
break your app but it would be a nightmare to read, debug and maintain
your application later.
Keeping a clean folder structure will make the code a lot more readable
and maintainable.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 6


Good Programming practices cont’d

• Naming conventions
Use of proper naming conventions is a well known best practice. Is a very
common issue where developers use variables like X1, Y1 and forget to
replace them with meaningful ones, causing confusion and making the
code less readable.
• Keep the code simple
The code should always be simple. Complicated logic for achieving simple
tasks is something you want to avoid as the logic one programmer
implemented a requirement may not make perfect sense to another. So,
always keep the code as simple as possible.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 7


Good Programming practices cont’d

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 8


Debugging in Programming

• Debugging is the routine process of locating and removing


computer program bugs, errors or abnormalities, which is methodically
handled by software programmers via debugging tools.
• Debugging checks, detects and corrects errors or bugs to allow
proper program operation according to set specifications.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 9


Types of errors in python
• Errors in Python can be categorized into two types:
1. Compiler Errors
• These are errors that occur when you ask Python to run the application.
Before the program can be run, the source code must be compiled into the
machine code. If the conversion can not performed, Python will inform you
that your application can not be run before the error is fixed.
• The most common errors of this type are syntax errors – for example, if
you don’t end an if statement with the colon. Here is an example:

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 10


Types of errors in python cont’d
2. Runtime Errors
• There are errors that occur after the code has been compiled and the
program is running. The error of this type will cause your program to
behave unexpectedly or even crash. An example of an runtime error is the
division by zero. Consider the following example:

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 11


Types of errors in python cont’d
2. Runtime Errors

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 12


Variables
What is a variable?
• In programming, variables are storage locations that are used to store
information that can later be referenced and manipulated.
• You can consider a variable as a sort of a container where you store an
information that can later be accessed with the variable name.
• In Python, variables are created when they are first assigned values. Values
are assigned using the assignment operator (=). For example, to create a
variable named x and store the numeric value of 3 in it, you can use the
following command:
• x = 12
• Name = “Daniel”

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 13


Variables Cont’d
• You can now use the variable Name in your code. For example,
to print the content of the variable, you can use the following
command:
• print(Name)
• print(x)

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 14


Data types in Python

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 15


Variable Data types

What is a variable data type?


• Variables in Python can be of a different data types.
• The data type of a variable is important because it specifies the type or
kind of information that can be stored inside a variable.
• For example, to store series of characters, i.e. string information, you need
a variable of the string type. You can’t store a number in a variable
designed to store string information. You will need to create a variable of
the numerical type to store a numerical value.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 16


Variable Data types cont’d

• There are five standard data types in Python:


1. Numbers
used to store numeric values. Numbers can be stored as integers, long
integers, floating-point values, and complex numbers. For example, the
statement x = 5 will store the integer number 5 in the variable x.
2. Strings
used to store a contiguous set of characters. To define a string, you type the
characters within single or double quotes. For example,
myString = ‘This is some text’
will store that string of characters (This is some text) in the variable myString.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 17


Variable Data types cont’d
3. Lists
• Lists are similar to arrays in some other programming languages, lists in
Python are used to store a set of elements under a single variable name.
• Each element can be accesses by using its index, which is simply an
address that identifies the item’s place in the list.
• Elements of a list are defined inside the square brackets ([]) and are
separated by commas. For example:
• myNumbers = [5,3,2,1]
• This will define the list myNumbers with four elements. To access the first
element of the list (the number 5), we can specify its index in the square
brackets. Since indexes start from 0, to access the first element of the list,
we would use the following statement:
• myNumbers[0]

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 18


Variable Data types cont’d

4. Tuples
• Tuples are similar to lists, tuples in Python are used to store a set of
elements under a single variable name.
• However, unlike lists, they cannot be changed once created. You can think
of tuples as read-only lists.
• They are used to represent fixed collections of elements, like days in the
week. Elements of a tuple are defined inside the parentheses and
separated by commas. For example,
• myNumbers = (2,4,2,5)
• To access the first element, we use the myNumbers[0] statement.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 19


Variable Data types cont’d

5. Dictionaries
• Dictionaries are also known as mappings
• They are used to store a set of objects, but they store objects by key instead by
relative position.
• The elements are defined within the curly braces.
• For example, the statement
• myDict = {‘color’ : ‘blue’, ‘size’ : ‘small’}
• This will create a two word dictionary. We can access the elements of this
dictionary by specifying a key.
• To access the value associated with the key color, we would use the following
statement:
• myDict[‘color’].

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 20


Date and Time

• There are times you might need to get the current data and time
• For example if you are calculating age of something, audit purposes etc
• To get the current date and time in python, we do the following :

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 21


Operators in Python

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 22


Arithmetic Operators

• The arithmetic operators in Python are used to perform math operations,


such as addition, subtraction, multiplication, and division.
• Python also offers a number of libraries that enable you to perform more
complex math tasks.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 23


Arithmetic Operators Cont’d
• Here is a list of the arithmetic operators in Python:
• Addition (+) – adds two values together.
• Subtraction (-) – subtracts right hand operand from the left hand
operand.
• Multiplication (*) – multiplies the right operand by the left operand.
• Division (/) – divides the left operand by the right operand
• Modulus (%) – divides the left operand by the right operand and returns
the remainder. Example: 9 % 5 = 4.
• Exponent (**) – calculates the exponential value. Example: 3 ** 4 = 81.
• Floor Division (//) – performs integer division. Example: 9//2 = 4.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 24


Comparison Operators
• As the name suggests, the comparison operators in Python are
used to compare one value to another.
• The result of a comparison is a Boolean value, which can be
either True or False.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 25


Comparison Operators
• The following comparison operators exist in Python:
==
determines whether two values are equal.
Examples: 1 == 1 is True, 1 == 2 is False.

!=
determines whether two values are not equal.
Examples: 1 != 2 returns True, 1 != 1 returns False.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 26


Comparison Operators
>
determines if the value of the left operand is greater than the
value of the right operand.
Examples: 3 > 1 is True, 1 > 2 is False.

<
determines if the value of the left operand is less than the value of
the right operand.
Examples: 1 < 2 is True, 3 < 2 is False.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 27


Comparison Operators
>=
determines if the value of the left operand is greater than or equal
to the value of the right operand.
Examples: 3 >= 1 is True, 1 >= 2 is False.
<=
determines if the value of the left operand is less than or equal to
the value of the right operand.
Examples: 1 <= 3 is True, 3 <= 2 is False.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 28


Comparison Operators
>=
determines if the value of the left operand is greater than or equal
to the value of the right operand.
Examples: 3 >= 1 is True, 1 >= 2 is False.
<=
determines if the value of the left operand is less than or equal to
the value of the right operand.
Examples: 1 <= 3 is True, 3 <= 2 is False.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 29


Logical Operators

• The logical operators in Python are used to combine


the true or false values of variables (or expressions) so you can figure out
their resultant truth value.
• Three logical operators are available in Python:
AND OR NOT

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 30


Logical Operators cont’d

• AND
Returns True only if both operands are true. In any other
case, False will be returned.
• OR
Returns True when one or both of the operands are true.
• NOT
Negates the truth value of a single operand.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 31


Logical Operators cont’d

• AND
Returns True only if both operands are true. In any other
case, False will be returned.
• OR
Returns True when one or both of the operands are true.
• NOT
Negates the truth value of a single operand.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 32


AND Operator’s truth table

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 33


OR Operator’s truth table

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 34


Assignment Operators
• The assignment operators in Python are used to store data into a variable.
We’ve already used the most common assingment operator (=), but there are
many more of them:
=
Assigns the value found in the right operands to the left operand.
Example: x = 5.

+=
Adds the value found in the right operand to the value found in the left operand.
Example: x = 5, x += 3 results in x = 8.
x = x+3

-=
Subtracts the value of the right operand from the value found in the left operand.
Example: x = 5, x -= 3 results in x = 2.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 35


Assignment Operators Cont’d
*=
Multiplies the value of the right operand by the value of the left operand.
Example: x = 5, x *= 3 results in x = 15.
x = x*3

/=
Divides the value of the left operand by the value of the right operand.
Example: x = 5, x /=3 results in x = 1.667.
x = x/3

%=
Divides the value found in the left operand by the value found in the right
operand. The reminder will be placed in the left operand.
Example: x = 5, x %=3 results in x = 2.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 36


Assignment Operators Cont’d
**=
Determines the exponential value found in the left operand when raised
to the power of the value in the right operand.
Example: x = 5, x **=3 results in x = 125.

//=
Divides the value found in the left operand by the value of the right
operand. The integer result will be placed in the left operand.
Example: x = 5, x //= 3 results in x = 1.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 37


Membership operators
• The membership operators in Python are used to test whether a
value is found within a sequence.
• For example, you can use the membership operators to test for the
presence of a substring in a string. Two membership operators exist in
Python: in and not in

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 38


Membership operators cont’d
in
Evaluates to True if the value in the left operand appears in the sequence
found in the right operand.
For example, ‘Hello’ in ‘Hello world’ returns True because the
substring Hello is present in the string Hello world!.

not in
Evaluates to True if the value in the left operand doesn’t appear in the
sequence found in the right operand.
For example, ‘house’ not in ‘Hello world’ returns True because the
substring house is not present in the string Hello world!.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 39


Membership operators cont’d

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 40


Identity Operators
• The identity operators in Python are used to determine whether a value
is of a certain class or type.
• They are usually used to determine the type of data a certain variable
contains.
• For example, you can combine the identity operators with the built-
in type() function to ensure that you are working with the specific
variable type. value.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 41


Identity Operators
• Two identity operators are available in Python:

• is
Returns True if the type of the value in the right operand points to the same
type in the left operand.
For example, type(3) is int evaluates to True because 3 is indeed an integer
number.

• is not
Returns True if the type of the value in the right operand points to a
different type than the value in the left operand.
For example, type(3) is not float evaluates to True because 3 is not a
floating-point value.

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 42


Identity Operators cont’d

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 43


Lab Exercise
1. Write a program which prompts the user for a Celsius temperature,
convert the temperature to Fahrenheit, and print out the converted
temperature. ((0°C × 9/5) + 32 = 32°F)
2. Write a python program to declare a variable called ‘name’ to hold your
name. and test if it has some string you will be prompted to enter using
input
3. Write a python program to calculate your age
4. Write a program to prompt the user for hours and rate per hour to compute
gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
5. Write a python program to enter any English word, the test if it is a
doing word i.e. verb (has ing)

8 maj 2020 BBT 4211 - Comp Programming - Kurui Daniel 44


END
Any Questions?
Thank you!
BBT 4211 - Comp Programming - Kurui Daniel

You might also like