• Keine Ergebnisse gefunden

Basics of CS

N/A
N/A
Protected

Academic year: 2022

Aktie "Basics of CS"

Copied!
8
0
0

Wird geladen.... (Jetzt Volltext ansehen)

Volltext

(1)

Departement Informatik

Basics of CS

Functions

Hans-Joachim Böckenhauer Dennis Komm

Autumn 2021 – October 21, 2021

Control Structures

Termination

Termination

i = 1

while i <= 5:

s += i i += 1

Here and commonly:

statement changes its value that appears in condition After a finite number of iterations condition becomes false ï Termination

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 1 / 26

Infinite Loops

Infinite loops are easy to generate while True:

print("0")

while not False:

print("1")

while 2 > 1:

print("2")

. . . but can in general not be automatically detected

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 2 / 26

(2)

Halting Problem

Undecidability of the Halting Problem [Alan Turing, 1936]

There is no Python program that can determine, for each Python program P and each input I , whether P terminates with the input I

This means that the termination of programs can in general not be automatically checked

Theoretical questions of this kind were the main motivation for Turing to design his computing machine

Alan Turing [Wikimedia]

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 3 / 26

The Collatz Sequence

Sequence of natural numbers n 0 , n 1 , n 2 , n 3 , n 4 , n 5 , . . . n 0 = n

for every i ≥ 1, n i =

n i−1 /2 if n i−1 even 3 · n i−1 + 1 if n i−1 odd

Example for n = 5

5, 16, 8, 4, 2, 1, 4, 2, 1, . . . (repetition at 1)

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 4 / 26

Exercise – The Collatz Sequence

Write a program that takes an integer n as input

outputs the Collatz sequence using n 0 = n and

n i =

n i−1 /2 if n i−1 even 3 · n i−1 + 1 if n i−1 odd stops when it reaches 1

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 5 / 26

Exercise – The Collatz Sequence

n = int(input("Compute the Collatz sequence for n = "))

while n > 1: # stop when 1 is reached if n % 2 == 0: # n is even

n //= 2

else: # n is odd

n = 3 * n + 1 print(n, end=" ")

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 6 / 26

(3)

The Collatz Sequence

Example for n = 27

27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 7 / 26

The Collatz Sequence

The Collatz Concecture [Lothar Collatz, 1937]

For every n ≥ 1 , the number 1 will occur in the se- quence

Nobody could prove the conjecture so far

If it is false, then the while loop for computing the Collatz sequence can be an endless loop for some n as input

Lothar Collatz [Wikimedia]

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 8 / 26

Control Structures

Control Flow

Control Flow – if

Order of the (repeated) execution of statements generally from top to bottom. . .

. . . except in selection and iteration statements condition

statement

true

false if condition : statement

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 9 / 26

(4)

Control Flow – if-else

condition

statement1

statement2

true

false

if condition : statement1 else:

statement2

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 10 / 26

Control Flow – while

condition

statement

true

false

while condition : statement

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 11 / 26

Kontrollfluss break in while -Schleife

condition

statement

break

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 12 / 26

Functions

(5)

Functions

So far. . .

One algorithm per file

Statements are processed sequentially Usage of loops and control structures

Group related code as function

def welcome():

date = "October 21, 2021"

print("Hello", username, "!")

print("Welcome to the lecture on", date)

welcome()

Definition of a function Optional list of parameters

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 13 / 26

Analogy to Natural Languages

Python “understands” some specific words These are called keywords: def , if , while , etc.

Basic stock of functions: print() , range() , input() , etc.

def f(): ⇐⇒ Python “learns” new word f From Merriam-Webster dictionary

re · frig · er · a · tor

A room or appliance for keeping food or other items cool

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 14 / 26

Analogy to Natural Languages

def welcome():

date = "October 21, 2021"

print("Hello", username, "!")

print("Welcome to the lecture on", date)

username = input("Enter username:") if username == "hjb" or username == "dkomm":

welcome()

...

else:

print("Username not found.") ...

date = "October 21, 2021"

print("Hello", username, "!")

print("Welcome to the lecture on", date)

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 15 / 26

Analogy to Mathematical Functions

f (x) = 2 · x + 1

Functions in Python

Parameter x is passed to function Value is passed back using return

def f(x):

y = 2 * x + 1 return y def f(x):

return 2 * x + 1

return without argument is used to simply end the function call

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 16 / 26

(6)

Analogy to Mathematical Functions

def f(x):

return 2 * x + 1

By using return , the function call represents the corresponding value; the call is ended

print(f(5)) results in output 11 z = f(6) assigns z the value 13

z = 3 * f(2) + f(4) assigns z the value 24

b = (f(10) > 20) assigns b the Boolean value True

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 17 / 26

Functions with Parameters

def checkuser(givenname):

validnames = [ "dbert", "dimant", "odudler", "fafrei", "shorvath", "ssteiner" ] if givenname in validnames:

return True else:

return False

username = input("Enter username:") if checkuser(username) == True:

print("Welcome", username)

password = input("Enter your password:") ...

else:

print("Username not found.")

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 18 / 26

Functions with Parameters

username = input(”Enter username:”) Enter username: dkomm

username = dkomm

if checkuser( dkomm ) == True:

def checkuser(dkomm):

validnames = [ ”dbert”, ”dimant”, ”odudler”, ”fafrei”, ”shorvath”, ”ssteiner” ] if dkomm in validnames:

return True else:

return False if False == True:

Username not found.

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 19 / 26

Definition of Functions

Function has to be defined before it can be used

def f(x):

return 2 * x + 1 print(f(2))

works, but not. . .

print(f(2))

def f(x):

return 2 * x + 1

NameError: name ’f’ is not defined

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 20 / 26

(7)

Functions

Example – Cookie Calculator

Example – Cookie Calculator

children = int(input("Number of children:")) cookies = int(input("Number of cookies:"))

print("Every child receives", cookies // children, "cookies") print("Dad receives", cookies % children, "cookies")

We want to make sure that children is positive and that each child gets at least one cookie

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 21 / 26

Cookie Calculator – Check Input

From this . . .

children = int(input("Number of children:"))

. . . we go to this

while True:

children = int(input("Number of children:")) if children >= 1:

break else:

print("Value needs to be at least 1")

Analogously, we have to check that cookies >= children

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 22 / 26

Cookie Calculator – Getting Complicated

while True:

children = int(input("Number of children:")) if children >= 1:

break else:

print("Value needs to be at least 1")

while True:

cookies = int(input("Number of cookies:")) if cookies >= children:

break else:

print("Value needs to be at least", children)

print("Every child receives", cookies // cookies, "cookies") print("Dad receives", cookies % children, "cookies")

Read and check number of children

Read and check number of cookies

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 23 / 26

(8)

Cookie Calculator – Takeaway

The two code fragments are nearly identical The following aspects are different:

The prompt, i.e., "children:" vs. "cookies:"

The minimum, i.e., 1 vs. children

We can outsource the code fragment into a function and thus feature reuse We have to parameterize the different aspects

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 24 / 26

Exercise – Cookie Calculator

Write a function that

gets two parameters prompt and minimum asks the user for an integer input

returns the input using return if it is at least minimum

otherwise asks for a new input

Use the function in the cookie calculator

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 25 / 26

Exercise – Cookie Calculator

def checkinput(prompt, minimum):

while True:

x = int(input(prompt)) if x >= minimum:

return x else:

print("Value needs to be at least", minimum)

children = checkinput("Number of children:", 1) cookies = checkinput("Number of cookies:", children) print("Every child receives", cookies // cookies, "cookies") print("Dad receives", cookies % children, "cookies")

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 26 / 26

Referenzen

ÄHNLICHE DOKUMENTE

Basics of Computer Science for Human Medicine – Introduction to the Course Autumn 2021 Böckenhauer, Komm 1 / 36.?.

Basics of Computer Science for Human Medicine – Lists, strings, loops Autumn 2021 Böckenhauer, Komm 2 / 21...

Basics of Computer Science for Human Medicine – Lists, strings, loops Autumn 2021 Böckenhauer, Komm 1 / 21.

Basics of Computer Science for Human Medicine – Control Structures Autumn 2021 Böckenhauer, Komm 1 / 36... Exercise –

Basics of Computer Science for Human Medicine – Control Structures Autumn 2021 Böckenhauer, Komm 7 / 36.

Basics of Computer Science for Human Medicine – Functions and return values Autumn 2021 Böckenhauer, Komm 2 / 26... but can in general not be

Basics of Computer Science for Human Medicine – Reading in Data and Sorting Autumn 2021 Böckenhauer, Komm 7 / 28... Then the left algorithm is faster ï Loop is left after

Basics of Computer Science for Human Medicine – numpy, matplotlib Autumn 2021 Böckenhauer, Komm 4 /