Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3,...

41
Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 https://go.illinois.edu/cs105sp20

Transcript of Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3,...

Page 1: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Variables and Expressions

Craig Zilles (Computer Science)

February 3, 2020

https://go.illinois.edu/cs105sp20

Page 2: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Today1. Objects, literals2. Types and representation• Integers• Strings, Unicode, and Escaping• Reals, floating point

3. Identifiers, assignment, immutability4. Expressions and Operator Precedence• Division, Floor division, and modulo operator

5. Modules and Importing6. Excel: relative and absolute references• Moving formulas between cells

2

Page 3: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

You are in good company (muddy pts.)

• "I find it difficult to memorize all the different functions and commands and how to write them correctly. "• "Will we have to know the encoded values of each

character in order to code?"• "I think having to remember the Unicode and escape

sequences was pretty difficult and confusing"• "The mass amounts of vocabulary was very confusing

and should be gone over."

3

Page 4: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

The Python interpreter is your friend!

Use it to play around with the language

4

Page 5: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

All data in Python is stored in an object

• Every object has:• A type• A value

• Literals are textual descriptions, read by Python to make objects

• “hi there”

• 17

• -203.5974

5

Page 6: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

We’ve now met three types:

• Integers: whole numbers of arbitrary precision• Strings: e.g., our string literals like “Hello CS 105!”• Floating point numbers: approximations of real

numbers

• Types are important, because it specifies how to store data• Computers represent everything as a finite number

of 1’s and 0’s• The type says how to interpret the 1’s and 0’s

6

Page 7: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

How ints are stored

• Integers are usually used for counting things

7

int 1 000110101

int 2 000101011 110101001

Type Numberof chunks

Chunks(Store the number in binary)

Small number

Large number

Page 8: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

How strings are stored

8

String 6 001000011 001010011

TypeNumber ofcharacters

Characters(Stored using Unicode encoding)

000100000 000110001 000110000 000110101‘CS 105’

C S 1 0 5

Page 9: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Which of the following are considered ‘whitespace’?

A) SpacesB) TabsC) NewlinesD) Spaces and TabsE) Spaces, Tabs, and Newlines

9

Page 10: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Which of the following are considered ‘whitespace’?

A) SpacesB) TabsC) NewlinesD) Spaces and TabsE) Spaces, Tabs, and Newlines

10

In computer programming, whitespace is any character or series of characters that represent horizontal or vertical space in typography. When rendered, a whitespace character does not correspond to a visible mark, but typically does occupy an area on a page. --Wikipedia

Page 11: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

How strings are stored

• Unicode can encode pretty much any character• Including many things that aren’t on your computer keyboard• How do we tell Python we want to use those characters?

• Can specify the Unicode codepoint: e.g., 0394 is the Greek delta (Δ)• How do we distinguish a codepoint from a number?

11

String 6 001000011 001010011

TypeNumber ofcharacters

Characters(Stored using Unicode encoding)

000100000 000110001 000110000 000110101‘CS 105’

C S 1 0 5

Page 12: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Escaping• Treat slash (\) as a special character• \ means that the following characters should be

interpreted differently• \u followed by a number is a code point• '\u0394’ is the Greek delta (Δ)

• \” and \’ are quote characters that don’t end a string• \t encodes a tab• \n encodes a new line• \\ encodes a slash

12

Page 13: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

How many visible characters are printed?

• print('\\n\t\\t')

A) 1B) 2C) 3D) 4E) 5

13

Page 14: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Numbers beyond integers

• Integers only represent whole numbers• Sometimes you need to represent numbers between

integers• Often when measuring things (lengths, speeds, etc.)

• Real numbers:• Mathematically, there are an infinite number of numbers between

each integer• On computers, we can’t represent an infinite number of possible

numbers with a finite number of bits• Can only approximate real numbers

14

Page 15: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

How floats are stored• Like scientific notation: 6.02 x 1023

• mantissa x 10exponent

• Fixed-size mantissa: finite precision• Normally hidden by python• format(0.1, '.17f')

• Fixed-size exponent: limited range• 100.1 ** 200

15

Float -3.76341 +22

Type Mantissa Exponent

Can specify in scientific notation

Page 16: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Which isn’t a valid Python literal

A) 1.000001B) 1E-7C) 1,097D) -3.00E) '\'\'\'' # Consists only of single quotes and slashes

16

Page 17: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

We’ve now met three types:

• Integers: whole numbers of arbitrary precision• Strings: e.g., our string literals like “Hello CS 105!”• Floating point numbers: approximations of real numbers

• You can ask a value what its type is using: type(expression)• You can convert between them with str() and int()

and float()

17

Page 18: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Variables• Useful to give names to objects

• Names in Python have to follow certain rules:• Begin with letter or underscore• Contains only letters, numbers, or underscores• Avoid reserved words (also known as key words)

• Python recommended style: Snake Case• lower_case_words_separated_by_underscores

18

Page 19: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Which are legal Python names?

1. ______2. 12monkeys3. m0nk3yM4n

A. 1 and 2B. 1 and 3C. 2 onlyD. 2 and 3E. 1, 2, and 3

19

Page 20: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Assignment

• Variable names are bound to values with assignmentstatements

• Structure: variable_name = expression

• What happens:1. expression evaluated to compute a value2. variable_name is bound to the value

20

Page 21: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

What is the value of y after this code executes

x = 2y = x + 3x = 5

A) 2B) 3C) 5D) 8E) 10

21

Page 22: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

What is the value of y after this code executes

x = 7y = xx = x + 2

A) 2B) 5C) 7D) 9E) None of the above

22

Page 23: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Immutability

• strings, ints, and floats are all immutable• Once an object has been created, it can’t be

changed• New ones must be made instead

• Multiple variables can be bound to the same object• If object is immutable, updating one variable

doesn’t affect the others

23

Page 24: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Garbage Collection

• If an object isn’t bound to any variable, the Python interpreter gets rid of it.• Frees up space for new objects

24

Page 25: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Logistics

• Lab next week: Excel + Spatial skills development • Bring plug-in headphones if you can

• Homework on PrairieLearn: • More points available than you need• Report any problems with “Report an error in this question”• Code reading exercises using natural language processing

• Exam 0 next week: Sign up on https://cbtf.engr.illinois.edu/sched/• Meant to get comfortable in the CBTF• Drawn almost completely from pre-lecture 1 & 2 and HW 1 & 2

25

Page 26: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Logistics, cont.

• Need help?• Sending me email is probably not the answer• Questions about course content?

• Search Piazza (first) or ask question on Piazza (second)• Office Hours: Wohlers Hall Computer Lab• CS 105 Tutoring (TBA soon)• Gies Tutoring

• Questions about course policies, grading -> Piazza• Questions/documents about DRES, excused absences?

[email protected] (our course administrator)

26

Page 27: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

27

Page 28: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Expressions• Any Python code fragment that produces a value• Can include:• Literals• Variables• Operators• Functions

• Right-hand side of assignment can be arbitrary expression

28

Page 29: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Order of Operations• Parentheses () highest

precedence• Exponentiation **• (unary) Positive, negative +x, -x• Multiplication, Division, Modulo *, /, %• Addition, Subtraction +, - lowest

precedence

Left-to-right within a precedence level

29

Page 30: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

What is the value of this expression?

-3 ** 2

A) -9B) -8C) 8D) 9E) None of the above

31

Page 31: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Good Style with Expressions• Put a single space between every variable, operator, and

number• this_is + a_readable – expression

• Break up complicated expressions

• vs

• Be generous with parentheses32

total = num_machines * (cost_per_machine * (1 + tax_rate) + shipping rate)

machine_cost = num_machines * cost_per_machinemachine_cost_with_tax = machine_cost * (1 + tax_rate)shipping_cost = num_machines * shipping_ratetotal = machine_cost_with_tax + shipping_cost

Page 32: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

What would happen…• if I type the following into a brand new Python

interpreter: x + y

A) nothingB) SyntaxErrorC) NameErrorD) ValueErrorE) TypeError

33

Page 33: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Expression types

• Result type generally depends on types of values in expression:• an_integer + another_integer -> an integer• a_float + another_float -> a float• a_string + another_string -> a string

• If you mix ints and floats, ints will be promoted to floats:• 3.0 + 7 -> 3.0 + 7.0 -> 10.0

• Generally can’t mix strings with either ints or floats

34

Page 34: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

What (if any) kind of error is in this program?

value = input("Input your fave number!\n")

print("Your new fave number is", value + 1)

A) No errorB) SyntaxErrorC) NameErrorD) ValueErrorE) TypeError

35

Page 35: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Division, Floor Division, and Modulo• Division operator (/) gives best approximation to true result• always results in a float

• Floor Division (//) rounds down to closest whole number• Uses normal type rules for result

• Modulo operator (%) performs a division and returns a remainder• Uses normal type rules for result

• For any numbers x and y, the following equality holds:y = (y // x) * x + (y % x).

36

Page 36: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Floor division and modulo example

dollars = product_cost_in_pennies // 100cents = product_cost_in_pennies % 100

37

Page 37: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Modules• Very few real computer programs are written from

scratch• Too inefficient

• Frequently use previously written code• Libraries• Python functions you previously wrote

• We call both of these modules

38

Page 38: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Importing modules• import command puts module in your program’s

namespace

• Access functions and variables in module with qualified name:

math.sin(7.3)

• Access documentation with help() and tab completion

39

Page 39: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Excel: Relative and Absolute References

• Every cell in Excel has a name: e.g., C7 (column C, row 7)

• When written in an Excel expression, this is a relative reference• If moved/copied to another cell, it will change proportionally

• If you move = 2 * C7 down two rows, it will become = 2 * C9

• You can make absolute references by adding $ before row and/or column• $C$7 moved anywhere stays $C$7• $C7 moved two down and two to the right becomes $C9• C$7 moved two down and two to the right becomes E$7

40

Page 40: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Next Week's reading• We've introduced 3 types: int, float, string• These are individual things

• It is useful to be able to group things together• Python has special types for these collections• Each has its own use• Lists are ordered sequences of things (e.g., play list)• Dictionaries map one thing to another• E.g., a gradebook maps a person to their grade

• Sets are un-ordered collections (w/o duplicates)• E.g., a guest list

• Intended to be first exposure; we'll see them again

41

Page 41: Variables and Expressions...Variables and Expressions Craig Zilles (Computer Science) February 3, 2020 Today 1.Objects, literals 2.Types and representation •Integers •Strings,

Sequences• Strings and Lists are both kinds of sequences

• You can reach into both and pull things out: "indexing"• Python starts counting at zero

• Lists are mutable! You can change them• There are functions for doing that

42