New 09 - Python Programming Introduction - 000
New 09 - Python Programming Introduction - 000
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
◼ 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)
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.
Literals
Why Use Named Constants
1) Make your program easier to read and understand
# NO
currentPopulation = 1000000
populationChange = (0.1758 – 0.1257) * currentPopulation
INCH_CENTIMETER_RATIO = 2.54
height = height * INCH_CENTIMETER_RATIO
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.
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
Negative number
= 1000 1101
Storing Real Numbers In The Form Of Floating
Point Sign Mantissa Exponent
‘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:
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
%s String
%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
Output:
Welcome to our Course
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
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)
hw=“hello world”
hw.title()
hw.upper()
hw.isdigit()
hw.islower()
More on String Methods
hw.upper()
hw = hw.upper()
Constant Description
e 2.7182818...
pi 3.1415926...
◼ var[‘lat’] = 40.2054
Now = time.time()
Code Execution Time
Example:
import time
startTime = time.time()
endTime = time.time()
totalTime = endTime - startTime