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

New 09 - Python Programming Introduction - 000

This document discusses variables, constants, and arithmetic operations in Python. It defines variables as locations in memory that can store information temporarily, and constants as similar locations that should not change. It provides naming conventions for variables and constants, and explains that constants should be in all uppercase. The document also demonstrates how to output the contents of variables and constants, perform arithmetic operations, and mix strings with variable outputs.

Uploaded by

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

New 09 - Python Programming Introduction - 000

This document discusses variables, constants, and arithmetic operations in Python. It defines variables as locations in memory that can store information temporarily, and constants as similar locations that should not change. It provides naming conventions for variables and constants, and explains that constants should be in all uppercase. The document also demonstrates how to output the contents of variables and constants, perform arithmetic operations, and mix strings with variable outputs.

Uploaded by

Rabab Elkomy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Python

Programming
LECTURE 9
Variables and Constants
Variables
• Set aside a location in memory.
• Used to store information (temporary).
–This location can store one ‘piece’ of information.
• Putting another piece of information at an existing location overwrites previous
information.
–At most the information will be accessible as long as the program runs.
• Some of the types of information which can be stored in variables
include: integer (whole), floating point (fractional), strings (text)
Format:
<name of variable> = <Information to be stored in the variable>
Examples:
–Integer (e.g., num1 = 10)
–Floating point (e.g., num2 = 10.0)
–Strings (e.g., name = “Aly")
Variable Naming Conventions
• Python requirements:
–Rules built into the Python language for writing a program.
–Somewhat analogous to the grammar of a ‘human’ language.
–If the rules are violated then the typical outcome is the program cannot be translated
(nor run).
• A language such as Python may allow for a partial execution.
• Style requirements:
–Approaches for producing a well written program.
(The real life analogy is that something written in a human language may follow the
grammar but still be poorly written).
–If they are not followed then the program can still be translated but there may be
other problems.
Variable Naming Conventions
1. Style requirement: The name should be meaningful.
2. Style and Python requirement: Names must start with a letter (Python
requirement) and should not begin with an underscore (style requirement).
3. Style requirement: Names are case sensitive but avoid distinguishing
variable names only by case.
4. Style requirement: Variable names should generally be all lower case (see
next point for the exception).
5. Style requirement: For variable names composed of multiple words
separate each word by capitalizing the first letter of each word (save for the
first word) or by using an underscore. (Either approach is acceptable but
don’t mix and match.)
6. Python requirement: Can not be a keyword.
Key Words In Python
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
Variables
◼ Variable: A named piece of memory that can store a value.
◼ Usage:
◼ Compute an expression's result,
◼ Store that result into a variable,
◼ Use that variable later in the program.
◼ Assignment statement: Stores a value into a variable.
◼ Syntax:
name = value
◼ Examples: x = 5
gpa = 3.14

x 5 gpa 3.14

◼ A variable that has been given a value can be used in expressions.


x + 4 is 9
◼ Exercise: Evaluate the quadratic equation for a given a, b, and c.
Variables
◼ No need to declare
◼ Need to assign (initialize)
◼ use of uninitialized variable raises exception

◼ Not typed
if friendly: greeting = "hello world"
else: greeting = 12**2
Print(greeting)

◼ Everything is a "variable":
◼ Even functions, classes, modules
Changing an Integer

a=1 a 1

a
b=a 1
b new int object created
by add operator (1+1)

a 2
a = a+1 old reference deleted
by assignment (a=...)
b 1
Named Constants
•They are similar to variables: a memory location that’s been given a name.
•Unlike variables their contents shouldn’t change.
•The naming conventions for choosing variable names generally apply to
constants but the name of constants should be all UPPER CASE.
•You can separate multiple words with an underscore.
•Example PI = 3.14
•They are capitalized so the reader of the program can distinguish them from
variables.
–For some programming languages the translator will enforce the unchanging nature of
the constant.
–For languages such as Python it is up to the programmer to recognize a constant for
what it is and not to change it.
Terminology: Named Constants Vs. Literals
• Named constant: given an explicit name.

TAX_RATE = 0.2
afterTax = income – (income * TAX_RATE)

• Literal/Unnamed constant/Magic number: not given a name, the value


that you see is literally the value that you have.

afterTax = 100000 – (100000 * 0.2)


Terminology: Named Constants Vs. Literals
• Named constant: given an explicit name.

TAX_RATE = 0.2
afterTax = income – (income * TAX_RATE)

Named constants
• Literal/Unnamed constant/Magic number: not given a name, the value
that you see is literally the value that you have.

afterTax = 100000 – (100000 * 0.2)

Literals
Why Use Named Constants
1) Make your program easier to read and understand
# NO
currentPopulation = 1000000
populationChange = (0.1758 – 0.1257) * currentPopulation

#YES In this case the literals are


BIRTH_RATE = 17.58/100 Magic Numbers (avoid
whenever possible!)
MORTALITY_RATE = 0.1257
currentPopulation = 1000000
populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation
Why Use Named Constants
2) Make the program easier to maintain
–If the constant is referred to several times throughout the program,
changing the value of the constant once will change it throughout the
program.
–Using named constants is regarded as “good” style when writing a
computer program.
Purpose Of Named Constants
BIRTH_RATE = 0.1758
MORTALITY_RATE = 0.1257
populationChange = 0
currentPopulation = 1000000
populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation
if (populationChange > 0):
print("Increase“)
print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, " Population change:", populationChange)
elif (populationChange < 0):
print("Decrease“)
print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange)
else:
print("No change“)
print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange)
Purpose Of Named Constants
BIRTH_RATE = 0.8 One change in the initialization of the constant
MORTALITY_RATE = 0.1257
changes every reference to that constant
populationChange = 0
currentPopulation = 1000000
populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation
if (populationChange > 0):
print("Increase“)
print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, " Population change:", populationChange)
elif (populationChange < 0):
print("Decrease“)
print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange)
else:
print("No change“)
print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange)
Purpose Of Named Constants
BIRTH_RATE = 0.1758 One change in the initialization of the constant
MORTALITY_RATE = 0.01 changes every reference to that constant
populationChange = 0
currentPopulation = 1000000
populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation
if (populationChange > 0):
print("Increase“)
print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, " Population change:", populationChange)
elif (populationChange < 0):
print("Decrease“)
print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange)
else:
print("No change“)
print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange)
When To Use A Named Constant?
• (Rule of thumb): If you can assign a descriptive useful, self-
explanatory name to a constant then you probably should.
• Example 1 (easy to provide self explanatory name)

INCH_CENTIMETER_RATIO = 2.54
height = height * INCH_CENTIMETER_RATIO

• Example 2 (providing self explanatory name is difficult)


Calories used = (10 x weight) + (6.25 x height) – [(5 * age) – 161]
In python:
CaloriesUsed = (10 * weight) + (6.25 * height) – ((5 * age) – 161)
Output: Displaying The Contents Of
Variables And Constants
Format:
print (<variable name>)
print (<constant name>)

Example:
aNum = 10
A_CONSTANT = 10
print (aNum)
print (A_CONSTANT)
Mixed Output
• Mixed output: getting string output and the contents of variables (or
constants) to appear together.
• Format:
print (“string”, <variable or constant>, “string”, <variable or constant> , etc…)

• Examples:
myInteger = 10
myReal = 10.5
myString = "hello"

print ("MyInteger:" , myInteger) The comma signals to the translator that the
print ("MyReal:" , myReal) string and the contents of the variable
print ("MyString:" , myString) should appear on the same line.
Output: Problems
• Python automatically adds an additional newline after
the “print”

year = 1997
print ("year=") Label and variable contents on different
print (year) lines
or
year = 1997
print ("year=", year) Label and variable contents on the same
line
Arithmetic Operations
Expressions
◼ Expression: A data value or set of operations to compute a
value.
Examples: 1 + 4 * 3
42
◼ Arithmetic operators used
◼ + - * / addition, subtraction/negation, multiplication, division
◼ // floor division
◼ % modulo, a.k.a. remainder
◼ ** exponentiation
◼ Precedence: Order in which operations are computed.
* / // % ** have a higher precedence than + -
1 + 3 * 4 is 13
◼ Parentheses can be used to force a certain order of evaluation.

(1 + 3) * 4 is 16
Arithmetic Operators
Operator Description Example
= Assignment num = 7
+ Addition num = 2 + 2
- Subtraction num = 6 - 4
* Multiplication num = 5 * 4
/ Division num = 25 / 5
// Floor Division num = 25 // 3
% Modulo num = 8 % 3
** Exponent num = 9 ** 2
Order Of Operation (Precedence)
• First level of precedence: top to bottom
• Second level of precedence
– If there are multiple operations that are on the same level then precedence goes
from left to right.

Brackets (inner before


( )
outer)
** Exponent
Multiplication,
*, /, //, % division, floor division,
modulo
+, - Addition, subtraction
Order Of Operation and Style
• Even for languages where there are clear rules of precedence
(e.g., Java, Python) it is regarded as good style to explicitly
bracket your operations.
x = (a * b) + (c / d)

• It not only makes it easier to read complex formulae but also a


good habit for languages where precedence is not always clear
(e.g., C++, C).
Variables: Storing Information
• On the computer all information is stored in binary (2 states)
–Example: RAM/memory stores information in a series of on-off
combinations
Bit On = 1 Off = 0
OR

Byte
8 bits
1100 1011
Variables: Storing Information
• Information must be converted into binary to be stored on a
computer.
User enters Can be stored in the computer as
13 0000 1101
Storing Integer Information
• 1 bit is used to represent the sign, the rest is used to store the size of the number
– Sign bit: 1/on = negative, 0/off = positive
• Format:

Positive number

Digits representing the size of the number

Negative number

• From previous example


Positive or
Negative number Value of number, in this case = 13

= 1000 1101
Storing Real Numbers In The Form Of Floating
Point Sign Mantissa Exponent

1 bit Several bits Several bits

–Mantissa: digits of the number being stored


–Exponent: the direction and the number of places the decimal point must
move (‘float’) when storing the real number as a floating point value.
• Examples with 5 digits used to represent the mantissa:
–e.g. 123.45 is represented as 12345 * 10-2
–e.g. 0.12 is represented as 12000 * 10-5
–e.g. 123456 is represented as 12345 * 101
• Remember: Using floating point numbers may result in a loss of accuracy
(the float is an approximation of the real value to be stored).
Storing Character Information
• Typically characters are encoded using ASCII
• Each character is mapped to a numeric value
– E.g., ‘A’ = 65, ‘B’ = 66, ‘a’ = 97, ‘2’ = 50
• These numeric values are stored in the computer using binary

Character ASCII numeric code Binary code

‘A’ 65 01000001
‘B’ 66 01000010
‘a’ 97 01100001

‘2’ 50 00110010
Storing Information: Bottom Line
Why is it important to know that different types of information
are stored differently?
Certain operations only apply to certain types of information and
can produce errors or unexpected results when applied to other
types of information.

• Example • Correct Example Format


num = input("Enter a number") num = int(input("Enter a number"))
numHalved = num / 2 numHalved = num / 2
Converting Between Different Types Of
Information
• Example motivation: you may want numerical information to
be stored as a string (for the formatting capabilities) but also
you want that same information in numerical form (in order to
perform calculations).
• Some of the conversion mechanisms available in Python:
Format: Examples:
int (<value to convert>) x = 10.9
float (<value to convert>) y = int (x)
str (<value to convert>) print (x, y)
Converting Between Different Types Of
Information
Example1: Example2:
x = '100' aNum = 123
y = '-10.5' aString = str(aNum)
print (x + y) aNum = aNum + aNum
print (int(x) + float (y)) aString = aString + aString
print (aNum)
print (aString)
Output: Output:
100-10.5 246
89.5 123123
Converting Between Different Types Of
Information: Getting Numeric Input
• Because the ‘input’ function only returns string information it
must be converted to the appropriate type as needed.
Example
# Problem!
HUMAN_CAT_AGE_RATIO = 7
age = input("What is your age in years: ")
• ‘Age’ refers to a string not a number.
catAge = age * HUMAN_CAT_AGE_RATIO
print ("Age in cat years: ", catAge) • The ‘*’ is not mathematical multiplication
# Problem solved!
HUMAN_CAT_AGE_RATIO = 7
age = int(input("What is your age in years: "))
• ‘Age’ converted to an integer.
catAge = age * HUMAN_CAT_AGE_RATIO
• The ‘*’ now multiplies a numeric value.
print ("Age in cat years: ", catAge)
print … Again
Let us say you want to display a hexadecimal number
("0xfde") as an integer

Example:
hexNumber = "0xfde"
print("Hex to int", int(hexNumber, 0))

Output:
Hex to int 4062
print … Again
Let us say you want to display a string number “34” as an
integer
Example:
StringNumber="34"
print("String to int", int(stringNumber, 0))
Output:
String to int 34
Determining the Type of Information Stored
in a Variable
• It can be done by using the pre-created python function
‘type’
Example: Output:
myInteger = 10 <class 'int'>
myString = "foo!"
<class ‘float'>
print (type(myInteger))
print (type(10.5)) <class ‘str'>
print (type(myString))
Data Size in Python
◼ Python has several data types
◼ Their respective sizes in memory are much larger than most other
languages
Example:
import sys Output:
print("size of variable = ", sys.getsizeof(5)) size of variable = 28
print("size of variable = ", sys.getsizeof(10.5)) size of variable = 24
print("size of variable = ", sys.getsizeof(“5”)) size of variable = 50
print("size of variable = ", sys.getsizeof(“12345”)) size of variable = 54
Output: Formatting
Output can be formatted in Python through the use of
placeholders.
Format:
print ("%<type of info to display/code>" %<source of the info to display>)
Example:
num = 123
Output:
num=123
st = “CS111"
course: CS111
print ("num=%d" %num) 12.500000 12
print ("course: %s" %st) 12.500000
num = 12.5
print ("%f %d" %(num, num))
print(“%f” %num)
Types Of Information That Can Be Displayed

Descriptor code Type of Information to display

%s String

%d Integer (d = decimal / base 10)

%f Floating point
Formatting Effects Using Descriptor Codes

• Format:
%<width>1.<precision>2<type of information>

1 A positive integer will add leading spaces (right align), negatives will add trailing
spaces (left align). Excluding a value will set the field width to a value large enough
to display the output
2 For floating point representations only.
Formatting Effects Using Descriptor Codes

• Format:
%<width>1.<precision>2<type of information>
• Examples: Output:
num = 12.55
num=12.550000
print (“num=%f" %num)
num= 12.6
print (“num=%5.1f" %num)
num=12.550000
print (“num=%.1f" %num)
num=12
num = 12
hi hihithere
st = "num="
print ("%s%d" %(st,num))
print ("%5s%5s%1s" %("hi","hihi","there"))
print … Again
Let us say you want to display any
float number with 2 decimal places
For example 73.4 as 73.40 and 288.5400 as 288.54.
Example:
number= 88.2345
print('{0:.2f}'.format(number))
Output:
88.23
Triple Quoted Output
•Used to format text output
•The way in which the text is typed into the
program is exactly the way in which the
text will appear onscreen.
Example:
print('''...and then they said "It's a trap"''')
Output:
...and then they said "It's a trap"
Triple Quoted Output
Example:
print('Welcome to our Course')
print()
print('Everybody start studying python')
print('Keep studying as long as you dare.’)
print('Stop working just before you think the time will end.’)

Output:
Welcome to our Course

Everybody start studying python


Keep studying as long as you dare.
Stop working just before you think the time will end.
Triple Quoted Output
Example:
print('''Welcome to our Course

Everybody start studying python


Keep studying as long as you dare.
Stop working just before you think the time will end. ''')

Output:
Welcome to our Course

Everybody start studying python


Keep studying as long as you dare.
Stop working just before you think the time will end.
Escape Codes
• The back-slash character enclosed within quotes won’t be
displayed but instead indicates that a formatting (escape) code
will follow the slash:
Escape sequence Description
\a Alarm. Causes the program to beep.
Newline. Moves the cursor to beginning of the next
\n
line.
\t Tab. Moves the cursor forward one tab stop.
\' Single quote. Prints a single quote.
\" Double quote. Prints a double quote.
\\ Backslash. Prints one backslash.
Escape Codes
Example:
print ("\a*Beep!*")
print ("hi\nthere")
print ('it\'s')
print ("he\\y \"you\"")
Extra Practice
• Traces:
–Modify the examples (output using descriptor and escape codes) so
that they are still valid Python statements.
• Alternatively you can try finding some simple ones online.
–Hand trace the code (execute on paper) without running the program.
–Then run the program and compare the actual vs. expected result.
• Program writing:
–Write a program that will right-align text into 3 columns of data.
–When the program starts it will prompt the user for the maximum
width of each column
Another Screen Output Method
Example:
import sys
...
sys.stdout.write("Hello there.")
sys.stdout.write("What is your name?")

Output:
Hello there.What is your name?
Note: No new line after the screen output command!!!
More on Numbers
◼ The usual suspects
◼ 12 ==> Integer Numbers
◼ 3.14 ==> Floating Point Numbers
◼ 0xFF ==> Hexadecimal Numbers (equal to 255)
◼ 0b1111 ==> Binary Number (equal to 15)
◼ 0377 ==> Invalid
◼ (-1+2)*3/4**5 ==> 0.0029296875
◼ abs(x) ==> Functions apply to numbers
◼ 0<x<=5 ==> True if x=3
More on Numbers
◼ Assignment Operators
= += -= *= /= //= %= **=

Example:
x+=5 ==> x=x+5
x-=5 ==> x=x-5
x*=5 ==> x=x*5
x/=5 ==> x=x/5
x//=5 ==> x=x//5
x%=5 ==> x=x%5
X**=5 ==> x=x**5
More on Integer Numbers
◼ C-style shifting & masking (Bitwise Operators)
◼ 1<<16 ==> 65536 (left shift “1” 16 times)
◼ 65536>>8 ==> 256(right shift ”65536” 8 times)
◼ x&0xff ==> Bitwise ANDing of “x” with 0xFF
◼ x|1 ==> Bitwise ORing of “x” with 1
◼ ~x ==> Bitwise invert
◼ x^y ==> Bitwise XORing of “x” with “y”
More on Integer Numbers
◼ Integer division truncates :
◼ 1/2 ==> 0 in python 2.7 and below
◼ 1/2 ==> 0.5 in python 3.x
◼ 1//2 ==> 0 in python 3.x
◼ -1//2 ==> -1 in python 3.x
◼ 1./2. ==> 0.5
◼ float(1)/2 ==> 0.5

It is much safer to change the operation


to float as in the last step
Integer Division in python 2.x
◼ When we divide integers with / , the quotient is also an
integer.

3 52
4 ) 14 27 ) 1425
12 135
2 75
54
21
◼ More examples:
◼ 35 / 5 is 7
Floor Division in
◼ 84 / 10 is 8

◼ 156 / 100 is 1
python 3.x takes
place by rounding
to the lower value
Integer Remainder
◼ The % operator computes the remainder from a division of
integers in all versions of python
3 43
4 ) 14 5 ) 218
12 20
2 18
15
3

◼ More examples:
◼ 35 % 5 is 0
◼ 84 % 10 is 4

◼ 156 % 100 is 56
More on Integer Numbers
◼Long (arbitrary precision)

◼ In python 2.x and below, we use suffix “L” for


very large integers
2L**100
==> 1267650600228229401496703205376L
◼ From Python 3.x, this is replaced by simply

writing the equation


2**100
==> 1267650600228229401496703205376
More on Numbers
◼Complex Numbers

◼ “j” is recognized in python as the complex


operator
◼ Valid for integers and real numbers

◼ 1j**2 ==> (-1+0j)


◼ (5.3+3j)*(1+1j) ==> (2.3+8.3j)
More on Real numbers
◼ Python can also manipulate real numbers.
◼ Examples: 6.022 -15.9997 42.0 2.143e17

◼ The operators + - * / // % ** ( ) all work for real


numbers.
◼ The / produces an exact answer: 15.0 / 2.0 is 7.5
◼ The same rules of precedence also apply to real numbers:
Evaluate ( ) before * / % before + -
More on Real numbers
◼ When integer and real numbers are mixed, the result
is a real number
◼ Example: 1 / 2.0 is 0.5

◼ The conversion occurs on a per-operator basis in python


2.x.
◼ 7 / 3 * 1.2 + 3 / 2
◼ 2 * 1.2 + 3 / 2
◼ 2.4 + 3 / 2
◼ 2.4 + 1
◼ 3.4
More String Methods
◼ Assign a string to a
variable
◼ In this case “hw”

hw=“hello world”
hw.title()
hw.upper()
hw.isdigit()
hw.islower()
More on String Methods
hw.upper()

◼ The string held in your variable remains the same


◼ The method returns an altered string

◼ Changing the variable requires reassignment

hw = hw.upper()

hw now equals “HELLO WORLD”


String Operations
◼ "hello"+"world" "helloworld" # concatenation
◼ "hello"*3 "hellohellohello" # repetition
◼ "hello"[0] "h" # indexing
◼ "hello"[-1] "o" # (from end)
◼ "hello"[1:4] "ell" # slicing
◼ len("hello") 5 # size
◼ "hello" < "jello" True # comparison
◼ "e" in "hello" True # search
◼ "escapes: \n …….., \033 ……….., \if ……….."
◼ 'single quotes' “double quotes” """triple quotes""“
◼ r"raw strings“ ‘raw strings’
Pre-written Python Functions
• Python comes with many functions that are a built in part of the
language e.g., ‘print’, ‘input’
(If a program needs to perform a common task e.g., finding the
absolute value of a number, then you should first check if the
function has already been implemented).
• For a list of all prewritten Python functions.
http://docs.python.org/library/functions.html
• Note: some assignments may have specific instructions on which
functions you are allowed to use.
Read the requirements specific to each assignment.
Math Commands
◼ Python has useful commands for performing calculations.
Command name Description
abs(value) absolute value
ceil(value) rounds up
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
Math Commands
◼ Python has useful constants for performing calculations.

Constant Description
e 2.7182818...
pi 3.1415926...

◼ To use many of these commands and/or constants, you must


write the following at the top of your Python program:

from math import *


Other Python Objects
◼ Lists (mutable sets of strings)
◼ var = [] # create an empty list

◼ var = [‘one’, 2, ‘three’, ‘banana’]

◼ Tuples (immutable sets)


◼ var = (‘one’, 2, ‘three’, ‘banana’)

◼ Dictionaries (associative arrays or ‘hashes’)


◼ var = {} # create dictionary

◼ var = {‘lat’: 40.20547, ‘lon’: -74.76322}

◼ var[‘lat’] = 40.2054

◼ Each has its own set of methods

(will be studied in details later on in the course)


Code Execution Time
•To calculate the time taken to complete the
execution of the code.
•Using a time module, You can calculate the time
taken to execute your code.
Example:
import time

Now = time.time()
Code Execution Time
Example:
import time

startTime = time.time()

# write your code or functions calls here!!!

endTime = time.time()
totalTime = endTime - startTime

print("Total time required to execute code is= ",


totalTime)
Code Execution Time
Output:
Total time required to execute code is=
0.002236604690551758
Summary and Discussion

You might also like