A function is a block of code that is named and can be called at any time to repeat repetitive code. A function may have values (called arguments) passed into it to perform calculations and return values, or the function may not return any values at all.
Step One - Declare (create the function) - 2 types
Function with no arguments
def my_function_name():
code.......
Function with no arguments example
#define functions at the beginning of your program
def introduction():
print("Welcome to the maths challenge!")
global difficulty
difficulty = input("Please enter E or H: ")
#execute functions
introduction()
print("The difficulty you have chosen is " + difficulty)
For more on local / global scope of variables and some further examples (academic, not necessarily practical), head to this link: https://www.geeksforgeeks.org/global-local-variables-python/
Function with Arguments - to return a value, use the keyword return
def function_with_arguments(a,b):
return a + b
Step Two - Call the function - make the function do its thing
#no arguments
my_function()
#with arguments - need to store returned value in a variable
x = function_with_arguments(2,3)
x = 5
Example #1
#defining a simple function
def printMe(string):
print("This passes a string into a function")
print (string)
#calling a simple function
printMe("Hello World")
Example #2
def happyBirthday(firstName, secondName):
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday, dear " + firstName + " " + secondName)
print("Happy Birthday to you!")
happyBirthday("John","Smith")
#variables can be passed into this function
happyBirthday(var1,var2)
Example #3
from random import randint
def randomAdder():
num1 = randint(10,50)
print(num1)
num2 = randint(10,50)
print(num2)
print ("Add these two numbers and you get")
total = int(num1) + int(num2)
print(total)
randomAdder()
Example #4
def addTwoInputs():
num1 = input ("Type in first number")
num2 = input ("Type in second number")
print ("Add these two numbers and you get")
total = int(num1) + int(num2)
print(total)
addTwoInputs()
Example #5
def addTwoValues(value1,value2):
total = int(value1) + int(value2)
print ("Adding " + str(value1) + " and " + str(value2) + " equals " + str(total))
print(total)
addTwoValues(1,3)
#variables can be passed into this function
addTwoValues(variable1,variable2)
In Python you can use libraries to access other file types like text, excel, CSV etc. The first step is to open a stream to the file you wish to access using the open command. There are multiple read / write modes that you can use:
‘r’ – Read mode which is used when a file only needs to be read. The stream is positioned at the beginning of the file.
'r+' – Read and write mode, opens a file for reading and writing actions. The stream is positioned at the beginning of the file.
‘w’ – Truncate a file to zero length or creates a new text file for writing. The stream is positioned at the beginning of the file. Known as write mode which is used to edit and write new information to the file. NOTE: any existing files with the same name will be erased when this mode is activated.
'w+' – Opens a file for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
‘a’ – Opens a file for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file. Appending mode, which is used to add new data to the end of a file; that is new information is automatically appended to the end, irrespective of any intervening fseek(3) or similar.
'a+' – Opens a file for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.
NOTE:Python v3 adds a number of additional modes. Here's a link to the documentation.
Sources and further reading:
https://www.guru99.com/reading-and-writing-files-in-python.html
http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
#syntax to open an existing file: filename = open('name of file','mode')
#open a text file and pull lines into a list
file1 = open('DB','r')
#read file contents into a new list (alist), with each new entry in the list based on a new line
alist = file1.read().splitlines()
#print the list in the python console
print(alist)
file2 = open('testfile.txt','w')
file2.write('Hello World. \n')
file2.write('This is our new text file. \n')
file2.write('and this is another line. \n')
file2.write('Why? Because we can. \n \n')
file2.write('This does ALMOST the same thing. \n Except it is in one line \n of code. \n Can you see the difference?')
file2.close()
What is a CSV file?
A CSV file (Comma Separated Values file) is a type of plain text file that uses specific structuring to arrange tabular data. Because it’s a plain text file, it can contain only actual text data; names printable ASCII or Unicode characters. The structure of a CSV file is given away by its name. Normally, CSV files use a comma to separate each specific data value. Here’s what that structure looks like:
column 1 name,column 2 name, column 3 name
first row data 1,first row data 2,first row data 3
second row data 1,second row data 2,second row data 3
...
Reading CSV Files With csv
Reading from a CSV file is done using the reader object. The CSV file is opened as a text file with Python’s built-in open() function, which returns a file object. This is then passed to the reader, which does the heavy lifting. Here’s the employee_birthday.txt file:
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
Heres the code to read it:
import csv
with open('employee_birthday.txt') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count += 1
else:
print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
line_count += 1
print(f'Processed {line_count} lines.')
This results in the following output:
Column names are name, department, birthday month
John Smith works in the Accounting department, and was born in November.
Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
Source and tutorial for you to complete: https://realpython.com/python-csv/