# Chapter 1 - Introduction to Programming ###### tags: `Computer programming` ## Learning objectives By the end of this chapter, you should able to: 1. Describe the basic concepts of the Input-Process-Output cycle and the use of stored program in a processing system 1. Describe the types of software of a computer system 1. Describe the development of programming languages 1. Distinguish between compiler and interpreter in third generation languages 1. Write “Hello World” and other simple program (arithmetic) in Python 1. Identify and use good programming style when writing a program 1. Identify the types of errors in programming 1. Use different debugging techniques to solve problems in program fragments ## Computer Systems ![](https://i.imgur.com/JKc6ny3.png) The user uses the hardware (physical equipment) like input and output devices, the processing units, and the auxiliary storage devices to communicate with the machine. Software is used to process the input and output data in the computer. Software can be generally divided into two types, namely system software and application software. The below picture shows the relationship between user, hardware, system software and application software. ![](https://i.imgur.com/OI6ef6W.png) ### Operating systems *An operating system (OS)*, in its most general sense, is software that allows a user to run other application on a computing device.While it is possible for a software application to interface directly with hardware, the vast majority of applications a written for an OS, which allows them to take advantage of common libraries and not worry about specific hardware details. ![](https://i.imgur.com/RhBUOBA.png) The operating system manages a computer’s hardware resources, including: * *Input devices* such as a keyboard and mouse * *Output devices* such as display monitors, printers and scanners * *Network devices* such as modems, routers and network connections * *Storage devices* such as internal and external drives The OS also provides services to facilitate the efficient execution and management of, and memory allocations for, any additional installed software application programs. Nowadays, there are mainly three types of operating systems, namely: * Microsoft Windows * Macintosh, including MacOS, iOS, iPadOS, etc. * Linux, which is a set of open source OS with different distributions, including Android ### Different types of computer system There are several types of computer systems that are commonly used in daily life. They are described as follows. * **Single-user single application system**: a system that can be used for only one user at a time for running only one application * **Single-user multi-tasking system**: a system that can be used for only one user at a time for running more than one applications * **Multi-user multi-tasking system**: a system that can be used for more than one users at a time for running more than one applications * **Batch processing system**: a system that operates the operations until a specific time * **Real-time system**: a system that operates the operations on order * **Online (Network) interactive system**: a system that connected to the internet * **Parallel processing system**: a system that includes more than one processing unit to increase the processing power * **Distribute processing system**: a system that is distributed to a collection of computers, i.e. one operation may involved more than one machine ## Programming Paradigm(*) In general, there are 5 generations of programming languages. They are listed below. * First Generation Language (1GL): Machine language * Second Generation Language (2GL): Symbolic language * Third Generation Language (3GL): High level language * Fourth Generation Language (4GL): Very high level language * Fifth Generation Language (5GL): Natural language ![](https://i.imgur.com/oGpqTfh.png) ### 1GL - machine language The machine language is composed of '0's and '1's only, which are used to represent two states: `ON` and `OFF`. ```...0001001010010000101010101001...``` Each computer has its own machine language, i.e. the machine language is machine dependent. **The machine language is the only language that is understood by computer hardware.** However, it is difficult for human beings to read and write the machine language, and hence secondary general language is developed. 2GL - symbolic language Second Generation Language is a language that composites by symbols (i.e. numbers, characters, etc.). It is easier (but still difficult) for human beings to write a computer program. ``` entry main, ^m sub12 #12,sp jsb C$MAIN_ARGS movab $CHAR_STRING_CON ... ``` However, the computer does not understand symbolic language, it must be translated to the machine language by a translator called assembler. It is machine dependent because it is a direct translation of machine language. ![](https://i.imgur.com/EXCQMpP.png) ### 3GL - high level language The assembly language is still difficult to be understood by human beings. Also, it is a machine dependent machine such that the codes cannot be used in different machines. Hence, the high-level language is invented to solve these problems. #### Translator ***Translators*** are required to translate the source code into machine codes. There are two types of translators for 3GL in general, namely compiler and interpreter. ##### Compiler We can create and run a program with a ***compiler*** with the following four-step process. 1. Writing and editing the program 1. Compiling the program with compiler, while compiler composes a preprocessor and a translator 1. Linking the program with the required library modules 1. Executing the program After the compilation, the source code is translated from the whole programming source code to the machine code, that is the language that only the machine can be read. C, C++, Pascal are using compiler. ![](https://i.imgur.com/U0DYNdY.png) ##### Interpreter Interpreter is another technology for running the codes. Unlike the compiler, the interpreter does not translate the whole program into the machine code, but translates it line by line. Javascript, Python and PHP are using interpreters. ![](https://i.imgur.com/DaIjArX.png) Below table shows the compare and contrast on the compiler and interpreter. | |Compiler|Interpreter| |---|--------|-----------| |Input|It takes an entire program at a time.|It takes a single line of code or instruction at a time.| |Output|It generates intermediate object code.|It does **NOT** produce any intermediate object code| |Speed|Faster|Slower| |Memory|More|Less| |Error detection|Difficult|Easier| |Pertaining Programming languages|C, C++, C#, ...|JavaScript, PHP, Python, ...| #### 3GL programming paradigm Programming languages fall into a number of programming paradigms. The two major programming paradigms in use today are procedural (imperative) programming and object-oriented programming. Each provides a different way of thinking about computation. They will be described in more detail in the later chapters. ### 4GL - very high level language The fourth generation language (4GL) is a programming language with a higher level of abstraction than 3GL. Only SQL is widely used nowadays and it will be covered in the later chapters. ### 5GL - natural language The fifth generation language (5GL) is a language based on problem solving using constraints given to the program, rather than using an algorithm written by programmers. Prolog is one of the 5GL. ## First program in Python You need to set up the programming environment before starting writing a program. In the course, PyCharm is suggested as the programming environment. ### Set up the programming environment 1. Download and install PyCharm from [https://www.jetbrains.com/pycharm/download/](https://www.jetbrains.com/pycharm/download/) 2. When PyCharm is launched, follow the instructions given by the program. 3. Create a new project by clicking ![](https://i.imgur.com/yuxjiP1.png) “New Project” ![](https://i.imgur.com/WO43dkZ.png) 4. Select ![](https://i.imgur.com/wUTYSCM.png) “Pure Python” Path, input the path and then click ![](https://i.imgur.com/3Hy8IcS.png) “Create”. ![](https://i.imgur.com/mfGaWgu.png) 5. Click “File” > “New…”, and then select ![](https://i.imgur.com/Nywwhe1.png) “Python File”. Name the file as “`hello.py`”, and then click Enter. ![](https://i.imgur.com/F4XMGkL.png) ![](https://i.imgur.com/QdRBxLU.png) ![](https://i.imgur.com/hXfYBHQ.png) 6. Input the following program. ![](https://i.imgur.com/UOHEP1n.png) 7. Click “Run” > “Run…”, and then select “hello.py”. ![](https://i.imgur.com/a8R4QKK.png) ![](https://i.imgur.com/yKvAOyZ.png) 8. You should see the following terminal. ![](https://i.imgur.com/uCxodwQ.png) ### Structure of a Python Program All Python programs should follow a series of rules called syntax. A Python program should include the following components. 1. **Import module commands** (optional): import functions and classes defined that can be used in the program 1. **Global declarations** (optional): variables used that are visible to all part of the program 1. **Functions** (optional): perform tasks within a program. 1. **Statements**: the instructions that perform tasks. ![](https://i.imgur.com/T9vMhmU.png) The following “Hello World” is a valid python program with empty global declarations and only one statement that prints a greeting. ![](https://i.imgur.com/PX19AIX.png) Note that Python is a *case-sensitive* programming language, i.e. `age` and `Age` is totally different in Python. ### Comments Comments are written as the internal program documentation by the programmer. It improves the readability of the program such that the other programmer can understand more about the program through comments. The interpreter ignores these comments when it translates the program. The commands starts with a pound sign (#). ```python! # This is a whole line comment a = 5 # This is a partial line comment. ``` Below shows an example of the Hello World program with comments. ```python!= # The greeting program. This program demonstrates # Some of the components of a simple Python program. # Written by: your name here # Date: Date program written # Local Declarations # Statements print("Hello World!"); ``` ### Basic of writing of Python Programs There are several basic concepts of writing a Python program, namely the variables, statements, and input and output functions. Details will be covered in the later chapters. #### Variables Variables are the name memory locations that have a data type. A variable needs to be declared before use. #### Declaring and defining a variable Syntax: `variable_name = value` Example: `age = 18` Note that `=` means assignment (from right to left) ### Statement Each statement performs one or more masks. Example 1 (variable definition is in fact a statement): `age = 21` Example 2 (update the value of a variable): `age = age + 2` ### Input and output function The input and output functions read the value input by user, and show the data on the screen respectively. #### `print()` function The `print()` function can output the static information. Text should be put inside the single quotation marks (`' '`) or double quotation marks (`" "`). The non-textual information special characters are represented by escape characters. Some examples are shown below. | Code | Description | | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `\n` | New line. Position the cursor to the next line. | | `\r` | Carriage return. Reset the position of the cursor to the beginning of line. In the Windows environment, `\r\n` is used as the new line character. | | `\t` | Horizontal tab. Move the cursor to the text tab stop. | | `\\` | Backslash (`\`). | | `\'` | Single quote (`'`). | | `\"` | Double quote (`"`). | | `\b` | Backspace. | E.g. Print the “Hello World” and a new line: `print("Hello World!\n")` Notice that a new line character will be added at the end of print() function by default. Try typing in each of the following commands. Write down the results you see. | Commands | Result | |--------------------------|--------------------| | `print("Hello, world!")` | Hello, world! | | `print("Hello", "world!")` | Hello world! | | `print(3)` | 3 | | `print(3.0)` | 3.0 | | `print(2 + 3)` | 5 | | `print(2.0 + 3.0)` | 5.0 | | `print("2" + "3")` | 23 | | `print("2 + 3 =", 2 + 3)` | 2 + 3 = 5 | | `print(2 * 3)` | 6 | | `print(2 ** 3)` | 8 | | `print(7 / 3)` | 2.3333333333333335 | | `print(7 // 3)` | 2 | | `print(7 % 3)` | 1 | #### `input()` function The `input()` function is used to input information and store it in a variable in the form of strings. E.g. `age = input("What is your age?")` The above statement prints the string "What is your age?", reads a string and then stores the value to the variable age. The `int()` function is required for converting the string read to integers, as shown below. `age = int(input("What is your age?"))` ### Example: Age program The below program asks the user’s age, and then prints out his/her age in the next year. ```python!= age = int(input("How old are you? ")) # Ask for input age = age + 1 # Increment the number # Output the number in a sentence print("You are", age, "years old next year.") ``` <iframe src="https://trinket.io/embed/python3/7e9941630a?toggleCode=true&runOption=run&start=result" width="100%" height="100" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> ## Good programming practice 1. Write down your plan and logic in the form of comments before writing any code. 1. Name the **variables** with **meaningful** names, e.g use counter instead of a. They are usually named in `CamelCase` (combine the word without spaces and use capital letter for each first letter) or `lowercase_seperated_by_underline`. 1. Keep spaces between operator and operands, e.g. `c = a + b` instead of c=a+b 1. Indent statements that are dependent on previous statements. The indentations are usually four spaces or a tab from the left end of the controlling statement. 1. Keep only **one action for each line**. 1. Consistent with the style you are using. ![](https://i.imgur.com/U8o9cCg.png) ## Errors and Debugging In programming jargon, *“errors” are known as “bugs”* [^1]. Even experienced programmers make mistakes, so implementing software always involves debugging: finding and fixing errors in the code. ### Types of programming errors We can classify programming errors into three general categories, namely build errors, runtime errors and logic errors. #### Build Errors A *build error* occurs when we attempt to build the code and are unable to do so because of an issue with the code. A Syntax error is one of the build errors. It occurs when we write code that does not conform to the syntax. The following shows an example when there is a syntax error. ```python!= print "Hello World" ``` <iframe src="https://trinket.io/embed/python3/60fe7120ac?toggleCode=true&runOption=run&start=result" width="100%" height="230" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> From the output console, we can read the error type (i.e. `SyntaxError`). There may be some suggestions for us to solve the bug. No programs can be run under build errors. Programmers need to modify the code first. #### Runtime errors *Runtime* errors are errors that make a program crash while it is running. A typical example of runtime error is *zero division error*. ```python! a = 3 b = 0 print(a / b) ``` <iframe src="https://trinket.io/embed/python3/c3f62859ed?toggleCode=true&runOption=run&start=result" width="100%" height="210" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> Programs still can run under runtime error until the error is reached. For this kind of case, we can use `try-except` statements to prevent errors, which will be discussed in a later chapter. #### Logic errors A *logic error* occurs when a program crashes but then exhibits incorrect behavior. ```python!= a = 3 b = 4 print("Average of 3 and 4 is", a + b / 2) ``` In the above example, we want to calculate the average of 3 and 4, and the expected result is 3.5. However, due to the order of operations, the program got an incorrect answer. ### Debugging techniques There are several debugging techniques used by the programmers. #### Program tracing Program tracing is the process of executing program code by hand, with concrete inputs. Please read [this article](https://lec.inf.ethz.ch/ifmp/2019/dl/additional/handouts/ProgramTracing.html) for more information. #### Breakpoints A breakpoint is a point in the program where the code will stop executing. Programmers can read the values of the variables in specific breakpoints with the aid of the debugger. #### Stubs A *stub* is a small piece of code that simulates another system your code has to interact with. For example, if there is a program that asks for users’ input, but we need to ensure the program fragment after the input statement, we can add one more line to assign a value such that the value of that variable is ensured. ```python!= a = int(input("Enter a: ")) a = 3 # We assign a = 3 here for testing b = 4 C = a + b / 2 ``` #### Print debugging *Print debugging* is a very useful debugging technique, which means to print out the values of variables and re-run the program by using the print function. Sometimes, seeing those values will help us to immediately realize what the problem is. We can even simulate breakpoint by print debugging, i.e adding some `print` function in the program. ## Learning Path of Python ![](https://i.imgur.com/1H4IahB.png) ## Chapter summary * Programs are written using a formal notation known as a programming language. There are many different languages, but all share the property of having a precise syntax (form) and semantics (meaning). * Computer hardware understands only a very low-level language known as machine langues. Programs are usually written using human-oriented, high-level languages such as Python. * A high-level language must either be compiled or interpreted in order for the computer to understand it. * Python is an interpreted language. * A Python program is a sequence of commands (called statements) for the Python interpreter to execute. Python includes statements to do things such as print output to the screen, get input from the user, calculate the value of a mathematical expression, and perform a sequence of statements multiple times (loop). * Programs are composed of statements that are built from identifiers and expressions. ## Exercises 1. The syntax of a language is its meaning, and semantics is its form. A. True B. False 2. Computer languages designed to be used and understood by humans are A. natural languages B. High-level computer languages C. machine languages D. fetch-execute langues 3. One difference between a compiler and an interpreter is A. a compiler is a program B. a compiler is used to translate high-level language into machine language C. a compiler is no longer needed after a program is translated D. a compiler processes source code 4. Which of the following is not true of comments? A. They make a program more efficient. B. They are intended for human readers. C. They are ignored by Python. D. In Python, they begin with a pound sign (#). 5. Why it is good idea to first write out an algorithm in pseudocode in the comment part, rather than jumping immediately to Python code? ## Programming Exercises ### Exercise 1 Write a program to print the following figure. ``` -. .-. .-. .-. .-. .-. . ||\|||\ /|||\|||\ /|||\|||\ /| |/ \|||\|||/ \|||\|||/ \|||\|| ~ `-~ `-` `-~ `-` `-~ `- ``` ### Exercise 2 Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. A sample run is shown below. ``` Give me your name: Michele How old are you: 16 Michele will be 100 years old in the year 2106 ``` ### Exercise 3 Write a program that prompts the user to enter two integers and then prints out the sum, difference and product of the two integers. A sample run is shown below. ``` Enter the first integer: 10 Enter the second integer: 6 The sum is 16 The difference is 4 The product is 60 ``` ## Appendix 1 - Useful websites 1. [Python Tutor](https://pythontutor.com/) 2. [Visualgo](https://visualgo.net/en) [^1]: There are many apocryphal stories about the origin of this term and how it got applied to programming. In the most popular story, Grace Murray Hopper discovered that the Harvard Mark II computer was producing incorrect answers. When she examined the machine more closely, trying to locate the problem, she found a squashed moth, which was caught between the contacts of an electromechanical relay, preventing the relay from fully closing; ergo, the first computer bug. In fact, she extracted the moth with a pair of tweezers and taped it into the operator's logbook with the comment “First actual bug found” -implying that the term was already in use at that time. Other stories about the first use of “bug” abound, so perhaps we shall never know the true entomology of this word.