Python Programming

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

boolean expressions

A boolean expression is a statement that can either be True or False.

Boolean operators: AND

AND combines two boolean values and evaluates as True if both its components are True, but False otherwise. syntax: and True : True = True False : False = False True: False = False False: True = False

if statement

Allows statements to be conditionally executed or skipped over

else if statements

An elif statement checks another condition after the previous if statements conditions aren't met.

name error

an exception that occurs when Python is asked to produce a value for a variable that has not been assigned a value

lists

an ordered set of objects in Python begins and ends with brackets and individual items are separated with commas

positional arguments

arguments that are assigned based upon position when calling a function EX: function(argument1, argument2) the parameters will go to the parameter in each position (1 to position 1, 2 to position 2)

strings

blocks of text designated with " " or ' '

written understanding of nested for loops regarding lists inside of lists

called the outside list and iterate through the inside list then call the inside list and iterate through the data contained in the inside lists

final example of list comprehension

celsius = [0, 10, 15, 32, -5, 27, 3] fahrenheit = [degree * 9/5 + 32 for degree in celsius] print(fahrenheit) Brilliant!

string concatenation

combining multiple strings or variables for display as one message using the + operator between them (cannot take non-string variables)

# comment here

comments are designated with a # to ensure python ignores your text

continue as an element of loops

continue allows an iteration to be skipped if the continue function is used based upon conditions or a blanket use of it

str(variable)

converts the variable into a string and is very useful for string concatenation

list.count() function

counts how many times the selected item appears in a list syntax: listName.count(input)

default arguments for parameters

declaring what the argument will be by setting it in the function declaration def greet_customer(special_item, grocery_store="Engrossing Grocers"): print("Welcome to "+ grocery_store + ".") print("Our special is " + special_item + ".") print("Have fun shopping!") notice how grocery store was assigned a value

return example

def divide_by_four(input_number): return input_number/4

try and expect example

def divides(a,b): try: result = a / b print (result) except ZeroDivisionError: print ("Can't divide by zero!")

declaring a function

def function_name(): some code #the above 'some code' line would be indented

returning and collecting multiple values with functions

def get_boundaries(target, margin): low_limit = target - margin high_limit = margin + target return low_limit, high_limit low, high = get_boundaries(target = 100, margin = 20)

declaring a function example

def greet_customer(): print("Welcome to Engrossing Grocers.") print("Our special is mandarin oranges.") print("Have fun shopping!") greet_customer() # prints greeting lines

multiple parameters (separated by a comma)

def greet_customer(grocery_store, special_item): print("Welcome to "+ grocery_store + ".") print("Our special is " + special_item + ".") print("Have fun shopping!") greet_customer("Stu's Staples", "papayas")

parameter example

def greet_customer(special_item): print("Welcome to Engrossing Grocers.") print("Our special is " + special_item + ".") print("Have fun shopping!") special_item is an variable passed as an argument in the function

else statements

defines what happens for anything not included in the if statement

len(listname)

determines the length of a list syntax: len()

tuple unpacking

elements of a tuple can be assigned to other variables to be used in normal operations assigned tuple elements can be modified

try and except statements

embeds into a function and the statement under try will be executed If an exception is raised during this execution and that exception matches the keyword in the except statement then the try statement will terminate and the except statement will execute.

another example of the use of list comprehension

messages = [user + " please follow me!" for user in usernames] Takes a string in usernames Assigns that string to a variable called user Adds " please follow me!" to user Appends that concatenation to the new list called messages Repeats steps 1-4 for all of the strings in usernames

collecting multiple returned values

multiple values can be collected through returning by assigning them to variables when calling a function x_squared, y_squared = square_point(1, 3)

returning multiple values

multiple values can be returned by separating them with a comma return low_limit, high_limit

zip syntax

names_and_heights = zip(names, heights)

nested loops

occur when a loop structure exists within another loop structure allows iterating individual situations when needed as a subset of other loops

python int to float conversion

python automatically converts integers into floats when performing division to allow decimal places to exist in the answer

range starting at a number other than 0

range(base number, n + 1 number)

range function that can skip numbers on a pattern

range(base number, n +1, skipping number)

for team in project_teams: for student in team: print(student)

requires indentation and is an example of a nested loop where a loop exists inside of a loop

return keyword

returns a function to the user to be modified or user later can be called in functions

list()

returns a list of the items passed through list(names_and_heights)

selecting the last index of an element or counting backward

selecting last index[start:] (leave the second blank) counting back index[negative:] (leave the second blank)

keyword arguments

specifically and explicitly stating which parameter an argument will be passed into greet_customer(special_item="chips and salsa", grocery_store="Stu's Staples")

starting place of the range function

starts at 0 (based on index)

values that a list can hold

strings numbers other lists emptiness

.append(item)

takes the item in parentheses and adds it to a list can only add one item at a time

zip

takes two or more lists as inputs and returns an object that contain a list of pairs

nth time type function with modulo

the way a modulo function works is that it will spit out the same number pattern from 0 to (divisor - 1). Therefore, it can be used to spit out the same numbers and perform conditional operations based upon the numbers it gives!

while loops

the while loop performs a set of code until some condition is reached

Slice a list

using index[start:end] we can control the range of certain elements to include in a selection lower index starts at the index of the item (to include a nonzero item, use n - 1) upper index needs to be one above our needed selection (n+1)

bool variables in python

values of true and false that can be stored in variables and called for later use can be simply stored as True or False or through a condition that produces the desired true or false state

multiple variables can be added in one line with += syntax

var1 += var2 + var 3

variable declaration and assignment

variableName = Assigned Data variable type is automatically determined by Python

variable changes

variables can be modified in any way but the original variable will not change without reassignment to the variable using =

Boolean Operator: NOT

when applied to any boolean expression it reverses the boolean value. syntax: not So if we have a True statement and apply a not operator we get a False statement.

syntax error

when the syntax rules of the language are violated mistakes that prevent a programming from running or cause it to run improperly to produce a wrong result or no result at all

while loop syntax

while index < len(dog_breeds): print(dog_breeds[index]) index += 1 (to amend the condition that the loop is running on)

index of -1

allows you to select the last index of a list item

parameters

an argument that can be passed into a function to influence the result

infinite loops

loops that never end very dangerous for your programming

exponentiation syntax

(base ** power)

a tuple syntax

(item, item, item) there always needs to be a comma in a tuple, even if there is only one element in the tuple

ZeroDivisionError

Dividing a number by zero (error)

relational operators in python for equal and not equal

Equals: == Not Equals: !=

multiplying strings

Multiplying a string just makes a new string with the old one repeated!

list comprehension

Python rules for creating lists intelligently usernames = [word for word in words if word[0] == '@'] Takes an element in words Assigns that element to a variable called word Checks if word[0] == '@', and if so, it adds word to the new list, usernames. If not, nothing happens. Repeats steps 1-3 for all of the strings in words

Boolean Operators: OR

The boolean operator or combines two expressions into a larger expression that is True if either component is True. syntax: or True : True = True False : False = False False : True = True True : False = True

creating functions

To write a function, you must have a heading and an indented block of code. The heading starts with the keyword def and the name of the function, followed by parentheses, and a colon. The indented block of code performs some sort of operation.

python highlights errors with

a ^ symbol (error highlighting)

function (python)

a collection of several lines of code that can be called without having to repeat multiple lines of code repeatedly

tuple

a data structure in python that allows the user to store multiple pieces of data inside of it Tuples are immutable and cannot be changed or modified after their creation (means no editing)

int()

a function that converts a passed argument into an integer

range(number)

a function that creates a list using a single input and generates numbers starting at 0 to 1 below the provided number range(9) = [0,1,2,3,4,5,6,7,8]

sorted(list)

a function that orders a received list and can be used in assignment because it generates a new list

list.sort() function

a function that orders the received list in ABC or 123 format it does not return anything when called (it just works) so you cannot use it to create new lists through assignment

calling a tuple

a tuple must be called in the exact order as its e

f string

a type of string that is like a template literal from JS that allows calling variables in a string (python 3.6 and later) f"Printed message and called {variable}"

variables

a way of storing data so that it can be called and used as needed within a program variable names cannot have spaces or symbols outside of _ underscore and cannot begin with numbers

calculation syntax

addition: + subtraction: - multiplication: * division: / exponentiation: **

loops

affords capability to: move through each item in a list (for loops) loops that keep going until we tell them to stop (while loops) loops that create new lists (list comprehensions)

selecting list elements with index[]

allows selection of individual items with a zero-index based position syntax: list_name[indexNumber]

break as a part of for loops

allows the program to stop running when the break is hit EX: you perform a search for a particular element in a list and use an if statement to break the program when the intended target is reached

square root calculation in python

exponentiation can be used with fractional exponents to perform root calculations of square and beyond

for loop syntax

for item in list: perform action (indentation is absolutely needed)

using range in a for loop

for variable in range(number): action to perform the number is the number of times the for loop should iterate through the function

print(syntaxHere)

function that tells python to send designated object to console

function calling in python

function_name()

calling a function with a parameter

function_name(parameter)

plus equals

functions to allow the addition of another variable while also allowing assignment variable1 += variable2 adds variable 1 to variable 2 and assigns the new sum to variable1 for storage

modulo operator

gives the remainder of a division operation (the remaining part that is left after all divisible numbers are removed EX: 32 % 3 = 2) gives 0 for wholly divisible numbers the modulo operator is useful when repeated functions are necessary every nth time

use for a tuple

good for data that needs to be stored together and that isn't necessarily similar such as the qualities of a person because they are

remaining relational operators

greater than: > less than: < greater than or equal to: >= less than or equal to: <=

list comprehension example

heights = [161, 164, 156, 144, 158, 170, 163, 163, 157] can_ride_coaster = [height for height in heights if height > 161] print(can_ride_coaster)

if statement syntax:

if 2 == 4 - 2: print("apple") indentation is very important to avoid errors similar to functions in that regard

if...else statement example

if weekday: wake_up("6:30") else: sleep_in()

index error

if you try accessing an index that is too large (or does not exist)

multi-line strings

if you use three quotes at the start and end then the string can go across several lines; the newline characters are included as part of the string

assigning variables with user input

input()

number types

int = a whole number (2) float = a decimal-based number (2.156)

function declaration

is actually called a function definition in python

indentation (whitespace)

is crucial to the execution of functions items not indented properly will not be in the function and will instead be executed on their own or throw errors

scope

limitations applied to variables dependent on the location of their declaration variables declared in functions have functions scope and are not accessible elsewhere (will throw an error when called) variables declared outside functions are accessible inside and outside functions

growing a list with +

lists can be combined and stored together with + new_orders = orders + ['lilac', 'iris']


Ensembles d'études connexes

Lesson 18 In-Class Quiz & Self-Assessment

View Set

Accounting 1 - Quiz over Purchases and Sales JE

View Set

Digital Skills for the Workplace Final Exam

View Set

GCSE Lit Revision: Mac, AIC and L&R

View Set

Prep U Chapter 34: Assessment and Management of Patients with Inflammatory Rheumatic Disorders

View Set

Emergency Action Plans and Fire Protection

View Set

BUS101: Chapter 9- SUmmary Learning Outcomes

View Set