Professional Documents
Culture Documents
Session #4
This Lecture
• Session-03 review
• Functions
• Built-in functions
• Library functions
• Writing
• Writing data from RAM to a newly created file on Hard disk.
• Note: Writing to an existing file overwrites the original data in that file
• Appending
• Adding data to the end of an existing file
3
What are the other file operations?
R RB R+ RB+
W WB W+ WB+
A AB A+ AB+
File functions
• open() and close()
• open() requires two pieces of input, (called arguments) a file name
and a mode of opening, for example, open(infileName, ‘r’)
• open() returns an integer that enables a file buffer to be accessed
• Infile = open(‘students.txt’,’r’)
6
Functions
• Useful for breaking up a large program to make it easier to read and
maintain.
• The arguments
• Students.txt, r are inputs to open
• Line[:-1] is the input to print
• No input to close.
28 November, 2020 8
Using functions
• When a function is called, control passes to the function
28 November, 2020 9
Different types of functions
• Built-in functions
• Library functions
• float(“7.8”) → 7.8
• int(7.8) → 7
• round(7.8) → 8
• len(“a string”) → 8
28 November, 2020 11
Familiar functions
• Library functions
• math.sqrt(144) → 12.0
• math.sqrt() - the argument can be of type int or float, a float is returned
28 November, 2020 12
User defined functions
18
Logic
• If an employee works for 30 hours. We have to calculate 30*20 and
return $600 as the answer.
• 20 hours = $400
• 40 hours = $800
Pseudocode
Main function
1. Read the input from user 1. Read input from the main function
• How many hours employee has worked? 2. Calculate employee wage
2. Call the function with user input 3. Return output to main
• Lets call it calc_wage()
3. Receive input from function
4. Print output
20
Pseudocode - main
• Print wage_to_pay
Pseudocode – function calc_wage
calculate
salary
23
Program structure
# define function calc_wage to read input hours_worked.
# set hourly rate to 20
# calculte wage and return to main
# start the main function.
Def main()
#Ask user for the number of hours worked.
main()
Develop the code in the class
25
Structure of code
• Always try to write a program in which main() is used simply to call a
series of functions.
26
Next Weeks Lecture
• Decision structures
• Multiple decisions
• Indefinite loops
• Loop/decision combinations
• Nested loops