MA1008 Introduction to Computational Thinking (Python), Summaries of Computer Programming

fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff

Typology: Summaries

2018/2019
On special offer
30 Points
Discount

Limited-time offer


Uploaded on 10/31/2019

brennanng
brennanng 🇸🇬

1 document

1 / 33

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
MA1008 Introduction to
Computational Thinking (Python)
PROGRAM LANGUAGES
BASIC COMPUTER OPERATIONS
Control Unit (CU) - controls and coordinates the overall
operation of the CPU.
Arithmetic/ Logic Unit (ALU) - performs the arithmetic
operations as well as Boolean logic functions.
Register Array - holds the various information used by
CPU operations
Central Processing Unit (CPU) - processes information and
performs operations based on information given.
Memory - stores information used by the computer.
Input/ Output (I/O) Interface - mechanism for transferring
information to and from the outside world, such as to interact
with users.
System Bus - providing the connection between the modules
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
Discount

On special offer

Partial preview of the text

Download MA1008 Introduction to Computational Thinking (Python) and more Summaries Computer Programming in PDF only on Docsity!

MA1008 Introduction to

Computational Thinking (Python)

PROGRAM LANGUAGES

BASIC COMPUTER OPERATIONS

Control Unit (CU) operation of the CPU. - controls and coordinates the overall Arithmetic/ Logic Unit (ALU operations as well as Boolean logic functions.) - performs the arithmetic Register Array CPU operations - holds the various information used by

Central Processing Unit (CPU) performs operations based on information given. - processes information and Memory - stores information used by the computer. Input/ Output (I/O) Interface information to and from the outside world, such as to interact - mechanism for transferring with users. System Bus - providing the connection between the modules

3 Basic Step for Program Execution: Fetch Decode Execute (by the CPU of a microprocessor)

IF – ELSE – ELSE STATEMENT The if…elif…else statement is used in Python for decision making.

IF – ELIF – ELSE IF - ELSE NESTED IF if expression1: suite elif expression2: suite else suite

if condition: suite else: suite

if condition1: if condition2: suiteA else: suiteB else: suiteC

*NOTE: if you use ‘if’ all the way instead of ‘elif’ , even if one of the condition is met, it will continue to run the program and execute the suite.

IF only IF - ELSE if 90 < = x < = 100: print('High Value') if 80 < = x < = 90: print('High Value') if 70 < = x < = 80: print('High Value') else: print ('Low Value')

if 90 < = x < = 100: print('High Value') elif 80 < = x < = 90: print('High Value') elif 70 < = x < = 80: print('High Value') else: print ('Low Value') Output High Value Low Value

High Value

Example:

While – Else, Break Statement:

The break statement can be used to immediately exit the execution of the current loop and skip past all the remaining parts of the loop suite.

While – Else, Continue Statement:

The continue statement can be used to skip some portion of the while suite we are executing and have control flow back to the beginning of the while loop.

‘For’ Loop:

SYNTAX Example for iterating_var in : suite (one or more indented statements)

for the_char in 'thinking': print ('Current char:', the_char)

Output: Current char: t Current char: h Current char: i Current char: n Current char: k…

Range() Function:

range (start, end, step)

start Starting number of the sequence. (Default value is 0) end To generate numbers up to, but not including this number step Difference between each number of the sequence. (Default value is 1)

Eg. range(1, 11, 2) [1, 3, 5, 7, 9] range(11, 2, -3) [11, 8, 5]

Md ImdM Length of String, len() opstr = ‘Basic’ len(opstr) 5 Concatente String, + opstr + ‘operations’ ‘Basic Operations’ Repeat String, ***** opstr*3 ‘BasicBasicBasic’ Uppercase the string, upper() mystr = ‘Shouting’ mystr. upper() ‘SHOUTING’ Finding the index of the letter in the string, find()

mystr = ‘Find in a string’ mystr. find(‘d’) 3

Formatting Strings: The format() method allows us to perform low-level type-setting (pretty strings).

SYNTAX: { [field] : [align] [min_width]. [precision] [descriptor] }

Alignment <: left

>: right

^: center

Descriptors s: string

d: decimal

e: floating point exponent

f: floating point decimal

u: unsigned integer

ASCII & UNICODE

Convert character to code, ord():

ord(‘a’) 97

Convert code to character, chr():

chr(97) ‘a’

Membership operation, IN:

Count() count the number of element of a kind

>>> my_list = ['a', ‘b’, 'c', 'b'] >>> my_list.count('b') 2 Sort() performs an in-place sorting

>>> my_list = ['a', ‘b’, 'c', 'b'] >>> my_list.sort() >>> my_list ['a', 'b', 'b', 'c'] Reverse() reverse the element in-place

>>> my_list = ['a', 'c', 'b'] >>> my_list.reverse() >>> my_list ['b', 'c', 'a'] Split() Splits a string and return it in list format

>>> splitLst = 'this is a test'.split() >>> print(splitLst) ['this' , 'is' , 'a' , 'test']

DATA STRUCTURES (LIST, TUPLES , DICT)

Commas Create Tuples:

Comma (,) can be thought of as the operator that makes a tuple while the round bracket ( ) simply

acts as a grouping.

Tuples VS List:

LIST COMPREHENSION List comprehension is a syntactic structure for concise construction of lists

Example shark_letters = [letter for letter in 'shark'] print(shark_letters) Output ['s', 'h', 'a', 'r', 'k']

Using Conditionals with List Comprehensions:

Example fish_tuple = ('blowfish', 'clownfish', 'catfish', 'octopus') fish_list = [fish for fish in fish_tuple if fish != 'octopus'] print(fish_list) Output ['blowfish', 'clownfish', 'catfish']

Nested Loops in a List Comprehension:

Example

This method can be used to query across dictionaries. For example, we can take a look at thecommon keys shared between two dictionary data structures: sammy = {'username': 'sammy-shark', 'online': True , 'followers': 987} jesse = {'username': 'JOctopus', 'online': False , 'points': 723} for common_key in sammy.keys() & jesse.keys(): print(sammy[common_key], jesse[common_key]) Output sammy-shark JOctopus True False

dict.values() isolates values sammy = {'username': 'sammy-shark', 'online': True , 'followers': 987} print(sammy.values()) Output dict_values([True, 'sammy-shark', 987])

dict.items() returns items in a list format of (key, value) tuple pairs sammy = {'username': 'sammy-shark', 'online': True , 'followers': 987} print(sammy.items()) Output dict_items([('online', True), ('username', 'sammy-shark'), ('followers', 987)])

We can iterate over the returned list format with a for loop. For example, we can print out each of the keys and values of a given dictionary, and then make it more human- readable by adding a string for key, value in sammy.items(): print(key, 'is the key for the value', value) Output online is the key for the value True followers is the key for the value 987 username is the key for the value sammy-shark

Modifying Dictionaries:

Dictionaries are a mutable data structure, so you are able to modify them using this syntax:

dict[key] = value

Adding Dictionary Elements usernames = {'Sammy': 'sammy-shark', 'Jamie': 'mantisshrimp54'} usernames['Drew'] = 'squidly' print(usernames)

Output {'Drew': 'squidly', 'Sammy': 'sammy-shark', 'Jamie': 'mantisshrimp54'}

Changing Dictionary Elements drew = {'username': 'squidly', 'online': True , 'followers': 305} drew['followers'] = 342 print(drew) Output {'username': 'squidly', 'followers': 342, 'online': True}

Program which allows users to add usernames into dictionary

usernames.py that runs on the command line and allows input from the user to add more names and associated usernames:

Define original dictionary

usernames = {'Sammy': 'sammy-shark', 'Jamie': 'mantisshrimp54'}

Set up while while True : loop to iterate

Request user to enter a name

print('Enter a name:')

Assign to name variable

name = input()

Check whether name is in the dictionary and print feedback

if name in usernames: print(usernames[name] + ' is the username of ' + name)

If the name is not in the dictionary...

else :

Provide feedback

print('I don't have ' + name + ''s username, what is it?')

Take in a new username for the associated name

username = input()

Assign username value to name key

usernames[name] = username

Print feedback that the data was updated

print('Data updated.') Output Enter a name: Sammy sammy-shark is the username of Sammy Enter a name: Jesse

FUNCTIONS IN PYTHON A function is a block of instructions that performs an action and, once defined, can be reused. Functions make code more modular, allowing you to use the same code over and over again.

Defining a Function:

A function is defined by using the def keyword, followed by a name of your choosing, followed by a set of parentheses which hold any parameters the function will take (they can be empty), and ending with a colon.

Returning a Value:

The print() function writes, i.e., "prints", a string or a number on the console. The return statement does not print out the value it returns when the function is called. It however causes the function to exit or terminate immediately, even if it is not the last statement of the function. Functions without return statements are often called procedures.

A function with multiple returns def funcA (number): if number > 0: return "positive!" elif number < 0: return "negative!" else: return "zero!"

Dynamics of Function Calls:

Functions Calling Functions:

Functions are made to solve a problem and can be called from other functions.

Example def str_length(a_str): count = 0 for ch in a_str: count = count + 1; return count

def funcA (text): length = str_length(text)

if length > 0: return "positive!" elif length < 0: return "negative!" else: return "zero!"