Introduction To Pythons Syntax
Introduction To Pythons Syntax
net/publication/350209611
CITATIONS READS
0 9,888
4 authors:
All content following this page was uploaded by Kinsey Church on 14 May 2021.
Abstract This tutorial is the second in our series and covers basic syntax in Python with examples Acting Editor
related to psychology. The aim is to teach programming beginners and experts alike the funda- Nareg Berberian
(University of Ot-
mentals required in order to smooth the learning curve and succeed with integrating Python with
tawa)
their research. It starts by covering basic built-in functions and variable creation. Next, different
data types and data structures that you will encounter are covered detail, followed by comments Reviewers
Matias Calderini
and best commenting practices. Finally, indentation, logic, conditional statements, and loops are all
explained with simple, illustrative examples. The tutorial ends with a comprehensive example of
the same-different task from cognition that ties together everything learned. With this foundation,
the reader will gain the confidence to begin practicing Python on their own and think of ways to
incorporate it into their own research and daily lives.
Keywords Python, Psychology, syntax. Tools Python.
B KCHUR026@uottawa.ca
10.20982/tqmp.17.1.S001
and the results should be identical to Fig. 2. Congratula- • Avoid using Python’s predefined function names as
tions, you have created your first few variables! variable names, such as the word “print”.
Note: You may have noticed that different colours have • Variable names should be short but descriptive. For ex-
appeared in your notebook. These colours are used to ample, name is better than n and student_name is better
help differentiate between data types. Just as nouns, verbs than s_n. Once you start building very long scripts, you
and adjectives are all different and have special uses in a may start to lose track of what some of your variables
phrase, so are the variables, strings and functions (just to mean. Good coding practice includes naming your vari-
name a few) in a script. Table 1 sums up the meaning of ables something meaningful to improve readibility for
each default colour for three popular IDEs. yourself and others.
Creating variables is very important for saving and Now that you have a better understanding of what vari-
reusing information. Think of creating an experiment ables are, let’s dive into the specific data types that can be
where in each trial you must display the same prompt to saved and stored.
your participants. Instead of having to copy/paste your en-
Data Types
tire prompt for each trial, you can save it as a variable and
use it repeatedly. This allows you to save time and avoid There are several different data types that are available in
lengthy code. In Python, you can attribute a variety of in- Python, each with its own utility. Outlined below are the
formation to variables, such as numbers, phrases and even four most common data types you will encounter. For each
entire functions. That being said, there are a few important one, a quick explanation and a simple example of how it
tips to remember when creating a variable: may pertain to research in psychology can be found. Let’s
• Spaces are not allowed in variable names, but under- begin learning the ABCs of Python!
scores are commonly used to separate words. For ex-
Strings
ample, psychology_rocks works, but psychology rocks
will cause an error. A string is a sequence of characters, anything that you
• Variable names can contain only letters, numbers, and type (a letter, a number, a symbol, or a space), enclosed in
underscores. Most importantly, they cannot start with ‘single’ or “double” quotation marks. An example of how
a number. For instance, you can call a variable Ban- strings can be used is when a researcher records a sub-
dura_1 but not 1_Bandura. ject’s response to the open ended question “How has your
depression been affecting your life?” (see Fig. 3.). Strings types can even be mixed within the same list. An exam-
are immutable, which means that you cannot change the ple of a list would be for storing IQ scores for a group of
contents of a string after it has been created, you can only participants, where the position of the score in the list (in-
write over it (redefine the variable). dex) matches the participant’s identification number (See
Fig.9.).
Integers
Since lists are ordered, you can use indexing to re-
Integers are positive or negative whole numbers (no deci- trieve information from a specific position in a list by using
mal point). An example of this could be how a researcher square brackets after the variable name. Indexing in the
in the field of neuroscience would count the number of ac- Python language starts at 0, meaning the first object in a
tive neurons at a given time (see Fig. 4.). list is 0, the second is 1, etc. For example, if a researcher is
interested in the first participant’s IQ score, they could use
Floats
IQ_scores[0] to retrieve the first object in that list (see Fig.
Floats, or float point real values, are real numbers (includ- 10.).
ing numbers with a decimal point). An example of a float
Tuple
would be recording a participant’s reaction time in mil-
liseconds to a given task (see Fig. 5.). Tuples are similar to lists, as they are ordered sequences of
Note: In certain cases, you may encounter floats or inte- objects. However, they are immutable (cannot be altered,
gers as either 32 or 64 bit. This simply refers to the num- only overwritten) and are delimited by ( ). A benefit of cre-
ber of bits you are limiting the number to be. Essentially, ating an immutable object is that they take up less space
float64 has double the number of values after the decimal in the computer system’s memory. An example of a tuple
point and requires more bits than float32. would be storing an individual participant’s reaction time
and whether they are part of the control group or not (see
Booleans
Fig. 11.).
Booleans are also known as logical expressions, meaning
Dictionary
that they are evaluated as True or False (1 or 0). An ex-
ample would be responses to a questionnaire whereby a Dictionaries are similar to sets as they are unordered, but
participant indicates positively or negatively to experienc- they are a little different. They have a unique format that
ing anxiety or depression (see Fig. 6.). allows them to be accessed in a similar way to indexing.
At any time, the type of data stored in a variable can be Dictionnaries use objects known as “keys” to retrieve other
easily checked using the built-in type() function. The out- stored objects, known as “values”. In a dictionnary, these
put from this function will indicate the data type (see Fig. “keys” cannot be repeated (duplicates), but the “values”
7.). stored inside can be repeated as much as needed. In addi-
tion, the objects are mutable, meaning that your code can
Data Structures
update and change these values when specified to do so.
If data types are the ABCs of Python, then data structures An example where a researcher might use a dictionary is
would be words. They define how your variables are struc- for storing information about different species of rodents,
tured and show how to store multiple data types in the like whether a particular species of rodent has a specific
same variable. Outlined below are four data structures gene or not and their average weight in grams. To achieve
that you will encounter while coding. this, the researcher would create an empty dictionary for
Rodent_species using {}. They could then create a “key” for
Set
each species of rodent and create a map that indicates var-
A set is a group of objects that is unordered, where no du- ious characteristics (or “values”) that are specific to that
plicates are allowed. Delimited by { }, sets can be used to species, such as the presence of a gene and the average
store objects of any data type (string, integers, etc.). An ex- weight (see Fig. 12.).
ample would be creating a set for storing the symptoms of To access specific information in a dictionary, similar
a particular disorder, such as ADHD (American Psychiatric to indexing, square brackets are used. However, instead of
Association, 2000), where the order of symptoms is not im- a numeric value indicating position, the “key” is used, as
portant (see Fig. 8.). dictionaries are unordered. Relating back to the previous
example, if a researcher had a dictionary of rodent species
List
with relevant information stored, but was only interested
Lists are ordered sequences of objects that are delimited in the Mus musculus species, they could specify this “key”
by [ ]. Lists may contain objects of any data type, and data and retrieve all the mapped “values” related to this species
(see Fig. 13.). ferent sections are all part of the same function, they would
Note: For a summary of all the different data structures, be found in the same block. In order to define these blocks,
see Table 2 in the appendix. many languages use curly brackets {}, but Python uses in-
dentation. This means that each line pertaining to a block
Comments in Python
is indented by the same amount to the right. It is also pos-
In order to stay organized, Python’s programming lan- sible to indent multiple times, effectively combining multi-
guage provide users with an easy way to label or annotate ple blocks of code, embedding one within another. This
sections of their code. Referred to as a comment, these can is known as nesting and helps the software understand
be used to remind yourself what a certain section of code which sections of your code take priority. Fun fact: This
is doing and label this information. This is specifically use- is where Python gets its name! Once your script is large
ful if you are working with others. Python will completely and involves several blocks of code, it will start to look like
ignore your comments, meaning that they will not change a snake slithering due to the indentation. You will see this
the way the code is run or interpreted. This means you effect of indentation for the rest of this tutorial.
can use comments to isolate certain lines of code temporar-
Logic in Python
ily and verify if it is working as intended. The main way
to comment in Python is to use the hash mark (#). Com- As per any other programming language, Python has vari-
mon practice is to use these comments on a separate line ous ways of activating certain blocks of codes (conditional,
or inline with other code. See Figure 14 for an example of if, elif and else statements). For instance, if you have a
how comments can be used to clarify some of the examples block of code that should only activate if a participant’s
given above. name is provided, you can do so by using conditional and
Note: It is a very important habit to always write com- logical statements. These are special types of code that al-
ments in your code. As time progresses, your skill low any user to incorporate logic into their program. Think
will change and you will forget what certain variable’s of mathematical conditions, such as the symbols <, >, if,
acronyms mean as well as what some functions are doing. etc., these can all be used to determine which block of code
Commenting will save you time in the long run and will should be executed. When checking if the coding condi-
avoid future confusion. Also, commenting is very useful tions are met, booleans are employed that either return a
for others that are trying to use or replicate your code. True or False value. This determines if the block of code
should be executed (True) or not (False). To make this
Indentation
more concrete, let’s dive into a few examples to see how
A block of code is related lines of code that are grouped they work.
together for a specific purpose. For example, if several dif-
loop and continue iterating through your code. There are complex tasks. If we combine our two previous examples,
also pass statements. These act as placeholders that tell the we can nest a for loop within a while loop. In this ex-
program to do nothing. Essentially they are a null opera- ample, a researcher has a survey that is incomplete. The
tion that fulfill the entry requirements of statements, loops while loop will continue until the survey is completed.
or functions. Nested within this loop is a for loop that iterates through
each question in the survey and prints the current question
For Loops
number. An if statement is then used to determine when
For loops in Python are used for iterating over a sequence, the questionnaire has reached the fifth and final question
such as lists, dictionaries, strings, etc. They can be used to (end of the for loop), thus completing the survey and end-
execute a series of statements a fixed number of times. As ing the while loop.
in while loops, the break, continue, and pass statements
A Comprehensive Example
are all still very useful. Another useful function when us-
ing for loops is range(). The range function can be used in Now that you are familiar with the basics of Python, we can
a for loop to execute the loop a specific amount of times. build upon our knowledge and create simple yet very pow-
For instance, if a researcher wanted to iterate through a erful scripts. In this tutorial, we have explained many dif-
questionnaire, they could use a for loop and the range ferent concepts, but in order to summarize them and fully
function to iterate a defined number of times over a list, as display the possibilities for your research in psychology,
seen in Fig.19. The logic behind this example can be trans- we will tackle a comprehensive example (see Fig. 21). The
lated as follows: For each question ranging from 0 to 4 (re- goal will be to create a general purpose corrector that can
member, Python starts at 0 not 1) the for loop will print out be used either for questionnaires, exams, or other similar
the current iteration as the question number. tasks in psychology. In this particular example, we will use
Loops can also be nested in order to perform more fictional results from the same-different task found in cog-
nition. That being said, it is important to remember that to the Marking list. Our goal was to use the Marking list
this code could easily be adapted and expanded to accom- after the loops finished in order to calculate the average
modate any type of questionnaires, exams, or tasks. of correct responses. We also added an else for when the
To begin, we created a variable called Answer_key and participant’s answer was incorrect. If that was the case,
assigned a list containing the correct responses to the task the program would print the trial number followed by “In-
to it. Then, we created a second variable called Partici- correct”. We also added “0” to the Marking list by using
pant_responses and assigned it a list containing the partic- .append().
ipant’s responses. Next, we created an empty list, called To verify if our code should end and display our re-
Marking, to be used to store the Participant_responses as sults, we created an if statement that checked if the trial
either a 1 for correct or 0 for incorrect. To ensure that we value was equal to the last index of our Answer_key. If
properly iterated/looped over all the answers, we created the loop had reached the last trial, it would change the
a variable called Total_trials that was based on how many task_complete value from False to True, thus ending the
answers were in the Answer_key (5) to use as one of the while loop. To ensure that our while loop concluded its
ending conditions for our while loop. Lastly we created a function, we added a print out a message saying that the
variable called task_complete and gave it a False value so same-different task was completed. As any good corrector,
the while loop would run. we wanted to add the possibility to see the calculated aver-
Once all variables were defined, we created our while age of correct responses for a given participant. Thus, we
loop. Directly inside of the while loop, we created a nested created a variable called Total_correct which contained the
for loop that was set up to cycle through each trial and ex- sums of all of the answers found in the Marking list. This
ecute our desired operation. By using the range() function was done by using the sum() function. The average was
we defined that the for loop would execute the code up un- then calculated by dividing the Total_correct variable by
til the Total_trials corresponding value (previously set to the Total_trials variable and was stored in a new variable
5). To create our operation/conditional statement, we used called Avg_Correct. To ensure that the user would be able
the first if statement to check if the participant’s response to see the participant’s average as well as to thank them for
matched the answer in the answer key for that trial. If a using our program, we added two lines of code printing out
match was found, the script would print the trial number the average and our message.
followed by “Correct”. To print the trial number, the str() Note: As mentioned before, this code can be easily
function was used to convert the number into a string so adapted to any similar tasks such as marking question-
it could be printed with the other strings. We then added naires or exams. It can also be scaled to iterate over a large
the instruction to use the .append() function to add a “1” number of participants or to handle other types of datasets.
Summerfield, M. (2010). Programming in python 3: A com- Van Rossum, G., & Drake, F. L. (2011). The Python language
plete introduction to the Python language. Addison- reference manual. Network Theory Ltd.
Wesley Professional.
Appendix
Table 2 shows the basic comparisons between the different variable types discussed in this tutorial. Ordered means that
they have an order. In other words, they will always be displayed in the same order. Changeable (or mutable) means
that the object can be changed after it is created. Indexing means the variable type has a built-in indexing system, such
as an index key for each value. Duplicates means the variable type allows for duplicate members.
Citation
Church, K., Rolon-Mérette, T., Ross, M., & Rolon-Mérette, D. (2021). Introduction to Python’s syntax. The Quantitative Meth-
ods for Psychology, 17(1), S1–S12. doi:10.20982/tqmp.17.1.S001
Copyright © 2021, Church, Rolon-Mérette, Ross, and Rolon-Mérette. This is an open-access article distributed under the terms of the Creative Commons
Attribution License (CC BY). The use, distribution or reproduction in other forums is permitted, provided the original author(s) or licensor are credited
and that the original publication in this journal is cited, in accordance with accepted academic practice. No use, distribution or reproduction is
permitted which does not comply with these terms.