This lecture aims at guiding you to understand the how to of programming, difference between programming languages and the natural languages, the type of programming errors and the meaning code debugging how to perform simple arithmetic operations on the Python command line. Throughout this course, I recommend you to use Jupyter for Python programming.


Programming glossary

The following table contains some technical programming phrases that are often used and heard in the field of computer science and programming, that you need to be familiar as well.

Table 1. Some programming phrases that are discussed in this lecture. The boldface words in the description column indicate items that are expressions with their own description in this table.
Expression Description
algorithm A general method for solving a class of problems.
bug An error in program that has to be resolved for successful execution of the program.
compiled language A programming language whose programs need to be compiled by a compiler in order to run.
compiler A software that translates an entire high-level program into a lower-level language to make it executable.
debugging The process of finding and removing any type of error in the program.
exception An alternative name for runtime error in the program.
executable An object code, ready to be executed. Generally has the file extension .exe or .out or no extension at all.
formal language A language that is intentionally designed for specific purposes, which, unlike natural languages, follows a strict standard.
high-level language A programming language (e.g., Python, Fortran, Java, etc) that has high level of abstraction from the underlying hardware.
interpreted language A programming language whose statements are interpreted line-by-line by an interpreter and immediately executed.
low-level language A programming language that has a low-level of abstraction from computer hardware and architecture, such as Assembly. Very close to machine code.
natural language A language that evolves naturally, and has looser syntax rules and standard compared to formal languages.
object code The output of a compiler after translating a program.
parsing Reading and examining a file/program and analyzing the syntactic structure of the file/program.
portability A program's ability to be exucatable on more than one kind of computer architecture, without changing the code.
problem solving The process of formulating a problem and finding and expressing a solution to it.
program A set of instructions in a that together specify an algorithm a computation.
runtime error An error that does not arise and cause the program to stop, until the program has started to execute.
script A program in an interpreted language stored in a file.
semantic error A type of error in a program that makes the program do something other than what was intended. Catching these errors can be very tricky.
semantics The meaning of a program.
source code A program in a high-level compiled language, before being compiled by the compiler.
syntax error A type of error in program that violates the standard syntax of the programming language, and hence, the program cannot be interpreted or compiled until the syntax error is resolved.
syntax The structure of a program.
token One of the basic elements of the syntactic structure of a program, in analogy with word in a natural language.


The content of a computer program

Although different programming languages look different in their syntax standards, virtually all programming languages are comprised of the following major compnents (instructions):

  1. input
    Virtually every program starts with some input data by the user, or the input data that is hard-coded in the program.

  2. mathematical/logical operations
    Virtually all programs involve some sort of mathemtical or logical operations on the input data to the program.

  3. conditional execution
    In order to perform the above operations on data, most often (but not always) there is a need to chack if some conditions are met in the program, and then perform specific programming instructions corresponding to each of the conditions.

  4. repetition / looping
    Frequently it is needed to perform a specific set of operations repeatedly in the program to achive the program’s goal.

  5. output
    At the end of the program, it is always needed to output the program result, either to computer screen, or to a file.

Debugging a program


As it is obvious from its name, a bug in a computer program is annoying programming error that needs fixing in order for the program to become executable or to give out the correct answer. The process of removing program bugs is called debugging. There are basically three types of programming bugs (errors):

  1. syntax error

    A program, wether interpreted or compiled, can be succesfully run only if it is syntactically correct. Syntax errors are related to the structure and standard of the language, and the order by which the language tokens are allowed to appear in the code. For example, the following Python print statement is a syntax error in Python 3 standard, whereas it was considered to be the correct syntax for print in Python 2 standard.

    In [21]: print 'Hello World!'
      File "<ipython-input-21-10fdc521e430>", line 1
     print 'Hello World!'
                        ^
    SyntaxError: Missing parentheses in call to 'print'
    


    The syntactically correct usage of print in Python 3 would be,

    In [22]: print ('Hello World!')  
    Hello World!
    


  2. runtime error

    Runtime errors or sometimes also named exceptions are a class of programming errors that can be detected only at the time of running the code, that is, they are not syntax errors. Examples include:

    • memory leaks (very common error in beginner C and C++ codes)
    • uninitialized memory
    • access request to illigal memory address of the computer
    • security attack vulnerabilities
    • buffer overflow
      These errors can be sometimes tricky to identify.

  3. semantic error
    Unlike syntax errors that comprise of something the compiler/interpreter does not understand, semantic errors do not cause any compiler/interpreter error messages. However, the resulting compiled/interpreted code will NOT do what it is intended to do. Semantic errors are the most dangerous types of programming errors, as they do not raise any error flag by the compiler/interpreter, yet the program will not do what it is intended to do, although the code may look perfectly fine on its face. Semantic error is almost synonymous with logical error. Dividing two integers using the regular division operator / in Python 2 and expecting the result to be real, would result in a semantic error. This is because in Python 2 standard, the regular division operator is equivalent to integer division for integer operands:

    In Python 2,
    In [23]: 2/7
    Out[23]: 0
    


    Whereas, you might have really meant a float division by using /, as in Python 3,

    In [24]: 2/7
    Out[24]: 0.2857142857142857
    


The first Python program


The traditional first program in Python language has the following form.

In [25]: print ('Hello World!')  
Hello World!


Methods of running a Python program


  1. Running Python code on the Python interpreter’s command prompt:
    Now, as you may have noticed, in the above example, I used IPython command line to code my first simple Python program. This is one of the simplest and quickest method of Python coding and is actually very useful for testing small simple Python ideas and code snippets on-the-fly.

  2. Running Python code inside a Python file Python from the Bash command line:
    As the program size grows, it wiser to put all of your Python script into a single file, and then let the Python interpreter run (i.e., interpret) your entire file all at once. To save the above simple “Hello World” Python code in a file and run it, open a Bash command prompt, then use the Bash cat command to create and add the Python command to your Python file as in the following (On Windows devices, you can use the Git command prompt).

    Amir@CCBB-Amir MINGW64 ~
    $ cat >> firstPythonCode.py << EOF
    print ('Hello World!')
    EOF
    


    Then you can use call python interpreter from the Bash command line to execute your Python code.

    $ python firstPythonCode.py
    python firstPythonCode.py
    Hello World!
    


  3. Running Python code inside a Python file from the Bash command line as an standalone executable:
    You can also avoid typing the name of the interpreter (python) in order to run your code by adding the following shebang at the top of your Python script, like the following.

    $ cat >> firstPythonCodeWithShebang.py << EOF
    #!/usr/bin/env python
    print ('Hello World!')
    print ('This is a Python script with Shebang!')
    EOF
    


    The result is that now you can run your Python script without the interpreter’s name, as an executable file:

    $ ./firstPythonCodeWithShebang.py
    Hello World!
    This is a Python script with Shebang!
    


    Note that shebang directive only works under Unix/Linux operating systems and command prompts (not windows). When a Python script with a shebang is run as a program, the program loader parses the rest of the script’s initial line as an interpreter directive. The specified interpreter program is run instead, passing to it as an argument the path that was initially used when attempting to run the script.

    On the other hand, if you try to run your original code (without Shebang) as an executable without Python interpreter name, you will get an error message like the following,

    Amir@CCBB-Amir MINGW64 ~
    $ ./firstPythonCode.py
    ./firstPythonCode.py: line 1: syntax error near unexpected token `'Hello World!''
    ./firstPythonCode.py: line 1: `print ('Hello World!')'
    


  4. Running Python code inside a Python file by first compiling it to bytecode from the command line:
    You can also compile your Python script into a bytecode. This is however, a topic of a future lecture.

Python interpreter as a simple calculator

One of the greatest advantages of Python is that it can be used as a simple calculator and program interpreter on-the-fly, just like MATLAB, Mathematica, R, and other scripting languages. In the following, you will see why and how.

Values and their types in Python

Values are one of the most fundamental entities in programming. Like any other language, a value in Python can be of different types, most importantly Numeric (plain integer, long integer, float (real number), complex), Boolean (logical) which is a subtype of Numeric, or String.

The following are a few example arithmetic operations with values in Python. You can perform very simple arithmetic on the Python command line, and the result immediately by pressing enter.

2 + 5 # Just typing some comment on the Python command line. Anything after # is a comment and will be ignored.
7
2 - 7 # difference
-5
2 * 7 # product
14

Obtaining the type of a value

You can use the Python’s built-in function type to get the type of a value in Python (Of course, this is somewhat obvious and redundant for a value as we already readily know the type of a value).

type(2*7) # type function gives you the type of the input object to function "type"
int ```python type('This is a Python string') # a string value in Python ```
str
type("This is a Python string") # you can also use quotation marks for representing string values, but keep in mind to be consistent!
str
type(True) # type of a boolean True value
bool
type(True) # type of a boolean False value
bool

Value coercion in Python

Value coercion is the implicit process by which a the Python interpreter/compiler automatically converts a value of one type into a value of another type when that second type is required by the surrounding context. For example:

2.0 * 7 # Note that the product of float and integer, is coerced into a float.
type(2.*7)
14.0
float
2 / 7 # floating point division (in Python 3!).
0.2857142857142857
ATTENTION: Python 2 Alert!

In Python 2, the above division would give you 0, that is, in Python 2, the division operator performs an integer division for two input integer operands. I recommend you to always coerce the result into float (if float is what you demand) by adding a decimal point to one of the operands in your operation.
2.0 / 7 # Also floating point division
0.2857142857142857
2 // 7 #  integer division, or floor division
0
2.0 // 7.0
0.0
12 // 7 #  another integer division, or floor division
1
12.0 // 7 #  Also a integer division, or floor division, BUT NOTE THAT the output is now a real number 
1.0

Summary of difference in division between Python 2 and Python 3:
Note that there is a difference between Python 2 and 3 for integer division.

Python 2

input:

print 'Python', python_version()
print '3 / 2 =', 3 / 2
print '3 // 2 =', 3 // 2
print '3 / 2.0 =', 3 / 2.0
print '3 // 2.0 =', 3 // 2.0


output:

Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0
Python 3

input:

print('Python', python_version())
print('3 / 2 =', 3 / 2)
print('3 // 2 =', 3 // 2)
print('3 / 2.0 =', 3 / 2.0)
print('3 // 2.0 =', 3 // 2.0)


output:

Python 3.5.2
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

In other words, in Python 3, 3 / 2 performs a floating point division, whereas in Python 2, 3 / 2 performs a floor division, also called integer division.

NOTE

If you want to get the Python version you are using, use the following commands. The first command imports from the Python platform module, the command python_version. Later on, we will discuss what Python modules are and how and why you should use them.
from platform import python_version
python_version()

'3.5.2'
2**7 # This is an exponentiation operation. The notation is taken from Fortran exponentiation
128
2.0**7 # This is a float exponentiation.
128.0
2**7.0 # ATTN: Avoid this format, if not necessary.
128.0
12 % 7  # This is a remainder operation
5
12.0 % 7 # Another remainder operation, with its result coerced into float
5.0

Some useful built-in operations/functions in Python

pow(2,7) # same operation as 2**7. This is the same exponentiation function as in C language.
128
pow(2.0,7) # same thing but now the result is coerced into float
128.0
abs(-999) # absolute value
999
int(-999.9) # removes the decmial points and keeps the integer part
-999
int(999.9) # removes the decmial points and keeps the integer part
999
complex(-999.9) # complex number with real part -999.9 and no (zero) imaginary part
(-999.9+0j)
complex(-999.9, 2) # complex number with real part -999.9 and imaginary part value of 2
(-999.9+2j)
complex(-999.9, 2).conjugate() # the conjugate of the complex number
(-999.9-2j)
type(complex(-999.9, 2).conjugate()) # type function can take complex arguments as input!
complex
divmod(5, 2.0) # gives out the pair (x // y, x % y)
(2.0, 1.0)
type(divmod(5, 2.0)) # the type of output from divmod
tuple

Order of operation in Python

The order of operation in Python is pretty much the same as in any other sane language: anything inside Paratheses has precendence over Exponentiation (**) has precedence over Multiplication & Division (/ & *) has precedence over Addition & Subtraction (+ & -). In abbreviation, the rule of operation precendence is PEMDAS.

print("3 + 2.0 - 3 * 2 / 3 =",3 + 2.0 - 3 * 2 / 3)
3 + 2.0 - 3 * 2 / 3 = 3.0

Operations on string values in Python

You can concatenate strings in Python just like adding numbers together. Also, you can multiply string values by a number, to get mutiple copies of the string value.

'Amir ' + 'Shahmoradl ' + 'is my full name!' # You can add strings together just like numbers. This is called string concatenation.
'Amir Shahmoradl is my full name!'
'amir' - 'shahmoradi' # This is meaningless and syntactically invalid in Python
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-6-41f5035ed36a> in <module>()
----> 1 'amir' - 'shahmoradi' # This is meaningless and syntactically invalid in Python


TypeError: unsupported operand type(s) for -: 'str' and 'str'
'amir ' * 5 + 'is 5 amirs concatenated!' # multiplying string values by some number
'amir amir amir amir amir is 5 amirs concatenated!'
'amir ' * 's' # meaningless
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-11-ddce79744de9> in <module>()
----> 1 'amir ' * 'r' # meaningless


TypeError: can't multiply sequence by non-int of type 'str'
'amir' / 's' # also meaningless
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-12-b6e45f1a8ab1> in <module>()
----> 1 'amir' / 's' # also meaningless


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


COOL FEATURE FOR STRING MANIPULATION

Note that string values are like vectors of characters in Python! you can call a specific element of it!


'amir'[0] # first letter in the string
'a'
NOTE

In order to count elements from the end of the string, use negative in the index.
'amir'[-2] # the second letter from the end of the string
'i'
'amir'[-2:-3] # you get nothing because of incorrect indices
''
'amir'[-3:-2] # you get something because of correct indices!
'm'
'amir'[-3] # this is the same as 'amir'[-3:-2] 
'm'
'amir'[-3:] # This outputs the three last letters of the string
'mir'
'amirShahmoradi'[:-3] # This outputs the letters of the string from the beginning up to the fourth letter from the end.
'amirShahmor'
'amirShahmoradi'[::-1] # This outputs ALL the letters in the string in reverse, from the end to the beginning.
'idaromhahSrima'
'amirShahmoradi'[::-2] # This outputs every other letter in the string in reverse, from the end to the beginning.
'iaohhrm'
'amirShahmoradi'[-3:].upper() # This outputs the third last letters of the string
'ADI'
NOTE: List of string manipulation methods

To see the full list of powerfull string methods that can manipulate strings, like the above example, see this page.

Boolean operations in Python

As we mentioned before, Boolean types are a subclass of Integers. Boolean operations are essential in branching statements.

True or False # This is OR logical operation
True
True and False # This is AND logical operation
False
not True # This is not logical operation
False
'amir' is 'amir' # object identity comarison
True
'amir' is not 'Jake!' # negated object identity
True

In addition, to the above operations, there also other more complex Boolean operations in Python, some of which you can study further here.

NOTE: Object's identity in Python

To get the identity of an object, use Python's id() command. id() is a built-in function in Python 3, which returns the identity of an object. This identity is a unique integer for that object during its lifetime. This unique id is also the address of the object in the device memory. Keep in mind that the object's id might change from one computer to another, from one run to another run.
id('amir')
81758280
id(2)
501744144
id(2) == id(3) # equality operation: tests for the same value
False
id(2) != id(3) # inequality operation
True
ATTENTION

Be very careful with operations is and equality ! These two are not the same! See the examples below.
(1,1) is (1,1) # Two similar tuples have not the same identifiers in Python! Will soon see what tuples are.
False
(1,1) == (1,1) # Two similar tuples have the same value in Python!
True

String comparison

Strings are compared lexicographically using the numeric equivalents in ASCII codes (the result of the built-in Python function ord() of their characters.

'amir' > 'jake' # String comparison. Basically the character ASCII codes are compared here.
False
'amir' > 'Jake' # 'J' is ahead of 'a' in ASCII characters.
True
'amir' > 'Amir' # 'A' is ahead of (smaller than) 'a' in ASCII characters.
True
'amir' > 'amis' # Comaprison is performed is equality for each character holds, until the end is reached.
False

Python’s print function

We have already used print function to create the first Python program. But note also the difference in print between the two Python versions. In Python 3, print is a Python function, whereas in Python 2, it is a Python statement.

print('My name is Amir')
My name is Amir

Note: You can use wildcards in Python strings. You can also use double quotes for strings.

print("My name is Amir",'\n') # You can use wildcards in Python strings. You can also use double quotes for strings.
My name is Amir 
print('My name is Amir','\n'*2,"I do work at \"UT Austin\".") 
print('''
You can multiply strings by integer! \n
Note how I used wildcards for quotation marks around "UT Austin" in my previous print function, in order to be consistent with Python syntax.

Did you also notice how I am creating a multi-line Python string right now?!
''')
My name is Amir 

 I do work at "UT Austin".

You can multiply strings by integer! 

Note how I used wildcards for quotation marks around "UT Austin" in my previous print function, in order to be consistent with Python syntax.

Did you also notice how I am creating a multi-line Python string right now?!
"""
This is also a multi-line
comment in
Python
"""
'\nThis is also a multi-line\ncomment in\nPython\n'
'''
You can use single quotes
for multi-line commenting as well.
Always be as expressive as possible with your comments in you code.
It does not harm!
'''
'\nYou can use single quotes\nfor multi-line commenting as well.\nAlways be as expressive as possible with your comments in you code.\nIt does not harm!\n'

In the following section, you will learn much more about the print function, especiallu when dealing with variables.

Variables in Python

Python has 6 main variable types:

  • Number
  • String
  • List
  • Tuple
  • Dictionary
  • Sets

We will get to each of these soon. The variable naming convention in Python is that each variable starts with a letter and can contain only letters, numbers or underscore “_”.

var1 = 1
print('value of var1 is ',var1,'.')
value of var1 is  1 .
a_long_variable_name = 2.5 # The variable name can be almost as long as you wish
print(a_long_variable_name)
2.5

Variable naming convention in Python

A Python variable can only begin with letter or underscore _. Numbers are only valid if they appear inside or at the end of the variable name. Other symbols are syntactically invalid anywhere in a variable name.

123new_var = 2.5 # This is an invalid name
  File "<ipython-input-10-0e3e63931842>", line 1
    123new_var = 2.5 # This is an invalid name
             ^
SyntaxError: invalid syntax
new_var$ = 2.5 # symbols are not valid in Python variable names
  File "<ipython-input-12-71f3fbc68938>", line 1
    new_var$ = 2.5 # symbols are not valid in Python variable names
           ^
SyntaxError: invalid syntax
amir = "teacher"
print('Amir is a', amir)
Amir is a teacher
123amir = "teacher" # Wrong name for variable
  File "<ipython-input-38-85ed673cd303>", line 1
    123amir = "teacher"
          ^
SyntaxError: invalid syntax
life_expectancy = 120; print( "The life expectancy for the millennials is projected to be %d years! (But don't believe it...)" % (life_expectancy) );
The life expectancy for the millennials is projected to be 120 years! (But don't believe it...)
# Now lets do a Physics calculation.
v0 = 5; # initial velocity for a projectile motion.
g = 9.81 # Earth gravity acceleration.
t = 0.6
y = v0*t - 0.5*g*t**2
print('''
At t = %f seconds, a ball with initial velocity v0 = %.3E m/s is located at the height %.2f m.
''' % (t,v0,y) )
At t = 0.600000 seconds, a ball with initial velocity v0 = 5.000E+00 m/s is located at the height 1.23 m.
# or on multi-line:
print('''
At t = %f seconds,
a ball with initial velocity v0 = %.3E m/s
is located at the height %.2f m.
100%% accurate!
''' % (t,v0,y) )
At t = 0.600000 seconds,
a ball with initial velocity v0 = 5.000E+00 m/s
is located at the height 1.23 m.
100% accurate!

Here are some printf format specifications, that can be used with print function:

  • %s for string
  • %d for integer
  • %0xd for integer padded with x zeros
  • %f for decimal notation with 6 decimals
  • %e for scientific notation
  • %E for scientific notation
  • %% percentage sign itself

There is also a a more recent, recommended way of determining the string format in Python, using .format() method, about which you find some more useful information here.



Comments