ALevel

0.2 - Programming Basics

Tasks

Programming Tasks

End of Chapter Tasks

Data Types

Category7

Name

Min

Max

C#

Java

Python

JavaScript

Integer

Byte

 

 

 

0

255

SByte

byte

 

 

-128

127

Char

char

 

 

U+0000

U+FFFF

UInt16

 

 

 

0

216-1

Int16

short

 

 

-215

215-1

UInt32

 

 

 

0

232

Int32

int

int­1

 

-231

231-1

UInt64

 

 

 

0

264

Int64

long

Int1

 

-263

263-1

Numerical3

Single

float

 

 

2-149

(2-2-23)*2127

Double

double

float2

number4

2-1074

(2-2-52)*21023

Decimal

 

decimal6

 

±1e-28

±7.9228e28

 

 

complex

 

 

 

Sequences

List6

ArrayList6,9

list

list

 

 

Array

array

 

 

 

 

Dictionary6

HashMap6,9

dictionary8

dictionary

 

 

Tuple6

 

tuple

 

 

 

IEnumerable6

 

range

 

 

 

Other

Boolean

boolean

bool

boolean

false

true

String

string

string

string

(len) 0

231-1

null

null

 

null

 

 

void5

void5

None

undefined

 

 

Notes:

  1. In Python 2, the max value for int = 263-1 and min = -263 because Python switches seamlessly from 32 bits to 64 bits once the 32 bit limit is exceeded. In Python 3, it is unbounded.
  2. Although float is usually used to refer to single-precision floating point numbers and double is used to refer to double-precision, Python internally uses a C double to represent floats.
  3. Limits may vary in different programming languages.
  4. Full technical name: Double-precision 64 bit floating point number IEEE 754
  5. Void is not used in the same way as None or undefined, although None or undefined may be used a similar way to void.
  6. Not strictly built-in but can be accessed through the standard library.
  7. Additional types such as linked lists, etc may be available in the languages’ standard library.
  8. Python dictionaries are unordered.
  9. Other similar implementations exist, which may have slightly different use cases.

Extra Info:

Keywords

Keyword Definition
Memory where instructions and data are stored (on a computer)
algorithm sequence of steps used to solve problem that always terminates
Syntax The rules that govern the tokens that make up a computer language. Can be defined using EBNF
Memory Address A location in memory
Assignment Setting something (to equal) something else
Constant A value that doesn’t change (as opp. to variable)
Debug Process of finding and removing bugs
Bug An error in terms of code
Declaration The definition of anything (e.g: variables, constants, classes, etc)
Data Type Information about the type of a certain data.
Integer A number with no fractional part.
Pointer A data item that identifies a particular element data structure An object that stores a memory address. Often used to refer aka ‘point’ to a value in memory.
Array A data structure used for holding multiple values/objects elements
Element A value within an array or similar data structures
Record One line of text file Aka struct: A collection of fields, which may be of different types, (the types of which, often defined by a Record Declaration)
Field A specific piece of data encapsulated by a record. Essentially a variable.

Naming Conventions

How to make your code look a little less painful: agreeing that everyone names everything with generally the same pattern :)

Of course, different companies, institutions, etc may have different conventions, but generally, some conventions are:

  Python Convention C# Convention
Class name UpperCamelCase UpperCamelCase
Constants CAPITALISED_SNAKE_CASE CAPITALISED_SNAKE_CASE
Variable names lower_snake_case lowerCamelCase
Private variable names __prepend_two_underscores _prependUnderscore
Keyword conflict prevention _prepend_undescore @prependAtSymbol

(For C# the conventions are a bit more complex official conventions here).

Code Style Conventions

Similar to naming conventions, but for the syntax of the program.

In C#, for example, often, the starting brackets get their own entire lines :^) - in a lot of other languages, the convention tends to be to keep the starting brackets with the statements before them.

1:

if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}

2:

if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}

(and other variants)

In terms of python, there is an extensive official coding style convention defined, called PEP 8. Info here.

Constants

Potential scenarios where may be appropriate:

Task 1

In your chosen language declare and assign a value to variables for the following:

A student record that would contain the name, age, gender and the total number of lessons they have attended in their whole time at school

Once this is complete, take a screenshot showing each variable value printed to the console

from enum import Enum

class Gender(Enum):
    UNKNOWN = 0
    MALE = 1
    FEMALE = 2
    OTHER = 3

class Student:
    def __init__(self,
                 name='unnamed',
                 age=-1,
                 gender=Gender.UNKNOWN,
                 lessons_count=-1):
        self.name = name
        self.age = age
        self.gender = gender
        self.lessons_count = lessons_count

    def print(self):
        just = 20
        print(('Name:').ljust(just) + str(self.name))
        print(('Age:').ljust(just) + str(self.age))
        print(('Gender:').ljust(just) + str(self.gender.name))
        print(('Lessons Count:').ljust(just) + str(self.lessons_count))


bob = Student(name="Bob", age=16, gender=Gender.MALE, lessons_count=3)
bob.print()

Explanation

Output

Name:               Bob
Age:                16
Gender:             MALE
Lessons Count:      3

Task 2

Data types examples

number = 1
string = 'seven'
Boolean = True
Groceries = ['apple', 'pear', 'Lego']
number2 = 3.141

Data types can essentially be split into integral, numerical, squential and other categories. (See above table).

Type Info
Integral Numbers with no fractional parts. The maximum and minimum numbers that can be stored depends on the amount of memory assigned (see table above for details).
Numerical Real numbers which may or may not have fractional parts. The maximum and minimum numbers that can be stored as well as the decimal precision of the numbers stored depend on the amount of memory assigned + implementation
Sequential Things like arrays and dictionaries. An array is a data structure used for holding multiple values/objects ( elements) (see above)
String This data type stores text, and is actually usually internally just an array of integers, where each integer represents a certain character (the integer being the character’s ID in a way). Which integers correspond to which characters is defined in an Encoding. The most popular such Encodings are UTF and ASCII

In the string section just now ASCII was mentioned. Here are some glyphs defined by ASCII and their respective values:

Hex Glyph
30 0
31 1
32 2
33 3
34 4
35 5
36 6
37 7
38 8
39 9
3A :
3B ;
3C <
3D =
3E >
3F ?
40 @
41 A
42 B
43 C
44 D
45 E
46 F

Task 3

Declare a new data type, assign values to the variables and screenshot evidence of the code and printout to the console

class NewType:
    def __init__(self):
        self.a=2
inst=NewType()
inst.a=923
print(inst.a)

user defined types’ behaviour achieved with class instances

Here, the class ‘NewType’ is defined with attribute ‘a’ which is initialised to some value. Demonstration of instantiating that class and replacing attribute ‘a’ with some other variable + demonstration of attribute access.

Task 4

Write a program that asks the user for their name and greets them with their name (you will need to use a scanner to read from the keyboard).

print("Hello, "+input("Please enter your name: "))

Explanation

Write a program that asks the user for 2 numbers, stores them and prints the sum of the numbers

num1=int(input("Enter a number: "))
num2=int(input("Enter a number: "))
print(num1+num2)

Explanation

Write a program that prints a multiplication table for numbers up to 12 (loop).

for i in range(13):
    print(str(i)+" times tables: ")
    for j in range(13):
        print(str(i)+"x"+str(j)+"=="+str(i*j))
    input("press enter to continue")

Explanation

Write a program that prints the next 20 leap years (loop).

from datetime import datetime
cur_year=datetime.now().year
for i in range(cur_year, cur_year+(20*4)+1):
  if i%4==0: print(i)

Explanation

Mod:

The modulus function mod(a, b), represented in most languages through the use of the infix operator % like a % b, gives the remainder after the integer division of a by b. This means that if a % b is equals to 0, for any values of a and b, it can be concluded that a is fully divisible by b.

Write a guessing game where the user has to guess a secret number. After every guess the program tells the user whether their number was too large or too small. At the end the number of tries needed should be printed.

attempts_limit=10
attempts=1
num=random.randint(0,100)
print("My number is between 0 and 100. Try guess it.")
while True:
    guess=int(input("Enter a guess: "))
    if attempts>=attempts_limit: # extension
        print("You ran out of attempts ("+str(attempts)+")")
        break
    if guess>num:
        print("Too high~")
    elif guess<num:
        print("Too low~")
    else:
        print("Yep~")
        print("It took you " + str(attempts) + " attempts")
        break
    attempts+=1

Explanation

Write a program that computes the reversal of a string. For example, reverse(“I am testing”) should return the string “gnitset ma I”.

print(''.join(list(reversed(input("Enter a string to reverse: ")))))

Explanation

EOC Tasks

Questions

Two reasons why meaningful variable names

So that both you and other people can more easily understand what is going on in your code.

Examples to explain difference between constant and variable

A constant cannot be changed at program runtime, whereas variables can. Defining variables that don’t change as constants may result in code being more optimised, so constants should be used as much as possible for variables that don’t change at runtime. An example usage would be the program’s build version. An example of a non-constant variable, however, for example, would be the number of tables in a room. What if someone takes a table out of the room and you have to update the variable? :^)

Why important to declare all variables + constants at start of program

Global variables, and constants should definitely be defined near the top of a program, or the specific scope, so that you can easily see which such variables you have defined when working on your program. More broadly, it also should for the purpose of adhering to good coding practices and conventions, for the sake of making your code more readable (for not just you but others).

Difference between value and variable.

The word ‘variable’ is commonly used to refer to the name given to a specific piece of data and also the piece of data itself. The word ‘value’, however, is usually used solely when referring to the data itself.

Suggest types and names for all of the following:

  • current rate of vat

  • today’s date

  • total takings from shop
  • dob
  • which wrist person wears watch on
  1. VAT_RATE, decimal
    • name follows constant naming conventions
    • decimal because decimal provide good accuracy when working with base-10 decimal numbers, such as the values for VAT
  2. cur_date, DateTime
    • name follows snake_case naming convention
    • Most languages provide classes for things like this - in python, it is DateTime
  3. tot_takings, Decimal
    • (same as above)
    • (same as above)
  4. wear_pos, Enum
    • (same as above)
    • Please do not: “adapt a Boolean variable so that Right was stored as True and Left as False” as the textbook says because that is not scalable at all and is quite unintuitive - unless you named the variable something like “wear_on_right”, which makes sense to either be True or False.
    • Enum: A set of unique named values. In other words, the data-type will be a category, in a sense, out of a defined set of categories. These categories may be “Left” and “Right”.

Research Tasks

n dimensional arrays

  1. An array = a data structure used for holding multiple values/objects elements (see above).
  2. An instance of an array is an object.
  3. This means you can put it inside an array.
  4. Put arrays inside arrays
  5. Now you have a 2-dimensional array
  6. repeat from step 3 until you have an n-dimensional array where n is any number you want
  7. ???
  8. profit
# array
a=[ 
]
# 2 dimensional array
a=[
    [],
    [],
    ...,
    []
]
# 3 dimensional array
a=[
    [
        [],
       	[],
        ...,
        []
    ],
    ...
]

# .
# .
# .
# n dimensional array
a=[
    ...
]

Built-in Data-Types

See top of the page.