Introduction To Python
Introduction To Python
add_numbers()
Note: The function definition must come before the function
call.
Passing arguments to function
def add_numbers(first_number, second_number):
total = first_number + second_number
print(total)
add_numbers(1.11, 2.22)
• positional arguments
Keyword arguments
def say_names_of_couple(husband_name, wife_name):
print("The names of the couple are " + husband_name
+ " and " + wife_name)
say_names_of_couple(husband_name="Bill",
wife_name="Zelda")
Assigning default values
def calc_tax(sales_total, tax_rate=.04):
print(sales_total * tax_rate)
• You can mix positional arguments and keyword
arguments. For example, you can code…
give_greeting("Hello there", first_name="Al”)
• Positional arguments must come before keyword
arguments
• Lists and dictionaries, as well as strings and numbers,
can be arguments passed to a function
Unknown number of arguments
def display_result(winner, score, **other_info):
print("The winner was " + winner)
print("The score was " + score)
for key, value in other_info.items():
print(key + ": " + value)
print(b)
you'll get an error message
• A variable defined in a function is recognized inside the function—
and only inside the function
• Remember, variables defined in the main code are global, meaning
that they're recognized everywhere, including inside functions
Functions within functions
def say_something():
what_to_say = "Hi"
now_say_it()
def now_say_it():
print(what_to_say)
While loops
• while user_input != "q":
• user_input = input("Enter a city, or q to quit:")
• break
• True, False
Classes
• In Python, classes are templates. They help you standardize
and organize information
class Patient():
def __init__(self, last_name):
self.last_name = last_name
pid4343 = Patient("Taleb")
• Instead of creating a class and then creating multiple instances
of the class, you could create a dictionary for each patient
Adding more attributes
• self.first_name = first_name
• self.age = age
• import calculations
• tax_for_this_order =
calculations.calc_tax(sales_total=101.37, tax_rate=.05)
CSV files
Year,Event,Winner
1995,Best-Kept Lawn,None
1999,Gobstones,Welch National
2006,World Cup,Burkina Faso
• import csv
• with open("competitions.csv") as f:
• contents_of_file = csv.reader(f)
• for each_line in contents_of_f:
• potter_competitions += each_line
Picking information from CSV
• print(potter_competitions[4])
• index_number_of_target =
potter_competitions.index("Best-Kept Lawn")
Loading information in CSV
• with open("whatever.csv", "w", newline="") as f:
• data_handler = csv.writer(f, delimiter=",")
• data_handler.writerow(["Year", "Event", "Winner"])
• data_handler.writerow(["1995", "Best-Kept Lawn", "None"])
• data_handler.writerow(["1999", "Gobstones", "Welch
National"])
• Use with open("whatever.csv", "a", newline="") as f: to
append
Saving a python list to dictionary
• You can't save a Python list in a text file. You can only
save a text string
• You can save a list in a CSV file, but a more
straightforward approach is to use JSON.
• The four characters stand for JavaScript Object Notation.
• import json
• alphabet_letters = ["a", "b", "c"]
• with open("alphabet_list.json", "w") as f:
• json.dump(alphabet_letters, f)
Retrieving contents from json
• with open("customer_29876.json") as f:
• customer_29876 = json.load(f)
Exception handling
• Bad things can happen to good programs.
• Try
• Except FileNotFoundError: