DS T02 - Your First Computer Program, and Using Variables
DS T02 - Your First Computer Program, and Using Variables
In this task, you are introduced to the Python programming language. Python is a
widely used programming language. It is consistently ranked in the top 10 most
popular programming languages as measured by the TIOBE Programming
Community Index. Many familiar organisations make use of Python, such as
Wikipedia, Google, Yahoo!, NASA, and Reddit (which is written entirely in Python).
This task is a gentle introduction to Python, where you will be asked to create a
simple program. In doing so, you will become familiar with the structure of a
Python program.
You will also be introduced to the concept of variables and more complex
programming problems that can be solved using these. A variable is a computer
programming term that is used to refer to the storage locations for data in a
program. Each variable has a name which can be used to refer to some stored
information known as a value. By completing this task you will gain an
understanding of variables and how to declare and assign values to them, as well
as the different types of variables and how to convert between types.
Remember that with our courses, you’re not alone! You can contact an expert code
reviewer to get support on any aspect of your course.
Hope you’re excited to start learning such a popular and fun programming language!
● Simple, yet powerful: looking at languages like C++ and Java can flummox
and scare the beginner. But Python is intuitive, with a natural way of
presenting code. Python’s succinctness and economy of language allows for
speedy development and less hassle over useful tasks. This makes Python
easy on the eyes and mind.
● Even Dropbox was built using Python: Dropbox must save massive
quantities of files while supporting massive amounts of user growth. 99.9%
of Dropbox code is written in Python! Using Python has helped Dropbox
gain more than a hundred million users. Using only a few hundred lines of
Python code, they were able to scale up massively in user numbers. Learn
from Dropbox and use Python!
ZEN OF PYTHON
The Zen of Python, written in 1999 by Tim Peters, mentions all the software
principles that influence the design of the Python language.
Ever need to recall these principles? Try entering this into your Python
interpreter:
import this
Know this – Python is hot!
The demand for Python programmers is only growing. Python boasts the highest
year-on-year increase in terms of demand by employers (as reflected in job descriptions put
up online) as well as popularity among developers. Python developers are one of the
highest-paid categories of programmers! The demand for Python is only set to grow further
with its extensive use in analytics, data science, and machine learning.
Before you get started, we suggest you use Virtual Studio (VS) Code to open all text
files (.txt) and Python files (.py). Do not use the normal Windows notepad for
reading code files.
Your content folder contains a sub-folder named “Installers” which will help you
download and set up Python on your machine.
1. Visit https://code.visualstudio.com/
2. Download the version of VS Code that matches your operating system (OS).
Alternatively, you can follow the instructions stated at the following links for
the corresponding operating system families:
a. macOS: https://code.visualstudio.com/docs/setup/mac
b. Linux: https://code.visualstudio.com/docs/setup/linux
c. Windows: https://code.visualstudio.com/docs/setup/windows
3. Unix-like operating systems such as macOS and Linux often come with a
pre-installed version of Python. It is generally discouraged to use the
distributions of Python that are shipped with macOS as they may either be
outdated or have customisations that might give you issues further down
the line. Please follow the guidelines at:
https://code.visualstudio.com/docs/python/python-tutorial.
a. Ensure that if you are on Windows or macOS, you have installed the
latest stable version of Python using the prescribed means on the link
above.
b. Ensure that if you are on Linux and the prepackaged Python version
is not the latest stable version, you get a package provider for your
operating system that uses the latest stable version. Being behind by
1 or 2 minor versions is fine on operating systems such as Fedora.
However, on operating systems such as Ubuntu, we strongly
recommend that you use a PPA (Personal Package Archive) such as
https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa.
c. For all operating systems, ensure that your environment paths are
up-to-date with regards to your installation.
d. Per the guidelines linked above, ensure that you install the latest
stable version of Microsoft’s Python extension available from
https://marketplace.visualstudio.com/items?itemName=ms-pyth
on.python so that you get tooltips and other useful tooling that help
you as your program.
4. Use the compulsory task to ensure that your setup is working as expected. If
unsure, please check with an academic staff member or a peer.
6. There are a range of other editors that you can use such as Vi, emacs,
Notepad++, and PyCharm, but we cannot guarantee that your peers will be
familiar enough with them to assist you with them or that the academic
staff members will be able to consistently review your work.
7. If you’re concerned about opt-out telemetry with Visual Studio Code, please
turn it off by using the instructions from:
https://code.visualstudio.com/docs/getstarted/telemetry#_disable-tele
metry-reporting.
WHAT IS PROGRAMMING?
After writing Python commands or code, you need to save them in a Python file. A
Python file has the following file naming format:
filename.py
The filename can be any valid filename and .py is the file extension.
You can then 'run' the Python file. In this process, the Python program you have
written is executed and displays the outcomes that may result based on what the
code statements say. Information about how to 'run' Python files is given in the
example file (example.py) that accompanies this task. We will now show you how
to write some basic code in Python, and perform some basic operations.
You may want your program to display or output information to the user. The most
common way to view program output is to use the print function. In this
explanation we’re going to talk about two new concepts, parameters and
arguments. A parameter is a variable in a method definition. When a method is
actually called, the arguments are the data you pass into the method's
parameters.
To use print, we enter the print command followed by one or more arguments in
brackets. In programming, a command is an instruction given by a user telling a
computer to do something. Together a command and an argument are known as
a statement. Consider the Python statement below:
print("Hello, World!")
When you run this program, the computer will output the argument “Hello,
World!” that was passed in to the input parameter. Note that the argument is
enclosed in double quotes ("..."). This is because "Hello, World!" is a string or a list of
characters. These are data types that will be discussed in more detail in later tasks.
The Python Shell (the window that is displayed when you run a Python program)
only shows the output of the program. Other statements in your code will be
executed but not displayed in the Python Shell.
SYNTAX RULES
All programming languages have syntax rules. Syntax is the "spelling and
grammar rules" of a programming language and determines how you write
correct, well-formed statements.
A common syntax error you could make above is forgetting to add a closing
quotation mark ("). Remember that all opening quotation marks (") require a
closing one! Another common syntax error that you could make in the above
example is forgetting to add a closing bracket ‘)’. Remember that all opening
brackets ‘(’ require a matching closing one, ‘)’!
Any program you write must be exactly correct. All code is case sensitive. This
means that ‘Print’ is not the same as ‘print’. If you enter an invalid Python
command, misspell a command, or misplace a punctuation mark, you will get a
syntax error when trying to run your Python program.
Errors appear in the Python shell when you try to run a program and it fails. Be sure
to read all errors carefully to discover what the problem is. Error reports in the
Python shell will even tell you what line of your program had an error. The process
of resolving errors in code is known as debugging.
Sorry to interrupt, but did you know that the first computer “bug” was named after a real
bug? Yes, you read that right! While the term “bug” in the meaning of a technical error
was first coined by Thomas Edison in 1878, it was only 60 years later that someone else
popularised the term.
In 1947, Grace Hopper, a US Navy admiral, recorded the first computer ‘bug’ in her
logbook as she was working on a Mark II computer. A moth was discovered stuck in a
relay and thus hindering the operation. She proceeded to remove the moth, thereby
‘debugging’ the system, and taped it in her logbook. In her notes, she wrote, “First actual
case of bug being found.”
Sometimes you want a user to enter data that will be used by your program
through the keyboard. To do this, use the input command.
The input command, in the example below, will show the text "Enter your name: "
in the output box of the program. The program will then halt until the user enters
something with their keyboard and presses enter.
Now that you are a little more familiar with Python and creating basic programs, we would
like to show you some stuff to help you on your journey to becoming a seasoned
programmer.
Creating excellent content requires good tools and equipment. This applies equally well to
programming. There are some great tools and resources available online that you can start
using as soon as possible, if you have not already, to make the coding process just that
much more convenient. Here is a link to the Hyperion Blog where you will find essential
utilities and resources for programmers.
In Python, we use the following code to create a variable and assign a value to it:
variable_name = value_you_want_to_store
Check out this example:
num = 2
In the code above, the variable named num is assigned the integer or whole
number 2. Hereafter when you type the word num, the program will refer to the
appropriate space in memory and retrieve the value 2 that is stored there.
We use variables in calculations to hold values that can be changed. You can name
a variable anything you like as long as you follow the rules shown below. However,
as previously stated, it is good practice to give your variables meaningful names.
It is very important to give variables descriptive names that reference the value being
stored. Here are the naming rules:
1. Variable names must start with a letter or an underscore.
2. The remainder of the variable name can consist of letters, numbers and
underscores.
3. Variable names are case sensitive so Number and number are each different
variable names.
4. You cannot use a Python keyword (reserved word) as a variable name. A reserved
word has a fixed meaning and cannot be redefined by the programmer. For
example, you would not be allowed to name a variable print since Python already
recognises this as a keyword.
The way you write variable names will vary depending on the programming language
you are using. For example, the Java style guide recommends the use of camel case —
where the first letter is lowercase, but each subsequent word is capitalised with no spaces
in between (e.g. thisIsAGoodExampleOfCamelCase)
The style guide provided for Python code, PEP 8, recommends the use of snake case — all
lowercase with underscores in between instead of spaces (e.g.
this_is_a_good_example_of_snake_case). You should use this type of variable naming for
your Python tasks.
In maths, variables only deal with numbers, but in programming we have many
different types of variables and each variable type deals with a specific type of
information.
There are five major types of data that variables can store. These are strings, chars,
integers, floats, and booleans.
● char: Short for character. A char is a single letter, number, punctuation mark
or any other special character. It can be used for storing the grade symbol
(A-F) of a pupil, for example.
● float: We make use of a float data type when working with numbers that
contain decimals. For example, it can be used to store measurements or
monetary amounts.
● boolean: Can only store one of two values, namely TRUE or FALSE.
The situation you are faced with will determine which variable you need to use. For
example, when dealing with money or mathematical calculations you would likely
use integers or floats. When dealing with sentences or displaying instructions to
the user you would make use of strings. When dealing with decisions that have
only two possible outcomes we would use booleans, as the scenario could only
either be True or False.
Variables store data and the type of data that is stored by a variable is intuitively
called the data type. In Python, we do not have to declare the data type of the
variable when we declare the variable. This is known as “weak-typing”. This is
because Python detects the variable's data type by reading how data is assigned to
the variable:
● strings are detected by quotation marks " ".
● integers are detected by the lack of quotation marks and the presence of
digits or other whole numbers.
● floats are detected by the presence of decimal point numbers.
● booleans are detected by either True or False.
So, if you enter numbers, Python will automatically know you are using integers or
floats. If you enter a sentence, Python will detect that it is storing a string.
Take heed that types can be converted from one to another. You need to take care
when setting a string with numerical information.
number_str = "10"
print(number_str*2) #Prints 1010- prints string twice
print(int(number_str)*2) #Prints 20 because the string 10 is cast to number 10
Watch out here! Since you defined 10 within quotation marks, Python figures this is
a string. It's not stored as an integer even though 10 is a number, as numbers can
also be made into a string if you put them between quotation marks. Now,
because 10 is declared as a string here, we will be unable to do any arithmetic
calculations with it — the program treats it as if the numbers are letters. In the
above example, when we ask Python to print the string times 2, it helpfully prints
the string twice. If we want to print the value of the number 10 times 2, we have to
cast the string variable to an integer by writing int(number_string). We’ll explain
this further in the next section!
There is also a way that you can determine what data type a variable is: with the
type() built-in function. For example:
mystery_1 = "10"
mystery_2 = 10.6
mystery_3 = "ten"
mystery_4 = True
print(type(mystery_1))
print(type(mystery_2))
print(type(mystery_3))
print(type(mystery_4))
Output:
<class 'str'>
<class 'int'>
<class 'str'>
<class 'bool'>
The output shows us the data type of each variable in the inverted commas.
CASTING
In the string printing example above, you saw something we called casting.
Casting basically means taking a variable of one particular data type and “turning
it into” another data type. Putting the 10 in quotation marks will automatically
convert it into a string, but there is a more formal way to change between variable
types. This is known as casting or type conversion.
Casting in Python is pretty simple to do. All you need to know is which data type
you want it to convert to and then use the corresponding function.
● str() — converts variable to a string
● int() — converts variable to an integer
● float() — converts variable to a float
number = 30
number_str = "10"
print(number + int(number_str)) #Prints 40
This example converts number_str into an integer so that we can add two integers
together and print the total. We cannot add a string and an integer together.
You can also convert the variable type entered via input(). By default, anything
entered into an input() is a string. To convert input to a different data type, simply
use the desired casting function.
When writing programs, you'll have to decide what variables you will need.
Take note of what is in the brackets on line 4 above. When working with strings, we
are able to put variables into our strings with the format method. To do this, we use
curly braces { } as placeholders for our values.
Then, after the string, we put .format(variable_name). When the code runs, the
curly braces/brackets will be replaced by the value in the variable specified in the
brackets after the format method. You will learn more about this in the next task.
Let’s briefly turn our attention to the benefits of using the f-string in comparison to
the format method.
The syntax for working with the f-string is quite similar to what is shown above in
the format method. Notice that we declare the variables upfront and we don’t
need to tag on the .format method at the end of our string. Also note the f at the
beginning of the string:
num_days = 28
pay_per_day = 50
print(f"I worked {num_days} days this month. I earned ${pay_per_day} per
day.")
Output:
f-strings provide a less verbose way of interpolating values inside string literals. If
you’d like to learn a little more about f-strings, you can read more about them
here.
print("You worked {0} this month and earned ${1} per day".format(num_days = 22,
pay_per_day = 50))
print("You worked {} this month and earned ${} per day".format(num_days = 22,
pay_per_day = 50))
Alan Turing (1912 – 1954) was a British mathematician, logician, and cryptographer. He is
considered by many to be the father of modern computer science. He designed and built
some of the earliest electronic, programmable, digital computers.
During the Second World War, Alan Turing was recruited by the military to head a
classified mission at Bletchley Park. This mission was to crack the Nazi’s Enigma machine
code which was used to send secret military messages. Many historians believe that
breaking the Enigma code was key to bringing the war to an end in Europe. Turing
published a paper in 1936 that is now recognised as the foundation of computer science.
Source: Wikipedia
Instructions
This lesson is continued in the example.py file provided in this task folder. Open
this file using VS Code. The context and examples provided in example.py should
help you understand some simple basics of Python.
You may run example.py to see the output. The instructions on how to do this are
inside the file. Feel free to write and run your own example code before attempting
the task, to become more comfortable with Python.
Try to write comments in your code to explain what you are doing in your program
(read the example.py file for more information).
You are not required to read the entirety of Additional Reading.pdf. It is purely for
extra reference. That said, don’t simply disregard it!
Compulsory Task 1
Compulsory Task 3
If you are having any difficulties, please feel free to contact our specialist team
on Discord for support.
Thing(s) to look out for:
1. Make sure that you have installed and set up all programs correctly. You have set
up Dropbox correctly if you are reading this, but Python or your editor may not
be installed correctly.
2. If you are not using Windows, please ask one of our expert code reviewers for
alternative instructions.
Hyperion strives to provide internationally-excellent course content that helps you achieve
your learning outcomes.
Think that the content of this task, or this course as a whole, can be improved, or think
we’ve done a good job?