0% found this document useful (0 votes)
25 views

unit_4_prog_1

This document outlines the fundamentals of computer science and programming, focusing on programming tools, variables, data types, and control structures. It covers the differences between compilers and interpreters, the requirements for programming in Python, and provides an overview of basic programming concepts such as variables, data types, and conditional statements. Additionally, it includes examples and guidelines for proper syntax and code structure.

Uploaded by

max.brus.2016
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

unit_4_prog_1

This document outlines the fundamentals of computer science and programming, focusing on programming tools, variables, data types, and control structures. It covers the differences between compilers and interpreters, the requirements for programming in Python, and provides an overview of basic programming concepts such as variables, data types, and conditional statements. Additionally, it includes examples and guidelines for proper syntax and code structure.

Uploaded by

max.brus.2016
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Fundamentals of Computer

Science and Programming


Unit 4 – Programming Part I

1 / 47
Outline

1. Programming tools
2. Requirements
3. Variables
4. Integers and Floats
5. Strings
6. Casting, Printing, Commenting, None-Keyword
7. Boolean variables and operators
8. Conditions (if-Statements)
9. Exercise

2 / 47
Programming tools

3 / 47
How does “text” become an executable program?

 When translating source code (“text”)


 The computer translates your written code into machine language.
 There are two different ways of translation:
 Compiler
 One-time translation into a binary file (executable)
 Interpreter
 Interpretation of the source code at each execution

4 / 47
Compiler

 Translates source code into machine code


 The resulting executable (file) only contains computer instructions
 The executable is no more human readable
 Saved as binary file (executable)
 Translation takes place only once!
 This process is also called compilation
000100111
print(”Hi”) compile
 The computer
… directly executes the program (executable)
101101100
110111010

Source code Executable file


(.exe)

5 / 47
Interpreter
 Similar to the compiler
 The program gets executed using computer instructions, but:
 Each command (e.g. print(“Hi”)) gets translated on its execution
 No additional binary file (executable) is created
 Source code gets translated on each execution
 This process is called “interpretation”
 Compilers can lead to drastic performance advantages

6 / 47
Basic terms in programming languages

 Programming language
 Formal language with fixed rules
 Syntax
 Fix rules on how to write in a programming language
 Fix rules for all language elements
 Semantics
 Meaning of the language elements
 What is exectued?
 Program logic, program flow, program structure
 Execution sequence and interplay between different program parts

7 / 47
Requirements

8 / 47
Requirements

 Computer (Mac OSX, Linux, Windows)


 No tablet
 No smartphone
 Python3 interpreter
 Integrated Development Environment (IDE)
 Jupyter Notebook / Jupyter Lab
 Installation instruction: https://github.com/dhelic/focsp/blob/main/installation.md

9 / 47
Python (www.python.org)

10 / 47
Jupyter (www.jupyter.org)

11 / 47
Python3

 Python 3.10 is recommended for the exercise


 Good readability, clear structure
 Interpreted
 Runs on all common OS

12 / 47
Variables

13 / 47
Variables

 Labels (names) for values and computations


 Variables reference values
 Placeholders
 Assignment of values with =
 <Variable name> = <Assigned value>
 Transient (temporary) storage of values
 Lifetime ends with the end of the program execution
 Start value is needed, after that we can change to arbitrary values
 Mutable

number = 123
message = 'Hello World!'
number2 = number

14 / 47
Variables

 Naming conventions for variable names


 Fixed rules (if not followed results in errors)
 Only letters, numbers and underscore _
 No numbers at the beginning
 No whitespaces
 Style guidelines
 Lower case, short and descriptive
 Words separated with underscore _
 https://github.com/dhelic/focsp/blob/main/style.md
 Notebook examples

15 / 47
Variables and data types
Data type Function Examples
int Natural numbers x = 3
float Floating point numbers x = 3.0
bool Booleans x = True
x = False
str Strings x = 'Test'
x = "Test"
tuple Tuples x = (1, 2, 3)
list Lists x = [1, 2, 3]
dict Dictionaries x = {1: 'blue', 2:
'red'}
io.TextIOWrappe Files x = open('readme.txt')
r
... ... ...

16 / 47
Integers and Floats

17 / 47
Integers and floating point numbers

 Integers:
 1, -13, 15, -42, 12345, ...
 Floats:
 1.3, 3.14159, -42.123, …

 Arithemtic operations:
 Adding (+), Subtracting (-), Multiplying (*), Dividing (/)
 Exponantiating (**)
 Modulo Operator (%)

number = 5 + 13
number_2 = number + 5

18 / 47
Extended operators

 Arithemtic operations with direct assignement:


 Adding (+=), Subtracting (-=), Multiplying (*=), Dividing (/=)

number = 42 number = 42
number += 8 # => 50 number = number + 8
number -= 10 # => 40 number = number - 10
number /= 4 # => 10 number = number / 4
number *= 2 # => 20 number = number * 2

19 / 47
Some special cases

 Operations with integers and Float == Float


 4/2 = 2.0, 2 * 3.0 = 6.0, 3.0 ** 2 = 9.0
 Floating point error
 0.2 + 0.1 ≠ 0.3
 Notebook examples

20 / 47
Strings

21 / 47
Strings

 Text = sequence of characters


 Begin and end marked with quotation marks " or '

string = 'This is a string'


string = "This is also a string"
string = '"Python" was named after "Monty
Python".'
string = '''This is a multiline
string'''
string = """This is another multiline
string"""

22 / 47
Strings

 Accessing
 Individual characters: [] and an index (0-based!)
 First character = index 0
 Last character = length of the string – 1
 Multiple characters with slicing: [], : and indices
 Length: len(string)

23 / 47
String slicing

 Slicing
 Retreive the i-th character:
 string[i]
 Retrieve a substring with characters from start (inxlusive) until end (exclusive):
 string[start:end]
 Retrieve a substring with characters from start (inxlusive) until end (exclusive)
in steps of the given size:
 string[start:end:stepsize]

24 / 47
String slicing

 Advanced slicing
 Retreive the i-th last character:
 string[-i]
 Retrieve everything from the i-th last character (inclusive):
 string[-i:]
 Retrieve everything until the i-th last character (exclusive):
 string[:-i]
 Reversed string:
 string[::-1]

25 / 47
String slicing: example

text = 'Vienna'

Command with text Result

text[0] 'V'
text[:2] 'Vi'
text[0:2]
text[6] IndexError
text[5] 'a'
text[-1]
text[2:] 'enna'
text[2:6]
text[::2] 'Ven'

text[::-1] 'anneiV'

26 / 47
String methods

 Strings are flexible with a Call Result


huge standard functionality name + ' , hi!' 'John Doe, hi!'
 Methods take actions on text * 2 ' Python! Python! '
the variable values
name.title() 'John Doe'
 Examples:
name.upper() 'JOHN DOE'
text = ' Python! ' text.lower() ' python! '
name = 'John Doe'
text.rstrip() ' Python!'
text.lstrip() 'Python! '
text.strip() 'Python!'
name.split(' ') ['John', 'Doe']

 Notebook examples

27 / 47
Casting, Printing, Commenting,
None-Keyword

28 / 47
Conversion between data types
num1 = 123
 Casting: converting between data types num2 = '15'
num3 = num1 + num2
 int(), str(), float(),
bool()… Output:
 Examples: TypeError
 int('5') 1 num1 = 123
=> 5
2 num2 = '15'
 float('5.23') => 5.23 --> 3 num3 = num1 + num2
 str(5) => '5' TypeError: unsupported
 int(True) => 1 operand type(s) for +:
'int' and 'str'
 bool(0) =>
False Solution:
num1 = 123
num2 = '15'
num3 = num1 + int(num2)

29 / 47
Formatting output

 print() function
 Prints also a new line at the end
 Parameters separated with ,
 Space character as a whitespace
 We can also print and format variables
 f before the string to print
 Variables in brackets {}

name = 'Max'
age = 20
print(f'My name is {name} and I am {age} years old')

Output: My name is Max and I am 20 years old

30 / 47
Formatting output

 Whitespaces and special characters

Sequence Result
\n New line
\t Tabulator
\' ' character in strings
\" " character in strings
\\ \ character (backslash)

31 / 47
Comments

 Syntax
 # single-line comment
 """ multi line
comment """
 ''' multi line
documentation '''
 Explanations to program flow and structure
 Supports understanding of the program
 Useful for group projects, longer lasting projects, etc.

32 / 47
None-Keyword

 None
 No value, Null value
 Placeholder when the variable value is still not assigned
 x = None is different than:
0
 False
 ''
 Notebook examples

33 / 47
Boolean variables and operators

34 / 47
Boolean variables

 Boolean variables (boolean, bool) store true/false values


 True
 False
 Boolean variables are results of comparisons of other variables

value = ((2 + 2) < 4)


print('This is', value)

35 / 47
Comparison operators

Operator Description Example


== is equal x == y
!= is not equal x != y
> greater than x>y
< smaller than x<y
>= greater or equal x >= y
<= smaller or equals x <= y
is objects are identical x is y
is not objects are different x is not y

Result of comparisons: Boolean value (True oder False)

36 / 47
Logical operators

Operator Description Example


and True iff both statements are true x == y and y < 5
or False iff both statement are false x > 2 or y > 3
not Negation of the statement not x == y
not z
^ True iff one of the statements is true (XOR) x == 2 ^ y < 4

 Note that ^ is so-called bitwise operator


 Works on bits
 Result of each comparison is a boolean value
 Hence, this should work as expected

37 / 47
Operator precedence
Operator precedence  If not sure: ()
(from low to high)
 Notebook examples
or
and
not
in, not in, is, is not, <, <=, >, >=, !=, ==
|
^
&
<<, >>
+, -
*, @, /, //, %
+x, -x, ~x
**

38 / 47
Conditions (if-Statements)

39 / 47
Branching: if statements

 Checking whether conditions are satisfied


 Conditional execution of code
 Control flow
 If condition satisfied then do something
 Syntax:

if condition: if x > 2:
print('Do something') print('In if')
print('Not in if')

Indented 4 spaces

40 / 47
Branching: if-else statements

 If statement with a fallback


 In case the condition is not fullfilled
 If condition satisfied then do something else do something else
 Syntax:

if condition:
print('Do something')
else:
print('Do something else')

if x > 2:
print('In if')
else:
print('In else')

41 / 47
Branching: if-elif-else statements

 Multiple branching for more complex case


 If first condition satisfied then do something
else if second condition then do something else
else if third condition then do somenthing else than before

else do something completly different

42 / 47
Branching: if-elif-else statements

 Syntax:

if condition:
print('Do something')
elif condition2:
print('Do something else')
elif condition3:
print('Do something different')
# there could be more elifs below this
else: # optional
print('Do something completely different')

43 / 47
Branching: if-elif-else statements

 Examples:

if x < 5: if x < 5:
print('Small') print('Small')
elif x < 15: if x < 15:
print('Medium') print('Medium')
elif x < 20:
print('Big') ≠ if x < 20:
print('Big')
else: else:
print('Huge') print('Huge')

44 / 47
Indentation rules

 Standard PEP8 (https://peps.python.org/pep-0008/)


 4 spaces, no tabulators (configure editors to replaces tabs with 4 spaces)
 Block indentation
 Everything that is indented after : belongs to the current block
 This is language syntax!
 Not following the syntax results in an error
 Implicitly: supports formatting and readability of code
 Changes the relation to the rest of the code
 if, for, while, def, …

45 / 47
Nested indentation
 Code blocks can be arbitrarly nested at multiple levels

age_max = 35
age_peter = 42
age_berta = 37

if age_max < age_peter:


print('Max is younger than Peter')
if age_berta < age_max:
print('Berta is the youngest!')
else:
print('Max is the youngest!')
else:
if age_berta < age_peter:
print('Berta is the youngest!')
else:
print('Peter is the youngest!')

 Notebook examples

46 / 47
Exercise

47 / 47
Student task

Task 1: Install python3 and jupyter lab. You can follow these installation instructions.
After installation is complete start the jupyter lab and implement following tasks in
separate cells:
1. Initialize variables radius and side with positive values. Compute the area of a
circle with a given radius and the area of a square with a given side. Compute the
difference of the larger area to the smaller area of the two.
2. Initialize an integer variable x. Write a code to decide wheather x is divisible by
both 2 and 3, by either only 2 or 3, or by neither 2 nor 3.
3. The volume of a sphere with radius r is . Write a cell to compute the volume of a
sphere. What is the volume of a sphere with radius 5?
4. Suppose the cover price of a book is €24.95, but bookstores get a 40% discount.
Shipping costs €3 for the first copy and €0.75 for each additional copy. What is the
total wholesale cost for 60 copies? Write a cell to compute this cost.

48 / 47

You might also like