﻿ VARIABLES, EXPRESSIONS, STATEMENT, STRINGS - NTRODUCTION TO PROGRAMMING WITH PYTHON (2015) ﻿

## INTRODUCTION TO PROGRAMMING WITH PYTHON (2015)

### CHAPTER 4. VARIABLES, EXPRESSIONS, STATEMENT, STRINGS

Remember those English grammar lessons? How “each sentence” is made of a subject and an object, has nouns, pronouns, auxiliary verbs, and adjectives, and the like?

Just remember how words and auxiliary verbs were used to create sentences, and how these sentences are used to communicate more complex thoughts.

This is what we are going to do here.

Python (and most other programming languages) are made of some universal basic components. These include (in order of increasing complexity) variables, expressions, statements, and strings.

The names are self-explanatory. Let’s see them in detail.

VARIABLE

A variable is the “x” you tried to find in most of your math classes. In programming it is a data type capable of containing changeable values.

The ability to manipulate variable in a programming language is one of the most powerful features in the coding world.

Hence, we must begin by understanding “values” in Python.

VALUES AND DATA TYPES

Values are categorized according to the type of data they can handle. For example, “Hello, Programming!”, “2”, and “2.3” are all considered values in Python, except each belongs to a different category or different data type.

NOTE: Data type donates the different types of data that can be used e.g. characters, numbers, float point (decimal numbers), etc.

The numeric 2 is an integer because it contains a whole number, whereas the “Hello, Programming!” is a string because it contains a string of letters, and “2.3” is a float because it has decimal number. Your Python interpreter is able to identify and use strings as a single value enclosed within the quotation marks.

If in confusion about the type, let Python tell you the data type of your value with the type () command:

>>> type (“Hello, Programming!”)

<type ‘str’>

>>> type (13)

<type ‘int’>

Note that the strings are always contained within quotes “”. Hence, if you were to put numeric values within these quotes, they automatically become strings.

>>> type (“13”)

<type ‘str’>

Furthermore, when writing strings, avoid using commas to separate tens, hundreds, and thousands. For example, if you want to write two hundred thousand as 2, 00,000, Python would react as follows:

>>> print (2,000,000)

2 0 0

Unexpected right?

That’s because commas are interpreted by Python as separators. Hence, you see three values: 2, 0, and 0.

NOTE: The syntax for print is print (x) with ‘x’ being replaced by strings (“string”) or normal numeric value (2)

This is different from Python 2, where the syntax is simply: print x, print 2, or print “this”

Other types include float (for decimal places)

>>> type (13.1)

<type ‘float’>

>>> type (“13.1”)

<type ‘str’>

NOTE: You can use both, single (‘’) and double (“”) quotes for writing strings in Python. AND, you can use double quotes within single quotes. For example: (‘He said, “Lo and behold!” ‘)

VARIABLES

Remember how basic equations were created in math?

Question: If Sam bought two eBooks for \$3, how much will it cost to purchase 5 eBooks? We normally began with supposing “x” as the cost of 5 eBooks.

Once supposed, “x” can be used anywhere in the solution and anyone can easily figure (interpret) that “x” is referring to the “Cost of 5 eBooks” defined in the beginning.

In programming, a variable is the name that refers to a changeable value — one that can be changed and automatically updated at will.

Like math, variables have to be declared/created (supposed) and then assigned a value. In python, the value of a variable is assigned using the assignment statement:

>>> message = "I’m programming with Python!"

>>> x = 2015

>>> yr = 365.25

Notice how each type of data is assigned in a similar manner, starting with a string, an integer, and a floating point number. The most important thing is the equal sign “=” that separates the name of the variable (left hand side) from the value of the variable (right hand side). The equal sign “=” is known as the assignment operator.

The left-hand, right-hand divide is a rule. Deviation is not permitted. If you reverse the order, it becomes meaningless for the interpreter.

Hence, the following makes no sense.

>>> "I’m programming with Python!"= message

>>> 2015 = x

>>> 365.25 = yr

TYPES OF VARIABLES

Variables also have types. In the example above, themessageis a string,‘x’is an integer, and‘yr’ is a float.

You can verify the type of the variable usingtype().

>>> type(message)

<type 'str'>

>>> type(x)

<type 'int'>

>>> type(yr)

<type 'float'>

Note how the type of the variable corresponds to the type of the value it contains.

Certain naming conventions are used when naming variables. These are simply standards that are used to standardize how code is written and to keep it clean. This gains importance as your code gets longer and your variables become more descriptive.

1. Always begin with an alphabet/letter

2. Never use illegal characters (\$, &, *, etc.)

3. Never use a Python keyword

Therefore, the following will result in syntax errors:

>>> 14numbers = "What are those fourteen numbers?"

SyntaxError: invalid syntax

>>> Increase\$ = 985

SyntaxError: invalid syntax

>>> class = "Python Basics "

SyntaxError: invalid syntax

Now“class”is a Python keyword, which means it is part of its rules and structure.

Python has thirty-one such keywords:

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

Keep this table handy, and if the interpreter complains about syntax error, check your variable naming!

STATEMENTS

Like normal language, a statement is an instruction. In Python, you can execute primarily two kinds of statements: printandassignment. The former produces a value while the later does nothing.

When you write a statement, the interpreter executes it and tries to display results:

print (3)

t = 17

print (t)

The above code will produce the output:

3

17

The assignment statement used for creating a variable produces no output.

EXPRESSIONS

As in language, an expression is a complete thought, with a premise and a conclusion. In python, an expression has inputs, a defined/expected use of those inputs, and an expected way of either directly displaying an output or computing it to display an output.

Generally, meaningful expressions are a combination of variables, values, statements, and operators that forces the interpreter to evaluate it and display results:

>>> 1 + 1

2

A value and a variable itself are simple expressions in Python:

>>> 2015

2015

>>> t

17

However, these expressions simply print/display the expression. Evaluating an expression is not similar to simply printing a value.

Take the example:

>>> message = "Writing expressions?"

>>> message

"Writing expressions?"

Notice how the quotation marks are displayed in the output. However, when usingprint(), only the contents of the string are displayed:

>>> print (message)

Writing expressions?

This is because theprint () statement fetches the value of the variable (the string).

Now, an expression all by itself is a legal statement. You can write as many as you want, but unless you use certain operators and commands to communicate the purpose of the expression, NO OUTPUT will be displayed. For instance:

2015

365.25

"Python, Expressions!"

13 + 1

No output will be displayed.

This is where operators and operands come into play.

OPERATORS AND OPERANDS

A code is supposed to perform certain computations on the expressions to generate predictable outputs. Computations are performed using operators — special symbols which you may think of as short forms for different commands.

The value that the operator uses is called an operand. Here are some examples:

1+2+3

t-20

t*30+minutes

t/60

(1+2+3)* (6-2)

How the symbols have been used +, -, /, * (for multiplication) are the same way they are used in mathematics. Now, when a variable is used with operator(s) to create an expression, the interpreter fetches and computes the value assigned to that variable.

However, there is a caveat. Though addition, multiplication, subtraction, and exponentiation (represented by the double asterisk operator **) have a single use and generate an expected result, division does not.

Let’s say the following expression is used:

>>> t = 49

>>> t/60

0.8166

But what if wanted to perform an integer division where the answer is always rounded off to the closest integer value?

Let’s say:

>>> t=121

This is where “//” is used to indicate our intention

>>> t/60

>>>t//60

2.0166

2

Another way of overcoming is to assign data types to the answer (a float), but we will come to that later.

ORDER OF OPERATIONS

You can use multiple operators in a single expression; however their evaluation is depended on the rules of precedence.

Python follows the same rule as is applied for mathematical operators. Remember PEMDASto memorize the order:

·               Parentheses — Expressions in the parenthesis are always evaluated first. Hence, 3*(4-1) is  9. Parenthesis are also a great way for making it easier to read the expression such as(t*100)/60.

·               Exponentiation — (**) has the next highest precedence. Hence,3**1+1 is 4 and not 9, whereas4*1**3 is 4 and not 64.

·               Multiplication and Division — Both have the same precedence, albeit higher than addition and subtraction

·               Addition and Subtraction — Also have the same precedence, albeit lower than multiplication and division.

What if multiplication and division come in the same expression?

For example:t*100/60

Operators that have the same precedence are evaluated from their appearance from left to right. Hence, in the expressiont*100/60, multiplication happens first, followed by division.

OPERATIONS AND STRINGS

Generally, you cannot perform any mathematical operations on strings. This includes instances where the strings look like numbers, or only have numbers in them. The following example shows an illegal mathematical operation on a set of strings:

message-1 "Word"/2015 message*"Now" "2012"+3

Though mathematical operations cannot be performed algebraically (or as we are accustomed to) on strings, some operators can work with them, but in a different manner.

For example, the “+” operator when used with strings performs concatenation instead of addition. It means that the two strings (or operands) are linked end-to-end i.e. they are attached one after the other:

Subject = “Python”

Object = “ Programming Language”

Aux_Verb = “ is a”

print (Subject+ Aux_Verb + Adj +Object)

The output of this code will be programPython is a simple Programming Language. The spaces before the words in the string are part of string, and necessary to produce the grammatically correct spacing between the concatenated strings.

The multiplication operator (*) also works on strings. Its function is to perform repetitions on that string. So, for example, the operations:

‘ Why?’*3

Will produce the results ‘Why? Why? Why?’

In multiplication’s (*) case, one of the operands must be an integer while the other a string.

﻿

﻿