CSC 1010 Lecture 5 1
CSC 1010 Programming for All
Lecture 5 Working with Functions
What do we know so far?
- Class – lecture, lab, Rephactor, Quick Checks, R&R
- Solve problems, computers useful, user vs. programmer
- Sequence of instructions, algorithm is step‐by‐step
- Python is 3rd most popular language, core principles
- Syntax, runtime, & logic errors, testing & debugging
- Hardware vs. software
- control flow – step‐by‐step, function call, conditional, loop
- IDLE shell, editor, install Python, Hello World
- Intrepreter, compiler, Python Standard Library
- Variables, assignment, numeric expr., precedence
- Print function, Strings, concatenation, indexes, in, *
- Interactive programs, if, if‐else, if‐elif‐else, int, float
- Boolean expressions: ==, !‐, <, <=, >, >=, not, and, or
- Input function, comparing strings, programming conventions
- variable & function names lowercase, CONSTANTS, indent
- while, for, range, augmented assignments, palindromes
- Turtle Graphics, forward, left, right, pensize, pencolor, dot, circle
- goto, penup, pendown, fillcolor, begin_fill, end_fill, speed
- easter eggs?
2
Functions
A function is a collection of programming statements that are given a name. When you call (or invoke) a function, the statements of the function are executed. Functions can be:
- called (or invoked)
- user‐defined
- built‐in
- external, in a module
3
Calling Functions
When you call a function, the code inside the function is
- executed. When done, execution picks up at the spot where it
was called.
4
A simple call to the print function is:
pr i nt ( ' Hel l o, Uni ver se! ' )
Calling Functions
The arguments are what is passed into a function call:
5
m y_f unct i on( ar g1, ar g2, ar g3)
There must be an argument for each parameters in the function definition. The print function is an example of a function that takes a variable number of arguments:
pr i nt ( ' Hel l o' ) pr i nt ( ' Num ber : ' , 5, ' Let t er : ' , ' a' ) pr i nt ( )
To call external functions, you may need to import them first
The import Statement
Use the import statement to use external functions
6
i m por t r andom num = r andom . r andi nt ( ) pr i nt ( ' The num ber i s: ' , num )
To use external functions without needing to use their module name to invoke them, use the from…import syntax
f r om r andom i m por t * num = r andi nt ( ) pr i nt ( ' The num ber i s: ' , num )