Python Crash Course Vocabulary

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Test case

A collection of unit tests that together prove that a function behaves as it's supposed to, within the full range of situations you expect it to handle.

Docstring

A comment that describes what the function does. It uses triple quotes, """ ... """.

Dictionary

A dictionary in Python is a collection of key-value pairs. Dictionaries allow you to connect pieces of related information. They are wrapped in braces, { }, with a series of key-value pairs inside the braces. e.g. Consider a game featuring alien that can have different colors and point values. This simple dictionary stores information about a particular alien: alien_0 = {'color': 'green', 'points': 5} print(alien_0['color']) print(alien_0['points'])

super() function

A function that helps Python make connections between the parent and child class.

Method

A function that's part of a class. e.g. class Dog(): --snip-- my_dog = Dog('willie', 6) my_dog.sit() my_dog.roll_over()

Key

A key is connected to a value, and you can use a key to access values associated with that key. A key's value can be a number, a string, a list, or even another dictionary. You any use any object that you can create in Python as a value in a dictionary. e.g. alien_0 = {'color': 'green', 'points': 5} 'color' and 'points' are keys, and 'green' and 5 are values.

Key-value pair

A key-value pair is a set of keys and values associated with each other. When you provide a key, Python returns the value associated with that key. Every key is connected to its value by a colon, and individual key-value pairs are separated by commas. You can store as many key-value pairs as you want in a dictionary. e.g. alien_0 = {'color': 'green'} This dictionary stores one piece of information about alien_0, namely the alien's color. The string 'color' is a key in this dictionary, and its associated value is 'green'.

Keyword arguments

A keyword argument is a name-value pair that you pass to a function. You directly associate the name and the value within the argument, so when you pass the argument to the function, there's no confusion. Keyword arguments free you from having to worry about correctly ordering your arguments in the function call, and clarify the role of each value in the function call. e.g. def describe_pet(animal_type, pet_name): ----"""Display information about a pet.""" ----print("\nI have a " + animal_type + ".") ----print("My " + animal_type "'s name is " + pet_name.title() + ".") describe_pet(animal_type='hamster', pet_name='harry')

While loop

A loop that runs as long as, or while, a certain condition is true. e.g. current_number = 1 while current_number <= 5: ----print(current_number) ----current_number += 1

Modules

A module is a file ending in .py that contains the code you want to import into your program. Helps organize the main program files.

Child class (subclass)

A new class from inheritance; the child class inherits every attribute and method from its parent class but is also free to define new attributes and methods of its own. e.g. class ElectricCar(Car): ----"""Represent aspects of a car, specific to electric vehicles.""" --snip--

Argument

A piece of information that is passed from a function call to a function. e.g. greet_user('jesse') 'jesse' is the argument.

Parameter

A piece of information the function needs to do its job. e.g. def greet_user(username): "username" is the parameter in the function.

__init__() method

A special method Python runs automatically whenever we create a new instance based on x class. e.g. class Dog(): ----"""A simple attempt to model a dog.""" ----def __init__(self, name, age): --------"""Initialize name and age attributes.""" --------self.name = name --------self.age = age

Full coverage

A test with full coverage includes a full range of unit tests covering all the possible ways you can use a function.

Flag

A variable that determines whether or not the entire program is active. You can set the flag to True (running) or False (stop running), and then have a while statement check the condition. prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " active = True while active: ----message = input(prompt) ----if message == 'quit': --------active = False ----else: --------print(message)

json module

Allows you to dump simple Python data structures into a file and load the data from that file the next time the program runs. e.g. Dump: import json numbers = [2, 3, 5, 7, 11, 13] filename = 'numbers.json' with open(filename, 'w') as f_obj: ----json.dump(numbers, f_obj) Load: import json filename = 'numbers.json' with open(filename, 'w') as f_obj: ----numbers = json.load(numbers, f_obj) print(numbers)

Alias

An alternate name, similar to a nickname for the function. e.g. We can give the function make_pizza() an alias, mp(), by importing make_pizza as mp. The 'as' keyword renames a function using the alias you provide: from pizza import make_pizza as mp mp(16, 'pepperoni')

from module_name import *

Another way of importing all classes. Not advised to use.

Positional arguments

Because a function definition can have multiple parameters, a function call may need multiple arguments. One way you can pass arguments to your functions is by positional arguments. Positional arguments must be in the same order the parameters were written (order matters!). When you call a function, Python must match each argument in the function call with a parameter in the function definition. The simplest way to do this is based on the order of the arguments provided. e.g. def describe_pet(animal_type, pet_name): ----"""Display information about a pet.""" ----print("\nI have a " + animal_type + ".") ----print("My " + animal_type "'s name is " + pet_name.title() + ".") describe_pet('hamster', 'harry')

Double asterisks before parameter

Causes Python to create an empty dictionary. e.g. def build_profile(first, last, **user_info): Creates an empty dictionary called user_info.

Classes

Classes are used in object oriented programming. They define general behavior that a whole category of objects can have, and represent real world things and situations. e.g. class Dog(): ----"""A simple attempt to model a dog.""" ----def __init__(self, name, age): --------"""Initialize name and age attributes.""" --------self.name = name --------self.age = age ----def sit(self): --------"""Simulate a dog sitting in response to a command.""" --------print(self.name.title() + " is now sitting.") ----def roll_over(self): --------"""Simulate rolling over in response to a command.""" --------print(self.name.title() + " rolled over!")

count_words() function

Counts each value in the list. e.g. def count_words(filename): ----""""Count the approximate number of words in a file.""" ----try: --------with open(filename) as f_obj: ------------contents = f_obj.read() ----except FileNotFoundError: --------msg = "Sorry, the file " + filename + " does not exist." --------print(msg) ----else: --------# Count approximate number of words in the file. --------words = contents.split() --------num_words = len(words) --------print("The file " + filename + " has about " + str(num_words) + " words.") filename = 'alice.txt' count_words(filename)

Read an entire file

Example 1: with open('filename.txt') as file_object: ----contents = file_object.read() ----print(contents) Example 2: with open('text_files/filename.txt') as file_object: ----contents = file_object.read() ----print(contents) Example 3: file_path = '/home/jcartaya/other_files/text_files/filename.txt' with open(file_path) as file_object: ----contents = file_object.read() ----print(contents)

Exceptions

Exceptions are special objects Python creates to manage errors that arise while a program is running. Whenever an error occurs that makes Python unsure what to do next, it creates an exception object. If you write code that handles the exception, the program will continue running. If you don't handle the exception, the program will halt and show a traceback, which includes a report of the exception that was raised. Exceptions are handled with try-except blocks. e.g. try: ----print(5/0) except ZeroDivisionError: ----print("You can't divide by zero!") else: ----print(answer)

Functions

Functions are named blocks of code that are designed to do one specific job. When you want to perform a particular task that you've defined in a function, you call the name of the function responsible for it. e.g. def greet_user(): ----"""Display a simple greeting.""" ----print("Hello!") greet_user()

Python standard library

Set of modules included with every Python installation.

Nesting

Storing a set of dictionaries in a list or a list of items as a value in a dictionary. You can nest a set of dictionaries inside a list, a list of items inside a dictionary, or even a dictionary inside another dictionary. e.g. alien_0 = {'color': 'green', 'points': 5} alien_1 = {'color': 'yellow', 'points': 10} alien_2 = {'color': 'red', 'points': 12} aliens = [alien_0, alien_1, alien_2] for alien in aliens: ----print(alien)

readlines() method

Takes each line from the file and stores it in a list. This list is then stored in lines, which we can continue to work with after the 'with' block ends. e.g. filename = 'pi_digits.txt' with open(filename) as file_object: ----lines = file_object.readlines() for line in lines: ----print(line.rstrip())

Absolute file path

Tells Python exactly where the file is on your computer regardless of where the program that's being executed is stored. e.g. file_path = '/home/jcartaya/other_files/text_files/filename.txt' with open(file_path)

Function definition

Tells Python the name of the function and, if applicable, what kind of information the function needs to do its job. e.g. def function_name():

Function call

Tells Python to execute the code in the function. To call a function, you write the name of the function, followed by any necessary information in parentheses.

Relative file path

Tells Python to look for a given location relative to the directory where the currently running program file is stored. e.g. open('text_files/filename.txt')

File path

Tells Python to look in a specific location on your system.

input() function

The input() function pauses your program and waits for the user to enter some text. Once Python receives the user's input, it stores it in a variable to make it convenient for you to work with. e.g. The following program asks the user to enter some text, then displays that message back to the user: message = input("Tell me something, and I will repeat it back to you: ") print(message) The input() function takes one argument: the prompt, or instructions, that we want to display to the user so they know what to do.

Parent class (superclass)

The original class from inheritance. e.g. class Car(): ----"""A simple attempt to represent a car.""" --snip--

Return value

The value that the function returns. The return statement takes a value from inside a function and sends it back to the line that called the function. def get_formatted_name(first_name, last_name): ----"""Return a full name, neatly formatted.""" ----full_name = first_name + ' ' + last_name ----return full_name.title() musician = get_formatted_name('jimi', 'hendrix') print(musician)

write() function

This function lets you write text to a file. e.g. with open(filename, 'w') as file_object: ----file_object.write("I love programming.")

items() method

This method reruns a list of key-value pairs. Used when looping through a dictionary by a for loop. e.g. for key, value in user_0.items(): ----print("\nKey: " + key) ----print("Value: " + value)

keys() method

This method returns all key values. e.g. favorite_languages = { ----'jen': 'python', ----'sarah': 'c', ----'edward': 'ruby', ----'phil': 'python', } for name in favorite_languages.keys(): ----print(name.title()) ** One way to return items in a certain order is to sort the keys as they are returned in the for loop. You can use the sorted() function to get a copy of the keys in order: e.g. for name in sorted(favorite_languages.keys()):

values() method

This method returns all value values. e.g. favorite_languages = { ----'jen': 'python', ----'sarah': 'c', ----'edward': 'ruby', ----'phil': 'python', } print("The following languages have been mentioned:") for language in favorite_languages.values(): ----print(language.title()) ** When you wrap set() around a list that contains duplicate items, Python identifies the unique items in the list and builds a set from those items. e.g. for language in set(favorite_languages.values()):

split() method

This method separates a string into parts wherever it finds a space and stores all the parts of the string in a list. e.g. >>> title = "Alice in Wonderland" >>> title.split() ['Alice', 'in', 'Wonderland']

open() function

To do any work with a file, even just printing its contents, you first need to open the file to access it. The open() function needs one argument: the name of the file you want to open. Python looks for this file in the directory where the program that's currently being executed is stored.

Attributes

Variables that are accessible through instances. e.g. self.name in: class Dog(): ----"""A simple attempt to model a dog.""" ----def __init__(self, name, age): --------"""Initialize name and age attributes.""" --------self.name = name --------self.age = age

Unit test

Verifies that one specific aspect of a function's behavior is correct.

Default value

When writing a function, you can define a default value for each parameter. If an argument for a parameter is provided in the function call, Python uses the argument value. If not, it uses the parameter's default value. So when you define a default value for a parameter, you can exclude the corresponding argument you'd usually write in the function call. e.g. If you notice that most of the calls to describe_pet() are being used to describe dogs, you can set the default value of animal_type to 'dog'. Now anyone calling describe_pet() for a dog can omit that information. def describe_pet(pet_name, animal_type= 'dog'): ----"""Display information about a pet.""" ----print("\nI have a " + animal_type + ".") ----print("My " + animal_type "'s name is " + pet_name.title() + ".") describe_pet(pet_name= 'willie')

Instantiation

When you create individual objects from the class, each object is automatically equipped with the general behavior; you can then give each object whatever unique traits you desire. Instantiation is the act of making an object from a class; it is an instance of a class. e.g. class Dog(): --snip-- my_dog = Dog('willie', 6) print("My dog's name is " my_dog.name.title() + " and he is " + str(my_dog.age) + " years old.")

Inheritance

If the class you're writing is a specialized version of another class you wrote, you can use inheritance. When one class inherits from another, it automatically take on all the attributes and methods of the first class. e.g. class Car(): ----"""A simple attempt to represent a car.""" ----def __init__(self, make, model, year): --------self.make = make --------self.model = model --------self.year = year --------self.odometer_reading = 0 ----def get_descriptive_name(self): --------long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() ----def read_odometer(self): --------print("This car has " + str(self.odometer_reading) + " miles on it.") ----def update_odometer(self, mileage): --------if mileage >= self.odometer_reading: ------------self.odometer_reading = mileage --------else: ------------print("You can't roll back an odometer!") ----def increment_odometer(self, miles): --------self.odometer_reading += miles class ElectricCar(Car): ----"""Represent aspects of a car, specific to electric vehicles.""" ---- def __init__(self, make, model, year): --------"""Initialize attributes of the parent class.""" --------super().__init__(make, model, year) my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name())

Import

Import statements import modules into main program. They tell Python to make the code in a module available in the currently running program file. e.g. import nuke nuke.createNode('Blur')

Append mode

Lets you add content to a file instead of writing over existing content. e.g. filename = 'programming.txt' with open(filename, 'a') as file object: ----file_object.write("I also love finding meaning in large datasets.\n") ----file_object.write("I love creating apps that can run in a browser.\n")

pass statement

Makes a program fail silently by explicitly telling Python to do nothing in the except block. e.g. def count_words(filename): ----""""Count the approximate number of words in a file.""" ----try: --snip-- ----except FileNotFoundError: --------pass ----else: --snip-- filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] for filename in filenames: ----count_words(filename)

unittest module

Provides tools for testing your code. e.g. import unittest from name_function import get_formatted_name class NamesTestCase(unittest.TestCase): ----"""Tests for 'name_function.py'.""" ----def test_first_last_name(self): --------"""Do names like 'Janis Joplin' work?""" --------formatted_name = get_formatted_name('janis', 'joplin') --------self.assertEqual(formatted_name, 'Janis Joplin')


Set pelajaran terkait

Chapter 1, AP Psychology Final Semester 1

View Set

Infant and Childhood Development: Final Exam

View Set

Stupid Smartbook Connect Orientation Assignment

View Set

Reformation an Religious Warfare in the Sixteenth Century: Chapter 13

View Set

CA Real Estate Practices Chapter 1

View Set

D-03 Identify the Defining Features of Single-Subject Experimental Designs (e.g., Individuals Serve as Their Own Controls, Repeated Measures, Prediction, Verification, Replication)

View Set

1R Physics Ch 5 Projectile Motion TEST Mr. Lundquist Oct 3 2014

View Set