• ¿Documento equivocado? Cámbialo gratis
  • Escrito por estudiantes que aprobaron
  • Inmediatamente disponible después del pago
  • Leer en línea o como PDF
Vender
¿Dónde estudias?
Tu idioma
Document preview thumbnail
Vista previa 4 fuera de 38 páginas
Notas de lectura

Study Notes for Computer Science 1015 (Intro to Programming) UCT

Document preview thumbnail
Vista previa 4 fuera de 38 páginas

These are a detailed summary of all of the PowerPoint slides, as well as the video lectures with information included from the face-to-face lectures. They will assist any students wanting to achieve a high mark in the final exam. My practical average for the course is 100% (not including theory as I have not yet written the exam), showing that they are of high quality.

Vista previa del contenido

© Thomas Kabalin




Introduction: What is Comp Sci?
Computer Science (CS) is the study of:
 Computer software
 Algorithms, abstractions and efficiency
 Theoretical foundation for computation
Learn the principles of computation, how to make machines perform complex
tasks, problem solving

Problem Solving
1. Understand the problem
2. Plan how to solve the problem (algorithm, break it up, what assumptions
can be made)
3. Carry out your plan (write the program i.e. implement the algorithm)
4. Assess the result (does it solve the problem & is it correct in all cases?)
5. Describe what you have learned
6. Document the solution (comments in the program/report for users)

Algorithms
 Algorithm is a set of steps to accomplish a task
o Repeatable
o Have a predictable outcome
o Can be executed by different people
 Elements of an algorithm
o Sequence – each step is followed by another step
o Selection – a choice is made
o Iteration – steps may be repeated

Programs
 Program is a set of instructions given to a computer, corresponding to an
algorithm to solve a problem
 Takes input, processes data, sends computed data back to real world
(output)
 Each time a program is executed, results can be different
 Python is a general purpose interpreted programming language
 Programs stored in text files, written in IDEs
 Instructions executed by Python Interpreter
o Run one instruction at a time
o Executes instructions then prompts user for the next
o Used for testing code snippets
 Programs must be saved as .py to store permanently

, © Thomas Kabalin



Basics of Programming
Python Syntax
print(“Hello Word”)
 Print is the name of the function (common task that can be reused)
 “Hello Word” is the argument or value sent to the function
 Statements are on separate lines & python is case sensitive
 # is used for comments
o Used for description of each function
o Used for non-obvious parts of code

Include the following comment in each program
# what the program does
# author of program
# date

Errors
 Syntax errors are when your program does not conform to the structure
required
 Logic errors are when your program runs but does not do what is expected

Escape Sequences
Escape sequences are special characters that cannot be represented easily in
the program
\a - bell (beep)
\b – backspace
\n – newline
\t – tab
\’ – single quote
\” – double quote
\\ - \ character

Numeric Data Types
 Integers
o Whole numbers with no fractional part
 Floating point number
o Number with fractional part
o Stores only an approximation to a real number
o Limit to precision of number
 Literals are actual data values written into a program

Integer Expressions
+ (plus), - (minus), / (divide), * (times), % (mod), // (integer division), ** (a to the
power b)
Integer result is given when both operands are integers (except for divide)
Modulus is also known as integer remainer

, © Thomas Kabalin


Identifiers
 How things are named e.g. print (reserved for program)
 Must start with _ or letter, and optionally followed by more letters, digits or
_
 Python style: hello_world

Variables
 Sections of memory where data can be stored
 Most have names (identifiers)
 Defined by assigning an initial value (automatically assigned data type):
a_value = 5
 Can assign other variables to variable (b = a + 5)

Advanced Print Statements
To print a series of values:
print(“the values are”, x, y, z)
To change / remove the line ending (usually \n): end=ending
print(x, y, z, end=ending)
To change the separator character between items (usually a space):
sep=sepchr
print(x, y, z, sep=sepchr)
End & sep must come at the end of the print statement (order does not matter)

Input
 Stores text string in variable:
<variable> = input(<prompt>)
 Always gives a string – must be converted
 eval() converts string to number (as either floating point or integer
depending on input)
 Can use int() or float() if you know data type
Concatenation symbol is ‘+’ (does not have a separator – just concatenates)

Numerical Syntax
a+=3 (means a=a+3)
a-=3
a*=3
a/=3
 Conversion (or casting) is when type is converted to another
 Implicit conversions
o If there is a type mismatch, the narrower range value is promoted
up
o Cannot automatically convert down
 Explicit conversions
o Typecast methods convert to another type (int, float)

, © Thomas Kabalin


o math.ceil, math.floor, round(number, [decimal places]) give
more control over floating-point numbers

Math Module
 Modules are collections of useful functions
 To use a module:
import math
 To use a function:
math.sqrt(a)
 Can also use the following to avoid prefix:
from math import <specific function>
from math import *

Formatting Numbers
print("The answer is: %.1f" % NumToDisplay)

 Can add total width before . (%5.1f)


Terminology
 Comment
o A part of the code (starting after a # symbol) that is ignored by
python and it intended to help a human reader
 Function
o A named sequence of instructions that perform a collective purpose
(e.g. print)
o Items passed into a function (inside the brackets) are called
arguments or parameters
 Identifier
o A word, consisting of letters, numbers and _ characters, used to
name functions and variables
 Variable
o A container for data (e.g., strings, integers and floating-point
numbers), named using the rules for identifiers
 String literal, numeric literal
o Fixed character sequences or numbers used directly (e.g., “Hello”,
3.15)
o Can be further broken down into floating point literal and integer
literal
 Expression
o An arithmetic expression combining variables, numeric literals, and
arithmetic operators (e.g, +, -, etc)
 Syntax
o The fundamental rules of a programming language

Información del documento

Subido en
15 de mayo de 2024
Número de páginas
38
Escrito en
2023/2024
Tipo
Notas de lectura
Profesor(es)
Aslam safla
Contiene
Todas las clases
$18.47

¿Documento equivocado? Cámbialo gratis Dentro de los 14 días posteriores a la compra y antes de descargarlo, puedes elegir otro documento. Puedes gastar el importe de nuevo.
Escrito por estudiantes que aprobaron
Inmediatamente disponible después del pago
Leer en línea o como PDF

Seller avatar
Los indicadores de reputación están sujetos a la cantidad de artículos vendidos por una tarifa y las reseñas que ha recibido por esos documentos. Hay tres niveles: Bronce, Plata y Oro. Cuanto mayor reputación, más podrás confiar en la calidad del trabajo del vendedor.
thomaskabalin
3.8
(6)
Vendido
37
Seguidores
20
Artículos
13
Última venta
2 meses hace



Por qué los estudiantes eligen Stuvia

Creado por compañeros estudiantes, verificado por reseñas

Calidad en la que puedes confiar: escrito por estudiantes que aprobaron y evaluado por otros que han usado estos resúmenes.

¿No estás satisfecho? Elige otro documento

¡No te preocupes! Puedes elegir directamente otro documento que se ajuste mejor a lo que buscas.

Paga como quieras, empieza a estudiar al instante

Sin suscripción, sin compromisos. Paga como estés acostumbrado con tarjeta de crédito y descarga tu documento PDF inmediatamente.

Student with book image

“Comprado, descargado y aprobado. Así de fácil puede ser.”

Alisha Student

Preguntas frecuentes