Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Introduction to python programming.

Compiled based versus Scripted programming languages

The earliest programming languages, that is languages that are not machine code but written in a
more human understandable form, where compiled programming languages. These languages first
needed to be translated into machine code and placed into the computer’s memory before they can be
executed (run). Compiler based programming languages remained the standard until the 1990s.

https://www.youtube.com/watch?v=mhpslN-OD_o

In the 1990s the internet gained mass adaption and with the invention of the web browser came a new
form of programming. Web pages were described by plain text (HTML –Hypertext Markup Language)
enriched with language constructs to format the text, e.g. to create hyperlinks, titles, insert images etc.
This text was then read by the web browser which would format it into a page. In this way webpages
could be written the same but could be displayed on any web browser and type of computer (e.g. IBM
PC or Apple MAC, windows or linux operating system, text based or graphical (see below)).
As an extension to this HTML format came Javascript. Javascript was a version of the java
programming language (which was also a compiler based language) that could be used within a
webpage to create e.g. interactivity or animation inside a web page. The code did not need to be
compiled in advance but was interpreted by the browser when the page was downloaded.

The use of a scripting language (which is interpreted by a different program and not compiled in
advance has its advantages and disadvantages.

Interpreter Compiler

Scans the entire program and translates it as a whole


Translates program one statement at a time.
into machine code.

It takes large amount of time to analyze the source


It takes less amount of time to analyze the source
code but the overall execution time is comparatively
code but the overall execution time is slower.
faster.

No intermediate object code is generated, hence are Generates intermediate object code which further
memory efficient. requires linking, hence requires more memory.

Continues translating the program until the first error It generates the error message only after scanning the
is met, in which case it stops. Hence debugging is whole program. Hence debugging is comparatively
easy. hard.

Can run platform independent Needs to be compiled for every platform

Python

Around the time javascript was developed also the Python programming came into creation. The idea
was born at CWI (Centre for Mathematics and Computer Science) in Amsterdam by Guido van
Rossum. The idea behind python was to make programming as easy as ABC, however to still keep
the structures of a programming language. Whether he succeeded is up to you to decide after this
course.

https://www.youtube.com/watch?v=J0Aq44Pze-w

Python is an interpreted (scripted) language for general purpose high level programming. That is,
many different applications can be made using python. It is not specific like matlab or labview. Pyhon
has a design philosophy that desires to make code readable, e.g. by using white spacing as scoping
mechanism.
C:

Python

Python features a dynamic type system and automatic memory management. That means you do not
need to declare a variable to be of any type. Python will determine what the type of the variable is. E.g.
in the example above the variable ‘x’ automatically becomes of type integer. Furthermore a fixed
memory space is not reserved in advance. Therefore in python you do not need to declare the range
of an array in advance. You can add as many elements as needed to your array and extra memory
space is allocated during execution.

Python is widely used around the world and has a large comprehensive standard library and many
additional libraries are available around the web. Because python is easy to use, relatively easy to
learn, no complex software is needed, and does not need to be recompiled (with all the possible
complications) it is widely used by hobbyist students, and scientists (outside computer science). In
industry specifically for embedded and critical systems it is used less because of the advantages of
traditional programming languages (see above).

To start programming in python you only need the python interpreter from python.org and a text editor
(notepad is already sufficient). After installing python (watch out to include to python path to your
(windows) path library) you can run a simple program by starting a command terminal and e.g. typing
“python myfirstprogram.py”. Press Enter and your program will be executed. Note that maybe striking
for python is that in python program does not require e.g. a main function, begin – end statements etc.

There is plenty of more elaborate tooling available for python programming which integrate the
command prompt, adds color to the program constructs for readability, keep your python projects
organized and feature debug options. Some examples are Visual Studio Code, PyCharm and
Microsoft Visual Studio.

https://code.visualstudio.com/

https://www.jetbrains.com/pycharm/

https://visualstudio.microsoft.com/
Basic Python Language constructs
Variables

Variables do not need to be declared (given a type before you use them like in C (e.g. int i = 0).
Furthermore variables can be assigned values from different types and the type of the variable
changes accordingly. E.g. a variable x can be given a value 1 and later it can be given the value 1.0.

Strings are defined like in C and can be concatenated (stuck together to form a new string) using the +
operator.

An array in python is called a list. When creating a list the length of the list does not need to be
defined. The elements of a list are written between ‘[’ and ‘]’ brackets. The type of a list also does not
need to be declared in advance and individual elements of a list can have different types. All variable
assignments below are therefore valid in Python.

Python has a lot of functions (methods) that can be used on lists, for instance to split a string on a
specific character and place the split string in a list.

This code prints the list [‘1’,’2’, ‘3’,’4’,’5’]

For an overview see: https://www.programiz.com/python-programming/methods/list

Print and input

print is used to print something inside a command terminal. This can be the value of any variable.
E.g. you can write print(“hello”) or print(1). You can also print multiple values of different
type at the same time e.g. by print(“hello”,1).

Input() can be used to read input from a command terminal. E.g. n = input() makes the
program wait for input from the command line and stores this input in variable n. However input is
always read as a string, even if it is a number. Therefore when asking for a number as input this
number need to be converted to a number (e.g. int or float) when used for calculation.
try and except

Because a python program is not compiled before execution errors only occur when the code
containing the error is encountered at runtime. This means the program might run OK for a while until
it crashes. Sometimes you do not want this to happen. To avoid this (in advance) you can use the try –
except language construct. This construct will try to execute the code and if not possible it will execute
the exception code. This is also helpful in debugging when you are not sure your code works OK and
you want to test it. For instance the code below only works on integer values and not characters or
strings. Therefore in case the input cannot be converted to an integer an exception can be specified.

Scope

In the program above you also see how the scope is defined in python. In C this was done by ‘{’ and ‘}’
brackets. In Python the scope is defined by indention (space before the program statements). In the
program above both x = int(n) + 2 and print(x) belong to the scope of the try construct.

; and :

In python a program statement also does not need to end with a ‘;’ like in C and other programming
languages. An end of line defines the end of a statement. However ‘:’ is used in several occasions like
with function definitions, if statements, and loops. Omitting these are a common course for errors.

If statements

Like in C, it possible to create conditional statements using if else constructs. The else-if construct
is written as elif. ‘(’ and ‘)’ brackets are not required for the condition. A condition, elif or else
construct always ends with a ‘:’.

Loops

The most common loop constructions are the for-loop and the while loop. In python a for loop can be
constructed over a range.
In this loop 10 times the value of x is incremented, printed, and decremented again. Note: It therefore
prints the same value 10 times. Every time the loop is executed the value is incremented with 1 to the
value 10 (excluding 10). As soon as i reaches value 10 the loop stops, therefore the loop is executed
10 times and not 11 times. It is also possible to make bigger increments, e.g. increasing i by 3 at a
time.

If you want to make a loop that counts down from 10 to 1 (decrementing) you have to write the
following.

It is also possible to create a loop on other ranges, like the elements of a list.

A while loop is basically the same as a while loop in same only written in python style. The while loop
uses a Boolean condition to end.

Functions

A function is defined using the def construct. Like in C a function can have parameters. These
parameters also do not need to be typed. A function also does not need to have a type in case it
needs to return a result. This is simply defined by a return statement at the end of the function. Again
the scope of the function is again defined by the indentation and the function definition also end with a
‘:’.
main function

A python script does not require a main function (or e.g. void loop() in Arduino) to execute. Every
program line is read and executed by the interpreted. However sometimes it may be convenient to use
a main function, if only for readability of your code.

Note: The actual reason to use if name == “ main ” condition is that if you use this python file
as a library for a different python file, the main function is not automatically executed.

Command line arguments

Sometimes you want to run a program in different modes or with different configurations. In this case it
is inconvenient to add these parameters using the input() function. In this case you can give them
when you start the program. For instance you made a controller called controller.py and you want to
run it in safe mode (instead of a regular mode) for 10 seconds. You can add this configuration as
parameters to your program:

Using the argv variable from the system library (sys) these parameters will be stored and can be
used. argv is a list containing the name of the script and its parameters. For instance for the program
above argv[0] = “controller.py” argv[1] = “safemode” and argv[2] = 10.

The following program shows what is contained in argv when you use it in your program:

When I do not add additional arguments when running the program this program simply returns the
program name in a list. However, when I add parameters to the program (called command line
arguments) they are also added in the list and you can use them in the remainder of your program.
Comments

Comments are written using a ‘#’.

References

Now you already know the basics of python programming. If you want to learn more check out the
following websites and links.

https://www.programiz.com/python-programming
https://www.pythoncheatsheet.org/

You might also like