2 Basic
2 Basic
By Dr. Qi Li
BUS 601
Objectives
• Write simple Python statements and scripts.
• Create variables to store data for later use.
• Become familiar with built-in data types.
• Use built-in function print to display text.
• Use arithmetic operators and comparison operators, and understand their
precedence.
• Use single-, double- and triple-quoted strings.
• Use built-in function input to prompt the user to enter data at the keyboard
and get that data for use in the program.
• Convert text to integer values with built-in function int.
• Use comparison operators and the if statement to decide whether to execute a
statement or group of statements.
• Learn about objects and Python’s dynamic typing.
• Use built-in function type to get an object’s type.
BUS 601
Programming
• Let machine knows what you want them to do
– commands!
– In sequence?
• Write simple Python statements and scripts,
• One statement per line, except for if and while statements
• Create variables to store data for later use.
• Define variables
• Do “math”, including calculations, logic, and others
• Do “functions”
• Do decision
• Do “repeat”
BUS 601
Literals and variables
BUS 601
Variables identify data
Variable
names
year cityname
BUS 601
Variables in Programming
• Refer to “things” in memory
• Locate “things” in memory
– names to memory locations and refer to them using
identifiers (= names) rather than numeric addresses.
PriceOfShoes
BUS 601 6
Assignment Statement
• Preceding snippet is a statement.
• It specifies a task to perform.
• Preceding statement creates x and uses the assignment
symbol (=) to give x a value.
y=3
x=7
total = x+y
– assignment symbol (=) is not an operator
print (total)
– the value on the RIGHT HAND SIDE.
– the variable on the LEFT to that value.
BUS 601
Assignment statements
Terminology:
m = 5 • 2 and 5 are integer literals
n = m + 2 • m and n are integer variables
n = 2 * m + n + 5
• m and n are assigned the values of
the expressions on the RIGHT
HAND SIDE
a = a + 1
NOT an equation or equality
checking!
BUS 601
Python Style
• The Style Guide for Python Code helps you write code that conforms
to Python’s coding conventions.
https://peps.python.org/pep-0008/
• Recommends inserting one space on each side of the assignment
symbol = and binary operators like + to make programs more readable.
• Variable Names
– A variable name is an identifier.
– May consist of letters, digits and underscores (_) but may not begin with a digit.
– Python is Case sensitive, myPicture vs mypicture
– Start with a letter
– No space between characters: my name -- X
– Not reserved words (command names)
• such as print, if, while
– Meaningful
BUS 601 9
Data types
• Each value in Python has a type that indicates the kind of data
the value represents.
integers
2023 -14 (whole numbers)
pictures
BUS 601
Types
• You can view a value’s type, with the type built-in
function.
• A function performs a task when you call it by writing
its name, followed by parentheses, ().
• The parentheses contain the function’s argument—the
data that the type function needs to perform its task.
BUS 601
The integer data type
• Integers are whole numbers, positive or negative.
• Integer literals may be used directly in a program, e.g.:
print( 45 )
BUS 601
Variables vary!
def main():
amount = 1000 amount
100
1000
10
45
x = 2
amount = 2*x x 2
amount = amount + 1
amount = 2*amount MEMORY
amount = amount*amount amount and x are names here,
that label the white boxes, which
print amount are memory locations/spaces
BUS 601 13
Arithmetic
• All operators and their precedence
Arithmetic
Python operation Python expression
operator
Addition + f+7
Subtraction – p-c
Multiplication * b*m
Exponentiation ** x ** y
True division / x/y
Floor division // x // y
Remainder
% r%s
(modulo)
BUS 601
Example
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2
10 % 3 = 1
abs(-10)=10
BUS 601
True Division (/) vs. Floor Division (//)
BUS 601
Floats
• Numbers that are not integers are needed in many
applications:
– Such as 0.07 or 3.141
– Called real numbers in math
– Called floating point numbers, or just floats in computer
science
• Operations: +, -, *, /
– Try 5/2 and 5/2.0
• 2 and 2.0 are not same
BUS 601 17
Arithmetic operators
• Arithmetic operators in Python follow the precedence
rules you learned in algebra, e.g., multiplication and
division have higher precedence than addition and
subtraction. Note that * is used for multiplication.
BUS 601
Integer/float Division
• “/” is defined as division. The result is always decimal.
BUS 601
Arithmetic expressions
• Arithmetic operators combine with variables and literals to make
arithmetic expressions.
• E.g. 5*(x-1)/(y+1)
• Parentheses are important:
• 2*x+9 vs. 2 * (x + 9)
• *, /, and % first, + and – last; for a different order, use
parentheses:
• x=5
• print (2*x+9) # first line of output is 19
• print (2*(x+9)) # second line of output is 28
BUS 601 20
Arithmetic expressions
• Arithmetic expressions often appear:
• In the right hand side of assignment statements:
– z = (x+3)*(y-2)-10
• In statements that print out values:
– print((x+3)*(y-2)-10 )
• Note: variables, x and y, need to be defined first!
• An arithmetic expression must have a definite value.
• in the above examples, x and y must already have values for
the expression to make sense.
• It doesn’t make sense to have an arithmetic expression
on the left hand side of an assignment statement:
– x+1 = 50 (Python doesn’t know how to solve
equations!) BUS 601 21
Arithmetic expressions
10 + 8 = 18
10 - 8 = 3
all-integer
math 10 * 6 = 80
1R2
10 / 8 = 1 8 10
10 % 8 = 2 8
2
10./ 8 = 1.25
floats 10 / 8.= 1.25
10.0/ 8.0 = 1.25
BUS 601
Straight-Line Form
• Algebraic expressions must be typed in straight-
line form using Python’s operators.
• Parentheses group Python expressions, as in
algebraic expressions.
BUS 601
Operator Precedence Rules
• Generally the same as those in algebra
• Complete list of operators and their precedence
• Python can use redundant parentheses to group
subexpressions to make an expression clearer.
• Operand Types
– If both operands are integers, the result is an integer—except
for the true-division (/) operator, which always yields a
floating-point number.
– If both operands are floating-point numbers, the result is a
floating-point number.
– Mixed-type expressions produce floating-point results.
BUS 601
The string data type
• Strings are sequences of characters.
• Like integers, string literals may be used directly in a program,
e.g.:
print("amazing")
BUS 601
Strings vs. Integers: Beware!
• We say that the + sign is overloaded, meaning it has a different
usage depending on the context:
– Used for adding integers
– Used for joining (concatenating) strings
28 is an integer
"28" is a string
34 + 51 is 85
"34" + "51" is "3451"
BUS 601
Function print
• The built-in print function displays its argument(s) as a
line of text
• Single vs. Double-Quoted Strings
BUS 601
Printing Many Lines of Text
• A backslash (\) in a string is the escape character.
• The backslash and the character immediately following it form
an escape sequence.
• \n represents the newline character escape sequence, which tells
print to move the output cursor to the next line.
BUS 601
Other Escape Sequences
Escape
Description
sequence
Insert a newline character in a string. When the
\n string is displayed, for each newline, move the
screen cursor to the beginning of the next line.
Insert a horizontal tab. When the string is
\t displayed, for each tab, move the screen cursor to
the next tab stop.
\\ Insert a backslash character in a string.
\" Insert a double quote character in a string.
\' Insert a single quote character in a string.
BUS 601
Ignoring a Line Break in a Long String
• Can split a long string (or a long statement) over
several lines by using the \ continuation
character as the last character on a line to
ignore the line break.
BUS 601
Getting data from the user
• Built-in input function requests and obtains user input.
– string concatenation.
BUS 601
built-in int function
• If you need an integer, convert the string to an
integer using the built-in int function.
BUS 601
Data type: Boolean
• Boolean data type is a form of data with only two possible values
(usually "true" and "false")
• A condition is a Boolean expression with the value True or False
Algebraic
Python operator Sample condition Meaning
operator
> > x>y x is greater than y
< < x<y x is less than y
≥ >= x >= y x is greater than or equal to y
≤ <= x <= y x is less than or equal to y
= == x == y x is equal to y
≠ != x != y x is not equal to y
• It's a syntax error when any of the operators ==, !=, >= and <=
contains spaces between its pair of symbols.
BUS 601
Comments
• Programmers insert comments into code to help
human readers understand their programs.
# Create and show a rectangular pink window.
pic= makeEmptyPicture( 300,200, pink )
show( pic )
Comments start with a #
and continue to the end
of the line.
BUS 601
Program development example - 1
Write a program that asks the user for the width and height
of a window. The program then pops up a yellow window
with those dimensions.
BUS 601
Program development example - 2
BUS 601
Program development example - 3
BUS 601