Variables and Expressions Craig Zilles (Computer Science) - - PowerPoint PPT Presentation

variables and expressions
SMART_READER_LITE
LIVE PREVIEW

Variables and Expressions Craig Zilles (Computer Science) - - PowerPoint PPT Presentation

Variables and Expressions Craig Zilles (Computer Science) https://go.illinois.edu/cs105sp20 February 3, 2020 To Today 1. Objects, literals 2. Types and representation Integers Strings, Unicode, and Escaping Reals, floating point


slide-1
SLIDE 1

Variables and Expressions

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

slide-2
SLIDE 2

To Today

  • 1. Objects, literals
  • 2. Types and representation
  • Integers
  • Strings, Unicode, and Escaping
  • Reals, floating point
  • 3. Identifiers, assignment, immutability
  • 4. Expressions and Operator Precedence
  • Division, Floor division, and modulo operator
  • 5. Modules and Importing
  • 6. Excel: relative and absolute references
  • Moving formulas between cells

2

slide-3
SLIDE 3

Yo You are in good company (m (muddy uddy pt 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

slide-4
SLIDE 4

The The Pytho hon n interpr preter is yo your friend!

Use it to play around with the language

4

slide-5
SLIDE 5

Al All data a in Python is stored in an an ob

  • bject
  • Every object has:
  • A type
  • A value
  • Literals are textual descriptions, read by Python to make
  • bjects
  • “hi there”
  • 17
  • -203.5974

5

slide-6
SLIDE 6

We We’ve now met three ty 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
  • f 1’s and 0’s
  • The type says how to interpret the 1’s and 0’s

6

slide-7
SLIDE 7

Ho How in ints ar are stored

  • Integers are usually used for counting things

7

int 1 000110101 int 2 000101011 110101001

Type Number

  • f chunks

Chunks (Store the number in binary)

Small number Large number

slide-8
SLIDE 8

Ho How st strings s are e stored ed

8 String 6 001000011 001010011

Type Number of characters Characters (Stored using Unicode encoding)

000100000 000110001 000110000 000110101 ‘CS 105’ C S 1 5

slide-9
SLIDE 9

Whi Which o ch of t the he f followi wing ng ar are c cons nside dered ‘ d ‘whi whitespace pace’?

A) Spaces B) Tabs C) Newlines D) Spaces and Tabs E) Spaces, Tabs, and Newlines

9

slide-10
SLIDE 10

Whi Which o ch of t the he f followi wing ng ar are c cons nside dered ‘ d ‘whi whitespace pace’?

A) Spaces B) Tabs C) Newlines D) Spaces and Tabs E) 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

slide-11
SLIDE 11

Ho How st strings s are e stored ed

  • 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

Type Number of characters Characters (Stored using Unicode encoding)

000100000 000110001 000110000 000110101 ‘CS 105’ C S 1 5

slide-12
SLIDE 12

Esc Escapi ping ng

  • 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

slide-13
SLIDE 13

Ho How man any visible char arac acters ar are printed?

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

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

13

slide-14
SLIDE 14

Nu Number ers s beyond integ eger ers

  • 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

slide-15
SLIDE 15

Ho How fl floats s are e stored ed

  • 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

slide-16
SLIDE 16

Wh Which isn’t a valid Python literal

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

16

slide-17
SLIDE 17

We We’ve now met three ty 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

slide-18
SLIDE 18

Va 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

slide-19
SLIDE 19

Wh Which are legal Pyt ython names?

  • 1. ______
  • 2. 12monkeys
  • 3. m0nk3yM4n
  • A. 1 and 2
  • B. 1 and 3
  • C. 2 only
  • D. 2 and 3
  • E. 1, 2, and 3

19

slide-20
SLIDE 20

As Assig ignment

  • Variable names are bound to values with assignment

statements

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

20

slide-21
SLIDE 21

Wh What is the value of y af after this code ex executes

x = 2 y = x + 3 x = 5

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

21

slide-22
SLIDE 22

Wh What is the value of y af after this code ex executes

x = 7 y = x x = x + 2

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

22

slide-23
SLIDE 23

Im Immutability ility

  • 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

slide-24
SLIDE 24

Ga Garba bage e Collec ection

  • If an object isn’t bound to any variable, the Python

interpreter gets rid of it.

  • Frees up space for new objects

24

slide-25
SLIDE 25

Lo Logistics cs

  • 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

slide-26
SLIDE 26

Lo Logistics, cs, c 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?
  • cs105admin@Illinois.edu

(our course administrator)

26

slide-27
SLIDE 27

27

slide-28
SLIDE 28

Expr Expressi ssions ns

  • Any Python code fragment that produces a value
  • Can include:
  • Literals
  • Variables
  • Operators
  • Functions
  • Right-hand side of assignment can be arbitrary

expression

28

slide-29
SLIDE 29

Or Order of Op 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

slide-30
SLIDE 30

Wh What is the value of this expression?

  • 3 ** 2

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

31

slide-31
SLIDE 31

Go Good d Styl yle e with h Expr Expressi essions ns

  • Put a single space between every variable, operator, and

number

  • this_is + a_readable – expression
  • Break up complicated expressions
  • vs
  • Be generous with parentheses

32

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

machine_cost = num_machines * cost_per_machine machine_cost_with_tax = machine_cost * (1 + tax_rate) shipping_cost = num_machines * shipping_rate total = machine_cost_with_tax + shipping_cost

slide-32
SLIDE 32

Wh What would happen…

  • if I type the following into a brand new Python

interpreter: x + y A) nothing B) SyntaxError C) NameError D) ValueError E) TypeError

33

slide-33
SLIDE 33

Ex Expression

  • n 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

slide-34
SLIDE 34

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

value = input("Input your fave number!\n") print("Your new fave number is", value + 1)

A) No error B) SyntaxError C) NameError D) ValueError E) TypeError

35

slide-35
SLIDE 35

Di Divisi sion, Fl Floor Di Divisi sion, 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

slide-36
SLIDE 36

Fl Floor divi visi sion an and modulo exam ample

dollars = product_cost_in_pennies // 100 cents = product_cost_in_pennies % 100

37

slide-37
SLIDE 37

Mo Modul dules

  • 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

slide-38
SLIDE 38

Im Impor

  • rtin

ting mod

  • dule

les

  • 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

slide-39
SLIDE 39

Ex Excel: Re Relative and Absolute Re 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

slide-40
SLIDE 40

Ne Next Week eek's s rea eading

  • 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

slide-41
SLIDE 41

Se Sequence ces

  • 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