Online introductory Python programming course

Marcin Leśniak, PhD

 

This is an introductory Python programming course for those who are going to apply for Cognitive Science second-cycle studies at the University of Warsaw. The programme of these studies includes developing competences in the analysis of data which are collected during various scientific projects. To become fluent in data analysis you need to develop some programming skills. Does it mean that you have to be a full-fledged programmer or computer scientist? The answer is no. However, cognitive scientists usually know (not necessarily at a very advanced level) one or two programming languages, which helps them analyze data faster and better. The good news is that if you know one programming language, it is much easier to learn another one. Therefore, the entrance exam will also test how well you understand basic programming concepts and rules. In this short course you will learn:

  • general information about what kind of programming language Python is
  • why and how Python is used in cognitive science
  • what tools (i.e. software) you can use to develop Python programs/scripts
  • elements of Python’s language, such as syntax and basic data types
  • basic operations we can perform on variables
  • some of good practices in programming

 

Python Q&A

Q: What is Python?

A: Python is a programming language.

Q: What is a programming language?

A: It is a language we use to write programs.

Q: What is a program?

A: It is a set of instructions that tell a computer what to do and how to do it.

Q: What are the instructions?

A: A piece of code which can be understood by a computer.

 

What is the difference between natural language and programming language?


Drink your medicine after a hot bath

What would YOU do?

What would COMPUTER do?

 

The languages used by humans and computers have many common features. However, natural language which all of us use on a daily basis (although not without some misunderstandings from time to time) is still too difficult for our computers. Programs we write are read by computers literally and should not leave room for interpretation or cause confusion. The program needs to tell the computer clearly what to do and in which order. The above example (taken from Rob Miles’ handbook „Begin to code with Python”) illustrates how ambiguous instructions formulated in human language can be for our computers. Your laptop (provided it could physically do so) would likely sip water out of the tub and then drink that cough syrup.

Exercise 1. Can I learn to code?

Basically, everyone can learn to write computer programs, although some people need more time than others. It is a myth that you have to be very good at math to write programs. In fact, programming rather relies on logic and problem solving skills. Math skills, however, help solve specific problems. Let’s see how well you understand computer language, here in the form of a pseudocode (instructions which only imitate real code). 

Read the code below and guess the proverb:

Proverb 1.

 

Proverb 2.

 

Proverb 3.

 

Proverb 4.

So, what is Python exactly?

  • Python is an interpreted scripting language − processed at runtime by the interpreter. You do not need to compile your program before executing it.
  • Python is interactive − using a Python prompt you can interact with the interpreter directly to write your programs.
  • Python is cross-platform – it can be used on Windows, Linux, macOS and Android operating systems.
  • Python is a high-level language – it provides high-level abstraction with data structures, semantics and syntax easy to understand by a human.
  • Python is Object-Oriented − supports Object-Oriented style or technique of programming that encapsulates code within objects.
  • Python is flexible − excellent both for the beginner-level programmers and experienced coders. It supports the development of a wide range of applications from simple text processing to websites, games and machine learning.
  • Python is free – you do not have to pay to be able to use it.

Where and how is Python used?

Python is a general purpose programming language, which means that it can be used to create a variety of different software/programs and that it is not specialized for any particular type of problems. Some programmers use Python to create web applications, some develop desktop or mobile apps, some use it for data analysis, building computational models and machine learning algorithms. Others take advantage of its simplicity and speed (in terms of program writing) and use it to create short scripts to automate their everyday work. The popularity of this programming language is reflected in the fact that many worldwide companies, such as Google, Netflix, Facebook and others provide software written in Python. In cognitive science Python is frequently used for data preprocessing, data manipulation, data visualization, and computational modeling.

Versions of Python

When starting your adventure with Python you need to be careful about which version of Python you choose. The first version of Python introduced in the early 90s is no longer used. But two versions – Python2 and Python3 are used in parallel. The differences between them (e.g. in syntax) may sometimes be substantial. However, Python2 is already much less frequently used and it will soon no longer be supported. So, basically, at the moment the only rational option is to learn Python3 and that will be our goal.

 

Online resources and self-education

Unboxing Python 3.n

When you install Python on you computer you actually install a bunch of different software including Python interpreter, standard library, Python shell, and usually some package manager.

Useful software (all free!) which helps coding in Python

There are dozens of additional useful applications which can make programming easier. Examples of such apps are presented below.

How to use Python editor

Programming in Python can be done in many different ways using many different so-called Integrated Development Environments (IDE). A good editor should be able to recognize and highlight the syntax (usually different colours and fonts are used for different categories of terms, i.e. numbers, text, variable names etc.) while you are typing your code, which gives you more control and allows you to catch some errors before running the program. The most commonly used IDEs are:

You are welcome to install and use one of them (there are hundreds of tutorials on the Internet). However, you can also use Python editors available online, such as the one provided by CodingGround. The most important features of this editor are presented in the picture below.

Programming styles in Python

Programming languages use different programming styles. Fortunately, Python is very flexible and allows the user to code the way they like. In practice, programmers usually use several styles in one program. Python supports following programming styles:

  • Imperative, which refers to a list of step-by-step instructions
  • Structured, which uses blocks of code that organize instructions
  • Procedural, which uses statements that change the state of the program
  • Functional, which uses expressions returning values
  • Object-oriented, which uses objects i.e high-level structures containing both information (attributes) and functions (methods)

Basic elements of Python language

Semantics

Semantics refers to individual words and symbols that have some particular meaning. Some of them, such as „round”, „+”, „if” or „=” are easy to understand, some become meaningful when you learn that they are abbreviations of existing words, e.g. „len” („length”), „def” („define”), „sqrt” („square root”). Others are more abstract and have more specific or special meaning e.g. „!=”, „list”, „{}”.

Syntax

Syntax, in turn, refers to the order and combination of words and symbols which create correctly structured expressions or statements. Just like a sentence is only meaningful if words are correctly ordered and combined with each other, expressions and statements can be understood by a Python interpreter if the elements of the semantics are arranged correctly.

Expressions and Statements

We already used these terms, so let us now explain their meaning in the context of programming. An expression is any valid unit of code that always resolves to a value, either by assigning it to a variable (e.g. a = 10) or evaluating an arithmetic or logical operation (e.g. 10 + 20, 5 > 1).

A statement is an instruction, an action, a part of a code whose execution leads to some specific effect (e.g. creating a variable). The statement which you will use most frequently is a print statement (which is technically a function). It is used to display a value (or multiple values) in the console e.g. the famous print("Hello world"). Print function takes values (placed inside round brackets) and displays the text in the output window. You can pass multiple values separating them with commas e.g. print("Number of cars:", 32, "Mean price:", 24000).

Python is case sensitive!

One of the first rules a Python adept should memorize is that Python differentiates between lower and upper case letters. It means that my_name and my_Name mean different things to Python.
At the beginning many problems with the code result from ignoring this rule by new „Pythonistas”.

Indentation

Spacing is important!

my code:
_further code

and

my code:
____further code

are not equivalent!
Indents (or leading spaces) are really important because they help Python understand the code. In Python we do not use curly braces (as e.g. in C++ or JavaScript) to include related parts of the code. Instead, we use indentation in a form of four spaces (for each level). This is frequently the reason for beginner’s frustration, especially when he/she tries to copy and paste a fragment of a code from a website or (even worse) from a text editor, such as MS Word which formats the text in a way that is not accepted by a Python interpreter.

Comments

Comments include a part of code that will be ignored by the interpreter. Use comments to describe what a particular part of your program is supposed to do (this will save your time in future when you finally decide to finish or to modify your program).

Single-line comment:

Multiple-line comment (however, technically Python does not support multiple-line comments…):

or

Errors and Exceptions

Errors and exceptions will be your daily bread. Just get used to it. Typos, wrong indents, undeclared variables – it happens all the time even to much more experienced programmers. It is, therefore, crucial to understand what the interpreter is trying to tell us. One of the best ways to control what is going on in your program is to use print() statements. This gives us tons of information – e.g. does a variable have the value that we expected it to have? Has a particular part of the code been executed at all? Etc. etc. So, the print() statement is actually the first instruction that we need to learn. Plus, do not ignore the messages spitted out by the interpreter. Find the problem and handle it.

Syntax errors occur when Python can’t interpret your code, since you didn’t follow the correct syntax for Python. These are errors you are likely to get when you make a typo, or you are first starting to learn Python. Important! The code will not be executed (Python checks syntax before running the program). For example, if you try to execute this code:

you will see a following message from the interpreter:

File "main.py", line 1
print "Some text"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Some text")?

Apparently, there are missing parentheses in the print() statement. BTW, this code will be perfectly fine in Python2!

Exceptions occur when unexpected things happen during execution of your program, even if the code is syntactically correct. There are different types of built-in exceptions in Python, and you can see which exception is thrown in the error message. Important! The code will be executed but will be stopped when it encounters an exception. For example, if you try to execute this code:

you will receive a following message from the interpreter:

Traceback (most recent call last):
File "main.py", line 1, in <module>
print(my_variable)
NameError: name 'my_variable' is not defined

Here, The syntax is OK, but there is no such variable as my_variable !

Another example:

and the message from the interpreter:

Traceback (most recent call last):
File "main.py", line 1, in <module>
my_variable = 5 / 0
ZeroDivisionError: division by zero

Here we try to divide by 0!

 

Declaring variables

Variables are the names we give to computer memory locations. These locations will store values (e.g. numbers) in a computer program. We may want to store values in our program to use them later. There are basically three steps:

  1. We create (or in other words, declare) a variable with a chosen name (e.g. my_age).
  2. We store a value in this variable using the assignment operator = (e.g. my_age = 21).
  3. We retrieve and use the stored values from this variable e.g. to make some calculations (e.g. my_age + 1).

In Python we do not have to specify a particular data type when declaring a variable, like we do in Java or C++ languages. Python will recognize whether it is a number or a string of characters, or some data collection, basing only on the assigned value. However, be careful when giving a name to your variable. You should not use any reserved keyword used by Python. Otherwise, you may face some unexpected problems and unexpected behaviors of your program.

Keywords in Python (avoid using them as variable names!):

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

Use „snake case” names (separating words with an underscore, e.g. user_name). Use names that are meaningful (e.g. person_age_years) but not too long (e.g. last_time_i_saw_my_uncle_steven). Always use lower-case characters in variable names. Python will not prevent you from using capital letters, but be aware that they have a different meaning. We usually use capital letters to name constants and classes.

Exercise 2.

Use your Python editor to:

  1. Declare variables (and assign values to them) for:
    • Number of books respondents have read during this year
    • Name of pet’s favorite toy
    • Mean height of skyscrapers in New York city
    • Minimum age required to buy alcohol
    • Whether a person is a supporter of the flat earth theory
  2. Print each of the variables using print() statement

How is data represented? Primitive data types.

In Python, data  can be represented in many different ways depending on whether it refers to numbers, text (characters) or logical values.

Numeric data types: int

Used for integers (whole numbers)

Numeric data types: float

Used for integers or decimal values (i.e. floating point numbers). As a decimal point always use a dot, not a comma.

Arithmetic Operators in Python

These operators are used to perform common mathematical operations on values (or variables).

a = 10

b = 20

Operator Description Example
+ Adds values on either side of the operator. a + b = 30
Subtracts right hand operand from left hand operand. a – b = -10
* Multiplies values on either side of the operator a * b = 200
/ Divides left hand operand by right hand operand b / a = 2
% „Modulus” divides left hand operand by right hand operand and returns remainder b % a = 0
** Performs exponential (power) calculation on operators a**b =10 to the power 20
// Floor Division – The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) −

9//2 = 4

-11//3 = -4

Exercise 3.

My coffee bills for the last three months are: 54 €, 76 € and 68 €. What was the average monthly cost of my coffee consumption over the three month period? Write an expression to calculate the mean (using only arithmetic operators!), and use print() statement to view the result. When assigning a value, ignore the currency symbol, e.g. coffee_bill_january = 54

Textual data type: string

Used for sequences of characters (letters, digits, signs). Strings should always be contained in quotation marks.

Notice that " " is also a string which, in this case, contains only one space (which is a character just like any other).

Exercise 4.

Create a single string variable that will contain the resume of your personal data (like in a code below). Use concatenation to „glue” separate strings.

Logical data type (boolean): bool

Booleans can only have one of the two values: True / False
Booleans are frequently used in conditional statements (so-called „if statements”).

The variable x will be of boolean type, because we assign the result of a comparison, which can be either True or False

Comparison Operators

These operators are used to compare two values (or variables). The result of this comparison is always either True of False.

a = 10

b = 20

Operator Description Example
== If the values of two operands are equal, then the condition becomes true. (a == b) is False
!= If values of two operands are not equal, then condition becomes true. (a != b) is True
> If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is False
< If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is True
>= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is False
<= If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is True

Exercise 5.

Long-finned pilot whales are known for having big brains, especially their neocortical part. However, the factor that may play a major role in cognitive abilities is rather the density of nerve cells than just their number. Write a code to compare neuron densities of whales and humans using the data provided. The number of neurons in the neocortex has been given in millions, while the volume of this structure is presented as cm3. Use the variables created to store the results of your calculations and replace the comments with proper code. The variable is_human_cortex_denser should be of boolean type (i.e., True or False).

What you have learned so far?

  • Python is a scripting programming language
  • There are different versions of Python
  • There is a lot of online resources for learning Python
  • There is a lot of free software that helps develop Python programs/apps
  • Errors and exceptions occur frequently, and they need to be analyzed and anticipated
  • There are 4 basic data types in Python: integers, floats, strings, and booleans
  • Good practices in programming really matter

What next?

The content of this mini-course covers all the material required for the entrance exam. However, if you want to go further and learn more, here are some self-study tips:

  • read and analyze code samples but also practice coding (e.g. by doing exercises) as often as possible
  • feel free to experiment with the code (try to change different things and observe results)
  • type the code in the editor, instead of copying and pasting
  • use the official Python documentation on https://docs.python.org/3/
  • read the Zen of Python