Computer Science Codecademy
:
A colon : to mark the end of the function header.
Local Scope
If we define a variable inside of a function then it is known as a local variable — a variable defined in a local scope. We can think of it being locally defined to only accessible inside the function. Here is what a local variable might look like inside of a program: def welcome_user(name): greeting = "Hello " + name + "!" print(greeting) welcome_user("User") The local variable in this example is greeting. This is a variable that is created inside of the function welcome_user() and thus only has scope locally within that function.
Scope
In Python, a scope refers to the region of a program where a particular variable or name is accessible. There are four different types of scopes in Python: 1. Local Scope 2. Enclosing Scope 3. Global Scope 4. Built-In Scope
Counting in a List
In Python, it is common to want to count occurrences of an item in a list. If we want to know how many times i appears in this word, we can use the list method called .count(): num_i = letters.count("i") print(num_i) We can even use .count() to count element appearances in a two-dimensional list. number_collection = [[100, 200], [100, 200], [475, 29], [34, 34]] If we wanted to know how often the sublist [100, 200] appears: num_pairs = number_collection.count([100, 200]) print(num_pairs)
Growing a List: Plus (+)
Using + Concatenation we can combine lists. broken_prices = [5, 3, 4, 5, 4] + [4,5,6] orders_combined = orders + new_orders (combine two lists)
Modifying 2D Lists
Utilize the same input as accessing a 2d list. Use the indexes [][] = string/bool/int/float/etc. to adjust the proper element in the index incoming_class = [['Kenny', 'American', 9], ['Tanya', 'Ukrainian', 9], ['Madison', 'Indian', 7]] incoming_class[2][2] = 8 Would change Madison's number to 8 or incoming_class[-3][-3] = 'Ken' to change 'kenny' to 'ken'
Length
When we apply len() to a list, we get the number of elements in that list: my_list = [1, 2, 3, 4, 5] print(len(my_list)) 5
The Power of Range!
For example, range(2, 9, 2) will give us a list where each number is 2 greater than the previous number: my_range2 = range(2, 9, 2) print(list(my_range2)) Would output: [2, 4, 6, 8] #(starting_item, ending_item -1, difference)
Functions
Functions are a convenient way to group our code into reusable blocks. A function contains a sequence of steps that can be performed repeatedly throughout a program without having to repeat the process of writing the same code again.
Indefinite Iteration Loop
This loop continues to run based upon how many times the condition is met.
Else Statements
else statements allow us to elegantly describe what we want our code to do when certain conditions are not met.
Empty Lists
empty_list = [] it's because we're planning on filling it up later based on some other input.
String Methods
capitalize(): Capitalizes the first character of a string. lower(): Converts all characters in a string to lowercase. upper(): Converts all characters in a string to uppercase. replace(): Replaces all occurrences of a substring with a new substring. split(): Splits a string into a list of substrings based on a delimiter.
Boolean Operators: and (logical operators)
combine smaller boolean expressions into larger boolean expressions. and allows you to check if multiple conditions are met.
Elegant While Loops(One-Line)
count = 0 while count <= 3: print(count); count += 1 Note: Here we separate each statement with a ; to denote a separate line of code.
Remove Method on a 2D List
customer_data = [['Ainsley', 'Small', True], ['Ben', 'Large', False], ['Chani', 'Medium', True], ['Depak', 'Medium', False]] Removing bool (False) from Ben customer_data[1].remove(False)
Global Scope (Global Variables)
Global variables are typically defined outside of all of the functions in the script and store data we want to use throughout the entire program. balance = 12.55 name = "Lilia" def withdraw_money(amount): result = balance - amount print("Hello " + name + " your balance remaining is: $" + str(result)) return amount withdraw_money(2) print("Save your money " + name + "!") the result is a local scope because it is only defined in the text body of the function. Balance and name are global scopes because they are defined outside of the function.
Great Break-Down of List Comprehensions w/conditionals
Here are a few list comprehensions in a single block. Take a moment to compare how the syntax must change depending on whether or not an else clause is included: numbers = [2, -1, 79, 33, -45] no_if = [num * 2 for num in numbers] if_only = [num * 2 for num in numbers if num < 0] if_else = [num * 2 if num < 0 else num * 3 for num in numbers]
Sorting Lists II sorted not .sort()
The sorted() function is different from the .sort() method in two ways: 1. It comes before a list, instead of after as all built-in functions do. 2. It generates a new list rather than modifying the one that already exists. names = ["Xander", "Buffy", "Angel", "Willow", "Giles"] sorted_names = sorted(names) print(sorted_names) Note that using sorted did not change names:
Shrinking a List: Remove
.remove( ) method The .remove() method removes the first matching element in a list.
Name Errors
A NameError is reported by the Python interpreter when it detects a variable that is unknown.
Parameters & Arguments
Function parameters allow our function to accept data as an input value. We list the parameters a function takes as input between the parentheses of a function ( ). Here is a function that defines a single parameter: def my_function(single_parameter) # some code def trip_welcome(destination): print("Welcome to Tripcademy!") print("Looks like you're going to " + destination + " today.") The parameter destination requires an argument in order to be printed in the second print statement in the function body. This argument acts as a value.
Accessing List Elements
utilize the index variable[1] [1] is an index representing an element in the list. This will return element.
Multiple Returns
weather_data = ['Sunny', 'Sunny', 'Cloudy', 'Raining', 'Snowing'] def threeday_weather_report(weather): first_day = " Tomorrow the weather will be " + weather[0] second_day = " The following day it will be " + weather[1] third_day = " Two days from now it will be " + weather[2] return first_day, second_day, third_day monday, tuesday, wednesday = threeday_weather_report(weather_data) print(Monday) print(tuesday) print(wednesday)
List
a list is one of the many built-in data structures that allow us to work with a collection of data in sequential order. For example, this list contains a string, integer, boolean, and float. mixed_list_common = ["Mia", 27, False, 0.5]
Set Methods
add(): Adds an element to a set. remove(): Removes an element from a set. union(): Returns a set containing all unique elements from two sets. intersection(): Returns a set containing common elements from two sets. difference(): Returns a set containing elements that are in one set but not the other.
Loop Control: Continue
big_number_list = [1, 2, -1, 4, -5, 5, 2, -9] for i in big_number_list: if i <= 0: continue print(i) This would produce the output: 1 2 4 5 2 When our loop first encountered an element (-1) that met the conditions of the if statement, it checked the code inside the block and saw the continue. When the loop then encounters a continue statement it immediately skips the current iteration and moves onto the next element in the list (4).
Slicing Lists I
letters = ["a", "b", "c", "d", "e", "f", "g"] We can do this using the following syntax: letters[start:end], where: start is the index of the first element that we want to include in our selection. In this case, we want to start at "b", which has index 1. end is the index of one more than the last index that we want to include. The last element we want is "f", which has index 5, so end needs to be 6. sliced_list = letters[1:6] print(sliced_list)
Removing by Index: Pop
removed_element = cs_topics.pop()print(cs_topics) print(removed_element) Notice two things about this example: 1. The method can be called without a specific index. Using .pop() without an index will remove whatever the last element of the list is. In our case "Clowns 101" gets removed. .pop() is unique in that it will return the value that was removed. 2. If we wanted to know what element was deleted, simply assign a variable to the call of the .pop() method. In this case, we assigned it to removed_element.
Boolean variables can be created in several ways.
set_to_true = True set_to_false = False bool_one = 5 != 7 bool_two = 1 + 1 != 2 bool_three = 3 * 3 == 9 These variables now contain boolean values, so when you reference them they will only return the True or False values of the expression they were assigned. print(bool_one) # True print(bool_two) # False print(bool_three) # True
Definite Iteration Loop
the number of times the loop will be executed is defined in advance (usually based on the collection size).
List Methods
there is built-in functionality that we can use to create, manipulate, and even delete our data. We call this built-in functionality a method. For lists, methods will follow the form of list_name.method()
$ (command line)
this is the shell prompt.
Boolean Operators: not
when applied to any boolean expression it reverses the boolean value. not True == False not False == True if not credits >= 120: print('You do not have enough credits to graduate.') if not gpa >= 2.0: print('Your GPA is not high enough to graduate.') if not (credits >= 120) and not (gpa >= 2.0): print('You do not meet either requirement to graduate!') Make sure to put the not before each variable.
Keyword Arguments
where we explicitly refer to what each argument is assigned to in the function call. def calculate_taxi_price(miles_to_travel, rate, discount): print(miles_to_travel * rate - discount ) calculate_taxi_price(rate=0.5, discount=10, miles_to_travel=100) These are not positional because they do not follow the order of the parameters. We utilize the parameter keyword to call specify these arguments.
Default Argument
# Using the default value of 10 for discount. calculate_taxi_price(10, 0.5) # Overwriting the default value of 10 with 20 calculate_taxi_price(10, 0.5, 20)
( )
Following the function name is a pair of parenthesis ( ) that can hold input values known as parameters (more on parameters later in the lesson!). In this example function, we have no parameters.
Function definition
def function_name(): # functions tasks go here
Expressions vs conditions
Expressions are used to compute values, while conditions are used to make decisions based on whether certain conditions are true or false. Expressions: 2 + 3 "Hello, " + "world!" 5 * x my_function(3) Conditions x > 5 y == "hello" z != 10 a in [1, 2, 3]
While Loops
A ~while~ loop performs a set of instructions as long as a given condition is true. while <conditional statement>: <action>
Temporary Variables in for loops
A temporary variable's name is arbitrary and does not need to be defined beforehand. Both of the following code snippets do the exact same thing as our above example: for i in ingredients: print(i) for item in ingredients: print(item) Programming best practices suggest we make our temporary variables as descriptive as possible. Since each iteration (step) of our loop is accessing an ingredient it makes more sense to call our temporary variable ingredient rather than i or item.
While Loop
A while loop performs a set of instructions as long as a given condition is true. count = 0 while count <= 3: # Loop Body print(count) count += 1 Let's break the loop down: count is initially defined with the value of 0. The conditional statement in the while loop is count <= 3, which is true at the initial iteration of the loop, so the loop body executes. Inside the loop body, count is printed and then incremented by 1. When the first iteration of the loop has finished, Python returns to the top of the loop and checks the conditional again. After the first iteration, count would be equal to 1 so the conditional still evaluates to True and so the loop continues. This continues until the count variable becomes 4. At that point, when the conditional is tested it will no longer be True and the loop will stop.
Else If Statements (elif)
An elif statement checks another condition after the previous if statements conditions aren't met. if donation >= 1000: print("You've achieved platinum status") elif donation >= 500: print("You've achieved gold donor status") elif donation >= 100: print("You've achieved silver donor status") else: print("You've achieved bronze donor status") What would happen if all of the elif statements were simply if statements? If you donated $1100.00, then the first three messages would all print because each if condition had been met. But because we used elif statements, it checks each condition sequentially and only prints one message.
Parent Directory Cont.
Each parent directory can contain more child directories and files.
Relational Operators (Comparison Operators)
Equal, ==, for returning True if two values are equal. Not equal, !=, for returning True if two values are not equal. Less than, <, for returning True if left value less than right value. Less than or equal to, <=, for returning True if left value is less than or equal to right value. Greater than, >, for returning True if left value greater than right value. Greater than or equal to, >=, for returning True if left value greater than or equal to right value.
Comparison Operators
Equal, ==, for returning True if two values are equal. Not equal, !=, for returning True if two values are not equal. Less than, <, for returning True if left value less than right value. Less than or equal to, <=, for returning True if left value is less than or equal to right value. Greater than, >, for returning True if left value greater than right value. Greater than or equal to, >=, for returning True if left value greater than or equal to right value. Predominately used in conditional (if/else statements)
cuts_under_30 = [hairstyles[i] for i in range(len(new_prices)) if new_prices[i] < 30]
Here's a breakdown of how this code works: cuts_under_30 = [...]: This creates a new list called cuts_under_30. [hairstyles[i] for i in range(len(new_prices))]: This is the list comprehension syntax. It creates a new list by iterating over each index i in the new_prices list using the range() function, and appending the corresponding element from the hairstyles list (hairstyles[i]) to the new list. if new_prices[i] < 30: This is an optional conditional expression that filters out elements from the new list that do not meet the specified condition. In this case, the condition is that the corresponding new_prices element is less than 30. So, the final result will be a list containing the names of all the hairstyles whose new_prices are less than 30.
One Element Tuple
In order for a one element tuple to execute properly we must format it as so: one_element_tuple = (4,) .. notice the trailing comma. which will print (4,) one_element_tuple = (4) will just print 4... not successful
Accessing List Elements: Negative Index
[-1] index represents the last element in the list. -1 last -2 second to last -3 third to last
Whitespace & Execution Flow
Just like loops and all other code in python, whitespace tells the computer what is a part of the function and what is not. def trip_welcome(): # Indented code is part of the function body print("Welcome to Tripcademy!") print("Let's get you to your destination.") # Unindented code below is not part of the function body print("Woah, look at the weather outside! Don't walk, take the train!") trip_welcome() Woah, look at the weather outside! Don't walk, take the train! Welcome to Tripcademy! Let's get you to your destination. Lastly, note that the execution of a program always begins on the first line. The code is then executed one line at a time from top to bottom. This is known as execution flow and is the order a program in python executes code.
Unpacking A Tuples
The great thing about tuples is that you can unpack them. Let's say we created the tuple tuple1 = ('Griffin', 25, 'Customer Success Manager') then we set tuple1 = name, age, occupation we can then call upon name.. print(name) and then 'Griffin would be returned. The same for age and occupation.
mkdir (make directory)
The mkdir command stands for "make directory". It takes in a directory name as an argument and then creates a new directory in the current working directory. $ mkdir media Here we used mkdir to create a new directory named media/ inside our working directory.
For Loops
Let's break down each of these components: The keyword "for" is used to initiate a loop that will iterate over each item in the collection specified after the keyword "in." A <temporary variable> that is used to represent the value of the element in the collection the loop is currently on. An ~in~ keyword separates the temporary variable from the collection used for iteration. A <collection> to loop over. In our examples, we will be using a list. An <action> to do anything on each iteration of the loop. The indented line "print(sports)" is executed on each iteration of the loop, which prints the value of the "sports" variable (i.e., the current sport) to the console. ingredients = ["milk", "sugar", "vanilla extract", "dough", "chocolate"] for ingredient in ingredients: print(ingredient) In this example: ingredient is the <temporary variable>. ingredients is our <collection>. print(ingredient) was the <action> performed on every iteration using the temporary variable of ingredient
# function tasks go here
Like loops and conditionals, code inside a function must be indented to show that they are part of the function.
Two-Dimensional (2D) Lists
Lists can contain other lists! We will commonly refer to these as two-dimensional (2D) lists. heights = [["Jenny", 61], ["Alexus", 70], ["Sam", 67], ["Grace", 64], ['Vik', 68]] ["Jenny", 61] ["Alexus", 70] ["Sam", 67] These are all examples of a sublist.
Nested Loops
Nested loops help us loop through and iterate through each sublist. project_teams = [["Ava", "Samantha", "James"], ["Lucille", "Zed"], ["Edgar", "Gabriel"]] for team in project_teams: print(team) Would output: ["Ava", "Samantha", "James"] ["Lucille", "Zed"] ["Edgar", "Gabriel"] # Loop through each sublist for team in project_teams: # Loop elements in each sublist for student in team: print(student) This would output: Ava Samantha James Lucille Zed Edgar Gabriel
Elegant loops: (one-line loops)
Note: One-line for loops are useful for simple programs. It is not recommended you write one-line loops for any loop that has to perform multiple complex actions on each iteration. Doing so will hurt the readability of your code and may ultimately lead to buggier code.
Sorting Lists I
Often, we will want to sort a list in either numerical (1, 2, 3, ...) or alphabetical (a, b, c, ...) order. .sort( ) .sort() also provides us the option to go in reverse. Instead of sorting in ascending order like we just saw, we can do so in descending order. names.sort(reverse=True) print(names)
Boolean Operators: or
Only one of the conditions needs to be met.
Scope and Nested Functions
Outer functions are not able to access inner function variables. Here is what that looks like in code: def outer_func(): location = "Inside the outer function!" def inner_func(): location = "Inside the inner function!" print(location) inner_func() print(location) outer_func() In this example, we use location as the variable name for two local variables. Each instance of location has a different scope, so when the functions are called, Python uses the closest available scope for the variable definition. Because of this, when we call outer_func() we do not overwrite the value of location and both of the strings are printed.
Types of Arguments
Positional arguments: arguments that can be called by their position in the function definition. Keyword arguments: arguments that can be called by their name. Default arguments: arguments that are given default values.
Built-in Functions vs User Defined Functions
Python has a large number of built-in functions that are available for use without the need to import any modules. Here is a list of some of the most commonly used built-in functions in Python: abs() - returns the absolute value of a number all() - returns True if all elements of an iterable are true any() - returns True if any element of an iterable is true bin() - converts an integer to a binary string bool() - converts a value to a Boolean value (True or False) chr() - returns a string representing a character whose Unicode code point is the integer complex() - returns a complex number dict() - creates a dictionary enumerate() - returns an enumerate object float() - returns a floating-point number format() - formats a specified value into a string frozenset() - returns a frozenset object hex() - converts an integer to a hexadecimal string id() - returns the identity of an object input() - prompts the user to enter input int() - returns an integer object isinstance() - returns True if an object is an instance of a specified class len() - returns the length of an object list() - creates a list object map() - applies a function to each item of an iterable and returns a list of the results max() - returns the largest item in an iterable or the largest of two or more arguments min() - returns the smallest item in an iterable or the smallest of two or more arguments next() - retrieves the next item from an iterator oct() - converts an integer to an octal string open() - opens a file and returns a file object ord() - returns an integer representing the Unicode character pow() - returns the value of a number raised to a specified power print() - prints a message to the console range() - returns a sequence of numbers repr() - returns a string that represents a specified object reversed() - returns a reversed iterator of a sequence round() - rounds a number to a specified number of decimal places set() - creates a set object slice() - returns a slice object sorted() - returns a sorted list from an iterable str() - returns a string object sum() - returns the sum of all items in an iterable tuple() - creates a tuple object type() - returns the type of an object zip() - returns an iterator that combines multiple iterables into tuples
Relational Operators: Equals and Not Equals
Relational operators compare two items and return either True or False. For this reason, you will sometimes hear them called comparators.
Tuples
Same as a list but it is immutable. Cannot pop(), append(), etc. can't change the order of elements Tuples are used when you do not want the above and let's say the information differs from the rest of the information you are analyzing. You will want this information to stay the same.
Consecutive Lists: Range
So, if we want the numbers from 0 through 9, we use range(10) because 10 is 1 greater than 9: my_range = range(10) print(my_range) Would output: range(0, 10) We use the list() function on our range object like this: print(list(my_range)) Would output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
cd 1
Stands for change directory. Let's say the directory we change into is 2015/: $ cd 2015
pwd
Stands for print working directory. This outputs the directory you are currently in. This is called the working directory.
Data Types
String type: str Boolean type: bool Binary types: bytes, bytearray, memoryview Number types: int, float, complex Sequence Types: list, range, tuple Set types: set, frozenset Dictionary type: dict
List Comprehensions: Conditionals
Suppose we wanted to double only our negative numbers from our previous numbers list. numbers = [2, -1, 79, 33, -45] only_negative_doubled = [] for num in numbers: if num < 0: only_negative_doubled.append(num * 2) print(only_negative_doubled) Now, here is what our code would look like using a list comprehension: numbers = [2, -1, 79, 33, -45] negative_doubled = [num * 2 for num in numbers if num < 0] print(negative_doubled) numbers = [2, -1, 79, 33, -45] doubled = [num * 2 if num < 0 else num * 3 for num in numbers ] print(doubled) I am going to define this one myself: num * 2 is the expression that will be operating on the elements in the numbers collection.
Syntax Errors
SyntaxError means there is something wrong with the way your program is written — punctuation that does not belong, a command where it is not expected, or a missing parenthesis can all trigger a SyntaxError.
Adding by Index: Insert
The .insert() method takes in two inputs: 1. The index you want to insert into. 2. The element you want to insert at the specified index. store_line.insert(2, "Vikor") print(store_line) Some important things to note: 1. The order and number of the inputs is important. The .insert() method expects two inputs, the first being a numerical index, followed by any value as the second input. 2. When we insert an element into a list, all elements from the specified index and up to the last index are shifted one index to the right. This does not apply to inserting an element to the very end of a list as it will simply add an additional index and no other elements will need to shift.
if is_raining: print("bring an umbrella") What is the colon?
The colon is telling the computer what is expected next. The colon replaces "then."
def function_name
The def keyword indicates the beginning of a function (also known as a function header). The function header is followed by a name in snake_case format that describes the task the function performs. It's best practice to give your functions a descriptive yet concise name.
Root Directory(Command Line)
The first directory in the filesystem is the root directory. It is the parent of all other directories and files within the filesystem.
Positional Arguments
The position of the arguments will be mapped to the positions defined in the function declaration. OMG I LOVE THAT 'function declaration' my_function(paramater1, paramater2) is the function declaration EX def calculate_taxi_price(miles_to_travel, rate, discount): print(miles_to_travel * rate - discount ) # 100 is miles_to_travel # 10 is rate # 5 is discount calculate_taxi_price(100, 10, 5)
For Loops: Using Range
To create arbitrary collections of any length, we can pair our for loops with the trusty Python built-in function range(). for temp in range(6): print("Loop is on iteration number " + str(temp + 1)) Here's what happens when the code is executed: On the first iteration of the loop, temp is assigned the value of 0, so the print statement outputs the message "Loop is on iteration number 1" (0 + 1 = 1). On the second iteration, temp is assigned the value of 1, so the print statement outputs the message "Loop is on iteration number 2" (1 + 1 = 2). This process continues for each iteration of the loop, with temp taking on the values of 2, 3, 4, and 5 in turn, and the print statement outputting messages that reflect the current iteration number.
cd II
To move across multiple directories with a single command, we can provide cd a relative path to the memory/ directory as an argument. From the blog/ directory use: $ cd 2015/jan/memory We can also move up multiple directories using the .. argument. To go from memory up 2 directories to 2015, we use ../.. $ pwd /home/ccuser/workspace/blog/2015/jan/memory $ cd ../.. $ pwd /home/ccuser/workspace/blog/2015 Lastly, we can move to an adjacent directory using .. and then a directory name. If we are in the 2015/ directory and we want to go into the 2014/ directory, we go up one directory then into the 2014/ directory: $ ls 2014 2015 hardware.txt $ cd 2015 $ pwd /home/ccuser/workspace/blog/2015 $ cd ../2014 $ pwd /home/ccuser/workspace/blog/2014
Elegant List Comprehensions
To start, let's say we had a list of integers and wanted to create a list where each element is doubled. We could accomplish this using a for loop and a new list called doubled: numbers = [2, -1, 79, 33, -45] doubled = [] for number in numbers: doubled.append(number * 2) print(doubled) The Elegant List Comprehension Version: numbers = [2, -1, 79, 33, -45] doubled = [num * 2 for num in numbers] print(doubled) Let's break down our example in a more general way: new_list = [<expression> for <element> in <collection>]
User Defined Functions
User defined functions are ones that are created by the user. def function_name() is defining a function.
Index
We call the location of an element in a list an index. calls = ["Juan", "Zofia", "Amare", "Ezio", "Ananya"] - 'Juan' or 'Sofia' is an index. Python lists are zero-indexed, which means they start at 0.
Argument in a command line
When a file, directory, or program is passed into a command, it is called an argument. Here the 2015/ directory is an argument for the cd command. $ cd 2015 $cd .. can also be used to move up one directory. .. stands for the directory above the current working directory.
ls (command)
When you type ls, the command line looks at the directory you are in, and then "lists" all the files and directories inside of it.
Can you sort a list and then store it into a variable?
Yes(NO), you can use the sort() method to sort a list in Python and then assign the sorted list to a new variable. The sort() method modifies the original list in place and returns None, so you cannot assign the result of sort() directly to a variable. However, you can sort the list and then assign the sorted list to a new variable using slicing or the built-in sorted() function. Here are two examples: 1. Using slicing: my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_list = my_list[:] # create a copy of the original list sorted_list.sort() # sort the copy in place print(sorted_list) # [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] 2. Using the sorted() function: my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_list = sorted(my_list) # create a new sorted list print(sorted_list) # [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] so obviously the sorted method is more viable than having to set your new list equal to the old list and then utilizing the sort method.
Combining Lists
Zip( ) function. When you call zip() on one or more lists, the result is a new iterable of tuples that contains the elements from the original lists, but in a different format. names = ["Jenny", "Alexus", "Sam", "Grace"]heights = [61, 70, 67, 64] names_and_heights = zip(names, heights) converted_list = list(names_and_heights) print(converted_list)
students_period_A = ["Alex", "Briana", "Cheri", "Daniele"] students_period_B = ["Dora", "Minerva", "Alexa", "Obie"] What is the for loop to combine these lists into one list?
all_students = [] for student in students_period_A: all_students.append(student) for student in students_period_B: all_students.append(student) print(all_students) This code creates an empty list called all_students, and then uses two separate for loops to append the elements from students_period_A and students_period_B to the all_students list. In the first for loop, each element of the students_period_A list is assigned to the variable student (which is a temporary variable name used in the for loop). The code then appends that element to the all_students list using the append() method. The second for loop works the same way, but instead of iterating over students_period_A, it iterates over students_period_B, and appends each element to the all_students list. After both for loops have completed, the all_students list will contain all the elements from both students_period_A and students_period_B. This code is a way to concatenate two lists in Python using for loops. It is less concise than using the + operator to concatenate the lists directly, but can be useful in situations where you need more control over the concatenation process.
List Method
append(): Adds an element to the end of a list. extend(): Adds the elements of a list to another list. insert(): Inserts an element at a specified index in a list. pop(): Removes and returns the last element of a list. remove(): Removes the first occurrence of an element from a list.
Returns (statement)
def calculate_exchange_usd(us_dollars, exchange_rate): return us_dollars * exchange_rate new_zealand_exchange = calculate_exchange_usd(100, 1.4) print("100 dollars in US currency would give you " + str(new_zealand_exchange) + " New Zealand dollars") So in this line of code(my interpretation that is backed my GPT), we first define the function in the function declaration return is just a KEYWORD in our function body. return allows us to enter a value or expression within the text body to run in our function. .... new_zealand_exchange is the variable we are calling our calculation function under saving the output to this variable. return passes the variable back to the function caller.
Variable Access Scope Included
def trip_welcome(destination): print(" Looks like you're going to the " + destination + " today. ") print(destination) destination will cause a NameError because it is a scope. We call the part of a program where destination can be accessed its scope. The scope of destination is only inside the trip_welcome(). My words = the scope can only be accessed if we call the function. It is only a part of the function. The scope can also be referenced as the parameter. I am not totally sure the difference. If a variable lives outside of any function it can be accessed anywhere in the file. Hence if we were to define destination before our syntax program. For example, if we had entered the variable destination = 'California' beforehand we could print(destination)
Multiple Parameters
def trip_welcome(origin, destination): print("Welcome to Tripcademy") print("Looks like you are traveling from " + origin) print("And you are heading to " + destination) # Calling my_function my_function(argument1, argument2) So origin and destination are the parameters, and once you insert an origin and destination, that is the argument.
Loop Control: Break
dog_breeds_available_for_adoption = ["french_bulldog", "dalmatian", "shihtzu", "poodle", "collie"] dog_breed_I_want = "dalmatian" for dog_breed in dog_breeds_available_for_adoption: print(dog_breed) if dog_breed == dog_breed_I_want: print('They have the dog I want!') break The print(dog_breed) after the temporary variable elegant(first-line) is important because it is going to print the elements in the collection until it hits. dalmation in which it breaks.
Indentation in For Loops
for ingredient in ingredients: # Any code at this level of indentation # will run on each iteration of the loop print(ingredient) If we ever forget to indent, we'll get an IndentationError or unexpected behavior.
Slicing Lists II
fruits[:n] ^ selects everything before the index you specify. Remember the index you specify is actually -1 print(fruits[-2:]) This is a negative index so it will start from the end of the list and move left to right and give you all the elements from -2 onward. fruits[:-n] Just putting examples bc you know how to do this. list[start:end:step] the colon (:) is used to separate the start and end indices of the slice.
Modifying List Elements
garden[2] = "Strawberries" print(garden) as you can see above, you will select the element utilizing the index, then update via the value string.
Dictionary Method
get(): Returns the value of a specified key in a dictionary. keys(): Returns a list of all keys in a dictionary. values(): Returns a list of all values in a dictionary. items(): Returns a list of all key-value pairs in a dictionary. update(): Updates the values of one dictionary with the values of another dictionary.
Accessing 2D Lists
heights = [["Noelle", 61], ["Ali", 70], ["Sam", 67]] #Access the sublist at index 0, and then access the 1st index of that sublist. noelles_height = heights[0][1] print(noelles_height) 61
for i in range(len(hairstyles)): total_revenue += prices[i] * last_week[i] print('Total Revenue: ' + str(total_revenue)) Check out this code and decipher it.
i is created to attach the element to I for each element in the hairstyles list. This line starts a loop that iterates over each index i in the hairstyles list. The range function generates a sequence of integers from 0 to the length of the hairstyles list - 1, which will be used to access each hairstyle's price and quantity sold. total_revenue += prices[i] * last_week[i]: This line is executed for each iteration of the loop. It calculates the revenue earned for a particular hairstyle by multiplying its price (prices[i]) by the quantity sold (last_week[i]), and adds the result to the current total_revenue variable. I take this as each price element is multiplied by each last_week element and then they are added together. hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"] prices = [30, 25, 40, 20, 20, 35, 50, 35] last_week = [2, 3, 5, 8, 4, 4, 6, 2]
Calling the function
instead of writing print(function_name) calling a function is how you print the task function_name would be proper and print the results of the task
While Loops: Lists
length = len(ingredients) index = 0 while index < length: print(ingredients[index]) index += 1 # Length will be 5 in this case length = len(ingredients) while index < length: In our while loop conditional, we will compare the index variable to the length of our list stored inside of the length variable. On the first iteration, we will be comparing the equivalent of 0 < 5 which will evaluate to True, and start the execution of our loop body. # The first iteration will print ingredients[0] print(ingredients[index]) Inside of our loop body, we can use the index variable to access our ingredients list and print the value at the current iteration.Since our index starts at zero, our first iteration will print the value of the element at the zeroth index of our ingredients list, then the next iteration will print the value of the element at the first index, and so on. index += 1 On each iteration of our while loop, we need to also increment the value of index to make sure our loop can stop once the index value is no longer smaller than the length value.This increment also helps us access the next value of the ingredients list on the next iteration.
Type Errors
piggy_bank = '2' + 0.25 Traceback (most recent call last): File "script.py", line 1, in <module> piggy_bank = '2' + 0.25 TypeError: must be str, not float
Describing what range does in the for loop (more in depth)
range(5) creates a sequence of numbers from 0 to 4. The for loop iterates over each value in this sequence, with the loop variable promises taking on the values of 0, 1, 2, 3, and 4 in turn. In summary, range(5) is a built-in Python function that generates a sequence of numbers from 0 to 4, which is used in this code snippet to control the number of iterations of the loop. In general, you can use range to create a sequence of integers for use in loops and other situations where you need to iterate over a specific range of values. IT SOUNDS LIKE ITS KEY PURPOSE IS TO TELL THE FOR LOOP HOW MANY TIMES TO ITERATE OVER THE COLLECTION