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 |
int1 |
|
-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 |
|
|
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 | |
Array | A data structure used for holding multiple values/objects elements |
Element | A value within an array or similar data structures |
Record | 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. |
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).
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.
if (you.hasAnswer()) {
you.postAnswer();
} else {
you.doSomething();
}
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.
Potential scenarios where may be appropriate:
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()
Enum
base class is imported from enum
standard libraryGender
class defined, sub-classing Enum
.
Student
class defined - serves as the record.
just
- a variable used for text justification, to make the output look prettyStudent
called bob
is instantiated, with some parametersprint
method of the instance is called, so as to print the attributes, as asked in the question.Name: Bob
Age: 16
Gender: MALE
Lessons Count: 3
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 |
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.
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: "))
"Hello, "
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)
num1
: from user input casted to an integer type, given the prompt "Enter a number"
.num2
‘’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")
i
varies from 0 to 12, being incremented by 1 each iteration, do the following:
i
prepended to the string " times tables: "
j
varies from 0 to 12, being incremented by 1 each iteration, do the following:
i
concatenated with "x"
concatenated with j
concatenated with "=="
concatenated with the product of i
and j
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)
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
.
i
ranges from the current year (2018) to the year +(20*4):
mod(i,4)
is 0, which would imply that i
is fully divisible by 4
- and so i
is a leap year.i
is outputted.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
while
loop keeps looping until the number is guessed, or until the attempts limit is reached, at which point the loop is broken.>
and <
comparison operators.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: ")))))
reversed(..)
returns a generator for the reversed list from a list (remember that a string
is internally a list)list(reversed(..))
''.join(..)
joins a list of strings into one big string. This is used because the previous bullet point meant that a list of strings (each representing 1 character) is returned.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
elements
(see above).# array
a=[
]
# 2 dimensional array
a=[
[],
[],
...,
[]
]
# 3 dimensional array
a=[
[
[],
[],
...,
[]
],
...
]
# .
# .
# .
# n dimensional array
a=[
...
]
See top of the page.