Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
48 views

DS T02 - Your First Computer Program, and Using Variables

This document provides an introduction to programming with Python. It discusses what programming is, introduces Python as a programming language, and explains variables as a way to store and refer to data in a program. It then provides instructions for installing Visual Studio Code and setting up a development environment for Python programming.

Uploaded by

Noemi Cristescu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

DS T02 - Your First Computer Program, and Using Variables

This document provides an introduction to programming with Python. It discusses what programming is, introduces Python as a programming language, and explains variables as a way to store and refer to data in a program. It then provides instructions for installing Visual Studio Code and setting up a development environment for Python programming.

Uploaded by

Noemi Cristescu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

TASK

Your First Computer


Program, and Using
Variables
Introduction
WELCOME TO THE TASK ON 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).

Python is a high-level programming language, along with other popular


languages such as Java, C#, and Ruby. High-level programming languages are
closer to human languages than machine code. They're called "high-level" as they
are several steps removed from the actual code that runs on a computer's
processor.

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.

The best way to get help is to login to Discord at https://discord.com/invite/hyperdev


where our specialist team is ready to support you.
Our team is happy to offer you support that is tailored to your individual career or
education needs. Do not hesitate to ask a question or for additional support!

Hope you’re excited to start learning such a popular and fun programming language!

A brief history of Python:


Python is named after the Monty Python comedy group. It was created by ‘Benevolent
Dictator For Life’ Guido van Rossum in 1991, who now works for Dropbox. At the time when
Guido van Rossum began implementing the Python language, he was also reading the
published scripts from Monty Python's Flying Circus (a BBC comedy series from the
seventies). His inspiration for Python stemmed from the desire to create a simple scripting
language and his experience with the ABC programming language.

Guido van Rossum


WHY PYTHON?

Python is a powerful, widely used programming language. Unlike Java, Python is a


more recent, efficient, and arguably faster programming language. The syntax (the
way the code is written) is very similar to Java.

Here are a few more reasons to use Python:

● 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.

● From child’s play to big business: while Python is simple enough to be


learned quickly (even by kids), it is also powerful enough to drive many big
businesses. Python is used by some of the biggest tech firms such as
Google, Yahoo!, Instagram, Spotify, and Dropbox, which should speak
volumes about the job opportunities out there for Python developers.

● Python is on the web: Python is a very appealing language of choice for


web development. Sites such as Pinterest and Instagram make use of the
versatility, rapidity and simplicity of Django (a web development framework
written in Python).

● 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.

Beautiful is better than ugly.


Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one — and preferably only one — obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let's do more of those!

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.

INSTALLING VIRTUAL STUDIO CODE

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.

VS Code is an IDE, which stands for Integrated Development Environment. An


Integrated Development Environment is the software that programmers use to
write, debug and execute their code.

Your content folder contains a sub-folder named “Installers” which will help you
download and set up Python on your machine.

SETTING UP YOUR DEVELOPMENT ENVIRONMENT

Please read the following instructions in full before following them:

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.

i. Please avoid the flatpak or snap versions as they give you


troubleshooting problems. Only proceed with flatpak if you are
sure of how they work.

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.

5. Use https://code.visualstudio.com/docs/languages/python to learn how


to use Visual Studio Code with Python. If you’ve never programmed before,
we strongly recommend you watch the videos.

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?

Programmers write statements of code to create programs. Programs are


executable files that perform the instructions given by the programmer.

Code can be written in different programming languages, such as Python, Java,


and C++. In this course, you will start by learning Python.

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.

THE PRINT() FUNCTION

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.”

- Riaz Moola, Founder and CEO

HOW TO GET INPUT

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.

name = input("Enter your name: ")


The variable name stores what the user entered into the box as a string (we’ll cover
strings in more depth in the next task). Storing and declaring variables doesn't
produce any output.

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.

WHAT ARE VARIABLES?

To be able to perform calculations and instructions, we need a place to store values


in the computer's memory. This is where variables come in. A variable is a way to
store information. It can be thought of as a type of “container” that holds
information.

Variables in programming work the same as variables in mathematics. We use


them in calculations to hold values that can be changed. In maths, variables are
named using letters, like x and y. In programming, you can name variables
whatever you like, as long as you don’t pick something that is a keyword in the
programming language. It is best to name them something useful and
meaningful to the program or calculation you are working on. For example,
num_learners could contain the number of learners in a class, or total_amount
could store the total value of a calculation.

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.

Below is an example of bad naming conventions vs good naming conventions.


● my_name = "Tom" # Good variable name
● variableOne = "Tom" # Bad variable name
● string_name = "Tom" # Good variable name
● h4x0r = "Tom" # Bad variable name

Here, my_name and string_name are examples of descriptive variables as they


reveal what their functions are and what content they store. variableOne and h4x0r
are terrible names because they are not descriptive.

Variable Naming Rules

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.

Variable Naming Style Guide

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.

VARIABLE DATA TYPES

There are five major types of data that variables can store. These are strings, chars,
integers, floats, and booleans.

● string: A string consists of a combination of characters. For example, it can


be used to store the surname, name, or address of a person.

● 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.

● integer: An integer is a whole number, or number without a decimal or


fractional part. For example, it can be used to store the number of items you
would like to purchase, or the number of students in a class.

● 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.

For example, consider this:

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.

num_days = int(input("How many days did you work this month?"))


pay_per_day = float(input("How much is your pay per day?"))
salary = num_days * pay_per_day
print("My salary for the month is USD:{}".format(salary))

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.

Working with the f-string:

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:

'I worked 28 days this month. I earned $50 per day.'

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.

If you wanted to use the str.format() method, you could do so as follows:


Example 1: insert values using index references

print("You worked {0} this month and earned ${1} per day".format(num_days = 22,
pay_per_day = 50))

Example 2: insert values using empty placeholders

print("You worked {} this month and earned ${} per day".format(num_days = 22,
pay_per_day = 50))

Hey there, have you heard about Alan Turing?

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.

Father of modern day computing

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

Follow these steps:

● Create a new Python file in this folder called hello_world.py


● Please first provide pseudo code as comments to this problem.
● Now, inside this file, write Python code to take in a user’s name using
input() and then print out the name.
● Also, take in a user’s age using the same method and print out their age.
● Finally, print out a new line and the string “Hello World!”
Compulsory Task 2
Follow these steps:

● Create a new Python file in your folder called details.py


● Please first provide pseudo code as comments to this problem.
● Use an input() command to get the following information from the user.
○ Name
○ Age
○ House number
○ Street name
● Print out a single sentence containing all the details of the user.
● For example:
○ This is John Smith. He. He is 28 years old and lives at house
number 42 on Hamilton Street.

Compulsory Task 3

Follow these steps:

● Create a new Python file in this folder called conversion.py


● Please first provide pseudo code as comments to this problem.
● Declare the following variables:
○ num1 = 99.23
○ num2 = 23
○ num3 = 150
○ string1 = “100”
● Convert them as follows:
○ num1 into an integer
○ num2 into a float
○ num3 into a string
○ string1 into an integer
● Print out all the variables on separate lines

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?

Click here to share your thoughts anonymously.

You might also like