0% found this document useful (0 votes)
8 views37 pages

2 Basic

Uploaded by

tolgaairmakk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views37 pages

2 Basic

Uploaded by

tolgaairmakk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

BUS 601 Python for Analytics

Lecture 2 Basic Python Programming


Intro to Python for Computer Science and Data Science, Chapter 2

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

• Fixed values such as numbers, letters, and strings, are called


“constants” because their value does not change
• Numeric constants are as you expect
• String constants use single quotes (') or double quotes (")

BUS 601
Variables identify data
Variable
names

year cityname

2023 “New Paltz"


venuspic
Data
values

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)

“New Paltz" "yes" strings


(character sequences)

pictures

There are many types of data.

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 )

• Integer cannot have commas or decimal points


– 1,405,972 vs 1405972
– 1405.0 vs 1405

BUS 601
Variables vary!

• The contents of variables can change; the name


remains the same.

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 (//)

• Dividing by zero with / or // is not allowed and results in an


exception.

• Exceptions produce tracebacks.


• The line that begins with ----> shows the code that caused the
exception.
• The error message at the bottom of the traceback shows the
exception that occurred, followed by a colon (:) and an error
message with more information about the exception.

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.

* / multiplication and division


+ - addition and subtraction

Other operators may be new to you:


% The modulo operator: 5 % 2 = 1
The result is called reminder.

BUS 601
Integer/float Division
• “/” is defined as division. The result is always decimal.

• “//” is defined as division with quotient only. Therefore, if either


operand is a float, the result is promoted to a float.

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")

• Operations on strings include concatenation, using the + sign in a


different way:

"am" + "azing" = "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"

"34" + 51 does not make sense (and is a runtime error)

BUS 601
Function print
• The built-in print function displays its argument(s) as a
line of text
• Single vs. Double-Quoted Strings

• Printing a Comma-Separated List of Items


– Displays each argument separated from the next by a space.

• Printing the Value of an Expression

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.

• In this case, \ is not the escape character because


another character does not follow it.

BUS 601
Getting data from the user
• Built-in input function requests and obtains user input.

• Function input always returns a string

– 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.

Meaningful comments will be required in all submitted programs. They


will initially consist of a preamble with the course/section, name of the
assignment, etc., and later include ad hoc explanations of code as needed.

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.

1. Understand the requirements. Ask the "client" questions if the


requirements are unclear.

BUS 601
Program development example - 2

2. Sketch out the algorithm in pseudocode. You can do this directly


in code developing environment using comments.

BUS 601
Program development example - 3

3. Turn the pseudocode into Python code, testing as you go.

BUS 601

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy