Variables and Expressions

Narrated by Horst

draw_tree(225, 35)
draw_tree(420, 45)
draw_house(720, 60)
draw_snow_person(300, 20)
  • How to use variables (this chapter)

  • How to write expressions (this chapter)

  • How to create our own functions (the next two chapters)

How to Use Variables

Variable and Function Names

Good Variable Names

  • temperature_in_celsius

  • tree_position_1

  • tree_position_2

  • car_speed

  • number_of_children

  • simpson

Bad Names, that still work:

  • temperatueInCelsius - Uses capital letters. Keep it lower case and use underscores.

  • x - Too short, and not descriptive.

  • Smith - Starts with a capital letter.

Names that don't work:

  • tree position - Can’t use spaces

  • 4runner - Can’t start with a number

Constants

  • Variables that don't change are constants

  • They should be in all upper-case

  • PI = 3.14159

  • SCREEN_WIDTH = 800

How to Create Expressions

Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
// Integer division
(always rounds down)
% Modulus
(division remainder)

Using Operators in Expressions

What's Different?

  • Juxtaposition doesn't work - It doesn't multiply
  • The '=' isn't an algebraic equality - It is an assignment

Juxtaposition Doesn't Work

Assignment Operators

Operator Description
= Assignment
+= Increment
-= Decrement
*= Multiply
/= Divide

Increasing a Variable

Increment/Decrement Operators

Using Expressions In Function Calls

Order of Operations

average = 90 + 86 + 71 + 100 + 98 / 5
average = (90 + 86 + 71 + 100 + 98) / 5

Printing Variables

Review

7 Variables and Expressions

By Paul Craven

7 Variables and Expressions

  • 160
Loading comments...

More from Paul Craven