Variables, Expressions and Statements

Values and Types

A value is one of the basic things a program works with, like a letter or a number.

"Hello World", and 2 are values with different types:

We can check their types using type() function in Python.


In [1]:
type("Hello World!")


Out[1]:
str

In [2]:
type(2)


Out[2]:
int

Another type of value is called floating-point numbers such as: 3.2, we name these types: float


In [3]:
type(3.2)


Out[3]:
float

But if we put quotations around integer or float numbers it will become string:


In [4]:
type("3.2")


Out[4]:
str

In [5]:
type("13")


Out[5]:
str

Variables

One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value.

Assignment Statement (=) assigns values to the variables, (value holders), let's see some examples of variable creation:


In [6]:
message = 'And now for something completely different'  # variable named message stores string
n = 17 # variable named n stores value 17
pi = 3.1415926535897932 # variable named pi stores 3.14...

In [7]:
type(message)


Out[7]:
str

In [8]:
type(n)


Out[8]:
int

In [9]:
type(pi)


Out[9]:
float

Variable names and keywords

Programmers generally choose names for their variables that are meaningful—they document what the variable is used for.

Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter.

There is also a way that we have to name our variables:

  • variable name cannot start with numbers:
  • variable name cannot have illegal characters:
  • variable name cannot be the keywords specific to the Python language:
# The illegal usages, which won't work
76trombones = 'big parade'
more@ = 1000000
class = 'Advanced Theoretical Zymurgy'

Keywords in Python 3: (Don't use them when you are naming variables:)

and     del      from     not     while
as      elif     global   or      with
assert  else     if       pass    yield
break   except   import   print   nonlocal
class   in       raise    is
continue         finally  return
def     for      lambda   try 

Operators and Operands

Operators are special symbols that represent computations like addition and multiplication. The values the operator is applied to are called operands.

The operators +, -, *, / and ** perform addition, subtraction, multiplication, division and exponentiation, as in the following examples:


In [13]:
32+45 # The result is integer


Out[13]:
77

In [14]:
32 + 45.0 # The result is float, because of the operands is float


Out[14]:
77.0

In [15]:
24 - 56


Out[15]:
-32

In [16]:
5 ** 2


Out[16]:
25

In [17]:
(5+9)*(15-7)


Out[17]:
112

In [22]:
90 / 56 # In Python 3 The result is always float.


Out[22]:
1.6071428571428572

In [23]:
90 // 56 # Floor division, rounds the number down to make it integer"


Out[23]:
1

Expressions and Statements

An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions (assuming that the variable x has been assigned a value):

17 
x 
17 + x

A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of statement: print and assignment.

Technically an expression is also a statement, but it is probably simpler to think of them as different things. The important difference is that an expression has a value; a statement does not.

Interactive mode and Scripting mode

Python is interpreted language, meaning that you don't have to compile each time you need to run your code. This feature also give possibility to a interactive development environment. The Jupyter notebook and Ipython is amazing environments to do interactive development.

if you are using Python as a calculator, you might type:


In [24]:
miles = 26.2
miles * 1.61


Out[24]:
42.182

But if you type the same code into a script and run it, you get no output at all. In script mode an expression, all by itself, has no visible effect. Python actually evaluates the expression, but it doesn’t display the value unless you tell it to:

miles = 26.2
print(miles * 1.61)

This behavior can be confusing at first.

A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute.

print 1
x = 2
print x

produces the output:

1
2

The assignment statement produces no output.

Try yourself!

Type the following statements in the Python interpreter to see what they do:

5
x = 5
x + 1

Now put the same statements into a script and run it. What is the output? Modify the script by transforming each expression into a print statement and then run it again.

String Operations

In general, you can’t perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:

'2'-'1' 
'eggs'/'easy' 
'third'*'a charm'

The + operator works with strings, but it might not do what you expect: it performs concatenation, which means joining the strings by linking them end-to-end. For example:


In [26]:
first = 'throat'
second = 'warbler'
print(first + " " + second)


throat warbler

The * operator also works on strings; it performs repetition. For example,


In [27]:
"spam" * 3


Out[27]:
'spamspamspam'

Comments

As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.

For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they start with the # symbol:


In [30]:
# compute the percentage of the hour that has elapsed
percentage = (24 * 100) / 60

In [31]:
percentage = (24 * 100) / 60 # percentage of an hour

Everything from the # to the end of the line is ignored—it has no effect on the program.

Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is much more useful to explain why.

Exercises

Exercise 1:

Assume that we execute the following assignment statements:

width = 17
height = 12.0
delimiter = '.'

For each of the following expressions, write the value of the expression and the type (of the value of the expression).

                1. width/2
                2. width/2.0
                3. height/3
                4. 1 + 2 * 5
                5. delimiter * 5

Use the Python interpreter to check your answers.


In [ ]:

Exercise 2: Practice using the Python interpreter as a calculator:

  1. The volume of a sphere with radius r is $\frac{4}{3}\pi r^3$. What is the volume of a sphere with radius 5? (Hint: 392.7 is wrong!)
  2. Suppose the cover price of a book is 24.95 dolar, but bookstores get a 40% discount. Shipping costs 3 dolar for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?
  3. If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?

In [ ]: