CSE 101 Lecture Notes - Lecture 4: Equals Sign, Concatenation, Newline
When we want to give a value to a variable, we write an assignment statement
•
An assignment statement consists of a variable name, the equals sign, and a value or expression
•
Number = 3 ("number is 3" or "number becomes 3")
○
Total = 3.85 + 12.9
○
First_name = 'Susan'
○
Examples:
•
These examples show three different data types: an integer, a real number, and a string
•
Total = 5 + 8 + 3
.… other code here ….
○
Total = 17 + 6
.… etc. .…
○
After assigning a value to a variable, you can change the value of the variable with another
assignment statement:
•
Next_year = this_year + 1
○
Total_bill = subtotal + tax + tip
○
Variables can also appear on the right-hand side (RHS) of an assignment statement:
•
Assignment Statements
Suppose we wanted to compute the area of a square countertop with one corner cut off
•
Assume that the triangular cut-out begins halfway along each edge
•
If we needed to perform the computation only once, say for a 100 cm-long countertop, we might
write an expression like this: area = 100**2 - 50*50/2
•
It's just a formula of sorts with no explanation of what the numbers mean
○
The code only works for countertops exactly 100 cm long. What if we had countertops of
other sizes?
○
Note that this code has a few issues with it:
•
# area = area of square - area of triangle
○
# area of triangle is 1/2 base*height
○
area = 100**2 - 50*50/2
○
Let's address the first issue: lack of clarity
•
Comments are notes that the programmer writes to explain what the program does
○
Comments do not affect the input or output of the program or anything about how it runs
○
The lines beginning with the # symbol are called comments
•
side = 100
○
square = side**2
○
triangle = (side/2)**2 / 2
○
area = square –triangle
○
Now let’s address the other issue: lack of generality
•
To compute the area for a countertop of a different size, all we need to change is the first line:
side = 100
•
This is an example of self-documenting code
○
This code is also more readable; comments aren’t needed
•
The spacing in between variables, numbers and operators is optional, but is included here to make
the formulas easier to read
•
Example: Area Calculation
To improve this code even further, let’s make it interactive so that the user can provide the value
•
Aside: Input Statements
Unit 2 - Computer Programming Fundamentals
Sunday, June 17, 2018
10:48 PM
CSE 101 Page 1