CIS 1051 - Temple Rome Spring 2023¶

Intro to Problem solving and¶

Programming in Python¶

LOGO

LOGO

Variables, Expressions and Statements¶

Prof. Andrea Gallegati

( tuj81353@temple.edu )

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.

Variable Assignment¶

It creates a new variable and gives it a value, e.g.

In [2]:
message = 'And now for something completely different'
In [3]:
n = 17
In [4]:
pi = 3.141592653589793

Variable Names¶

... generally choose variables names to document what the variable is used for.

  • can be as long as you like
  • can contain both letters and numbers
  • can’t begin with a number

The underscore character (can appear), is often used in names with multiple words, e.g. your_name

It is legal to use uppercase letters, but it is conventional to use only lowercase for variables names (in python).

If you give a variable an illegal name, you get a syntax error:

In [12]:
76trombones = 'big parade' #begins with a number
  File "<ipython-input-12-58a707cabf44>", line 1
    76trombones = 'big parade' # begins with a number
              ^
SyntaxError: invalid syntax
In [11]:
counter@ = 1000000 #contains an illegal char
  File "<ipython-input-11-812170a98a40>", line 1
    counter@ = 1000000
           ^
SyntaxError: invalid syntax
In [15]:
class = 'Advanced Theoretical Zymurgy' #is a python keyword
  File "<ipython-input-15-fc6d141676f8>", line 1
    class = 'Advanced Theoretical Zymurgy' #is a python keyword
          ^
SyntaxError: invalid syntax

The interpreter uses keywords to recognize the structure of the program.

They cannot be used as variable names.

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

... usually displayed in a different color!

Expressions¶

... are a combination of values, variables, and operators.

Even a value or a variable all by theirself are considered an expression.

The following are all legal expressions:

In [16]:
42
Out[16]:
42

Typing an expression at the prompt, the interpreter evaluates it, finding the value of the expression

In [17]:
n
Out[17]:
17
In [18]:
n + 25
Out[18]:
42

Statements¶

... are units of code with an effect, like creating a variable or displaying a value.

In [21]:
n = 17 #assignment statement - gives a value to n
In [22]:
print(n) #print statement - displays the value of n
17

When you type a statement, the interpreter executes it, which means that it does whatever the statement says.

In general, statements don’t have values.

Script Mode¶

Running Python in interactive mode, means that you interact directly with the interpreter.

... a good way to get started, but not working with a few lines of code, it soon becomes clumsy!

Thus, save code in a file (aka script), then run the interpreter in script mode to execute the script.

By convention, Python scripts' names end with .py

In [25]:
%run ../scripts/example.py
17

Again, typing the above command from an actual CLI, you don't need to precede it by a %run

This notebook cells aren't CLIs in the strictest sense of the word.

Since Python provides both modes, it turns useful to test bits of code in interactive mode before putting them into a script.

But there are differences between the two!

... using Python (interactively) as a calculator

In [27]:
miles = 26.2
miles * 1.61
Out[27]:
42.182

It turns out that a marathon is about 42 kilometers.

But running the same code into a script, you get no output at all.

In script mode an expression, all by itself, has no visible effect.

Python always evaluates the expression, but without displaying the value unless told:

In [29]:
miles = 26.2
print(miles * 1.61)
42.182

A script usually contains a sequence of statements:

  • on different lines
  • on the same line, separated by ;

and the results appear one at a time as the statements execute.

Order of Operations¶

With more than one operator, the order of evaluation depends on the order of operations.

For mathematical operators, Python follows mathematical convention (PEMDAS).

  • Parentheses

highest precedence and can be used to force an expression to evaluate in the order you want.

You can also use parentheses to make an expression easier to read, even if it doesn’t change the result.

  • Exponentiation

has the next highest precedence.

  • Multiplication and Division

higher precedence than Addition and Subtraction.

Operators with the same precedence are evaluated from left to right (except exponentiation).

... use parentheses to make it obvious.

String Operations¶

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

In [30]:
'2'-'1'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-30-c01bed84b0cf> in <module>()
----> 1 '2'-'1'

TypeError: unsupported operand type(s) for -: 'str' and 'str'

In [31]:
'eggs'/'easy'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-0345b55442cd> in <module>()
----> 1 'eggs'/'easy'

TypeError: unsupported operand type(s) for /: 'str' and 'str'
In [32]:
'third'*'a charm'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-6e8a84f5298f> in <module>()
----> 1 'third'*'a charm'

TypeError: can't multiply sequence by non-int of type 'str'

But there are two exceptions.

The + operator performs string concatenation: it joins the strings by linking them end-to-end.

In [33]:
first = 'throat'
second = 'warbler'
first + second
Out[33]:
'throatwarbler'

The * operator performs repetition. If one of the values is a string, the other has to be an integer.

In [34]:
'Spam'*3
Out[34]:
'SpamSpamSpam'

These two exceptions make sense by analogy.

On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication.

Can you think of a property that addition has that string concatenation does not?

Comments¶

As programs get bigger and more complicated, they get more difficult to read.

Formal languages are dense: it is difficult to say what a piece of code is doing, or why.

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:

a comment may appear on a line by itself

In [37]:
# compute the percentage of the hour that has elapsed
minute = 45

... or you can even put comments at the end of a line

In [46]:
percentage = (minute * 100) / 60     # percentage of an hour
print(str(percentage) + " % ")
75.0 % 

Everything from the # to the end of the line (aka EOL) is ignored – without affecting the execution.

Comments are most useful when they document non-obvious features of the code.

This comment is redundant with the code and useless

In [47]:
v = 5     # assign 5 to v

This comment contains useful information that is not in the code:

In [49]:
v = 5     # velocity in meters/second.

Good variable names can reduce the need for comments, but long names make complex expressions hard to read.

...so there is a trade-off.

Debugging¶

Three kinds of errors can occur in a program:

syntax error¶

refers to the structure of a program and the rules about that structure, e.g. parentheses have to come in matching pairs.

If there is a syntax error anywhere in your program, Python displays an error message and quits.

... the easiest to track down and you will find them everyday faster.

runtime error¶

the error does not appear until after the program has started running.

Also called exceptions to indicate that something exceptional (and bad) has happened.

... it might be a while before you encounter one, but for sure will happen!

semantic error:¶

related to meaning, e.g. your program will run without generating error messages, but it will not do the "right thing", rather something else: specifically, what you told it to do.

tricky, requiring you to work backward (aka reverse engineering) by looking at the output

It could take your entire life, sometimes, to get to the point!