Coding Terms in Python for Jack Oatz

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

list comprehension questions

# Use for the questions below: nums = [i for i in range(1,1001)] string = "Practice Problems to Drill List Comprehension in Your Head." Find all of the numbers from 1-1000 that are divisible by 8 Find all of the numbers from 1-1000 that have a 6 in them Count the number of spaces in a string (use string above) Remove all of the vowels in a string (use string above) Find all of the words in a string that are less than 5 letters (use string above) Use a dictionary comprehension to count the length of each word in a sentence (use string above) Use a nested list comprehension to find all of the numbers from 1-1000 that are divisible by any single digit besides 1 (2-9) For all the numbers 1-1000, use a nested list/dictionary comprehension to find the highest single digit any of the numbers is divisible by Answers: https://towardsdatascience.com/beginner-to-advanced-list-comprehension-practice-problems-a89604851313

important thing to remember (1)

+= is NOT the SAME as =+ Ex: i+=1 is the same as i=i+1 whereas i=+1 just means i=(+1).

what are the commands that can be used in the function set?

.intersection (finds the common thingy) .symmetric_difference (finds the difference and shows all) .difference (finds the difference from the main list to the other list) .union (combines the list without any repeating thingies)

what does .lower do

.lower just makes everything lower case

what does .upper do

.upper just makes everything upper case

What is list comprehension?

A powerful alternative to building lists that contain specific values Ex: fruits = ["apple", "banana", "cherry", "kiwi", "mango] newlist = [] for x in fruits: if "a" in x: newlist.append(x) print(newlist) # Turn that into a list comprehension fruits = ["apple", "banana", "cherry", "kiwi", "mango] newlist [x for x in fruits if "a" in x] print(newlist) Ex2: a_list = [x for x in range(10)] b_list = [] for y in range(10): b_list.append(y) print(a_list) print(b_list) # They would have the same output with different lines of code

what does := do in python

Assigns values to variables as part of a larger expression Ex:

How do you index DataFrames? choice deux

Choice (deux): using integers and shiii Ex: import pandas as pd randomassvariable = pd.read_csv("randomasscsvfile", index_col 0) print(randomassvariable[0:4]) #prints data rows 1 - 4

what does a list comprehension look like

Ex: #before list comprehension numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7] newlist= [] for x in numbers: if x > 0: newlist.append(int(x)) print(newlist) #after list comprehension numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7] newlist = [int(x) for x in numbers if x > 0] print(newlist)

What does .index do

Ex: x = "one" y = "banana" print(x.index("o")) print(y.index("a")) Result: 1 2 (it will only show the first occurrence)

what does .endswith do

Exactly as u think it'd do check if it ends with something if it does = True if it doesn't = False

what does string.ascii_letters

Gives both upper and lower case letters Ex: x = string.ascii_letters print(x) Result: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

what does help do

Gives info abt the module Ex: import Calc help(Calc) Result: Help on module Calc: NAME Calc FUNCTIONS add(a, b) div(a, b) mult(a, b) sub(a, b) FILE /Users/me/Calc.py

what are packages

Idk they said: "namespaces containing multiple packages and modules. They're just directories, but with certain requirements."

what does max() do

Returns the item with the highest value, or the item with the highest value in an iterable. If the values are strings, an alphabetically comparison is done.

what does type() do

Said: "returns class type of the argument(object) passed as parameter. type() function is mostly used for debugging purposes" Ex: height = [1.87, 1.87, 1.82, 1.91, 1.90, 1.85] weight = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45] import numpy as np np_height = np.array(height) np_weight = np.array(weight) print(type(np.height)) Result: <class 'numpy.ndarray'>

what are sets? what does set() do

Sets are used to store multiple items in a single variable Ex: x = set(("apple", "banana", "cherry")) print(x) y = set("apple") print(y) Result: {'banana', 'cherry', 'apple'} {"l","a","p","e"} # Note: the set list is unordered, so the result will display the items in a random order. # Note: the set for y is a list of letters without repeat of letters

What does enumerate() do?

Takes a collection of tuples and returns it as an enumerate object Also adds a counter to the tuple Ex: x = ('apple', 'banana', 'cherry') y = enumerate(x) print(y) Result: [(0, 'apple'), (1,

What does the __init__ do?

The stupidest thing ever cuz jfc I'm losing my mind: "used for assigning values in a class" Ex class StupidafClass: def __init__(x, y): x.y = y def returningthestupidassnumbers(x): return x.y variable = StupidafClass(7) print(variable.returningthestupidassnumbers()) Result: 7 (Why does it do that? Idfk. For some reason, has to be paired with def to make __init__ work then some weird mathematical trailing bs) (Just go with it)

what does super(). function do

The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class. Ex: class Parent: def __init__(self, txt): self.message = txt def printmessage(self): print(self.message) class Child(Parent): def __init__(self, txt): super().__init__(txt) x = Child("Hello, and welcome!") x.printmessage() Result: Hello and, welcome!

what does [(whatever number) :: (another number)] do?

The whatever number is the starting point to count and another number is the amount of skips to count (remember counting starts from 0) Ex: x= "FAPAPAPAPA" print(x[1::2]) print(x[2::1]) Result: AAAAA PAPAPAPA

How do you index DataFrames? choice uno

There multiple ways but here the two main ones: Choice (uno): using strings and shii Ex: import pandas as pd randomvariable = pd.read_csv("randomcsvfile", index_col = 0) print(randomvariable["randomrow"]) #this will give data as a series print(randomvariable[["randomrow"]]) #this will give data as a DataFrame print(randomvariable[["randomrow", "urmom"]]) #this will give a dataframe of both randomrow and urmom

how to use multiple arguments in a function

add * or ** with .get idk

what does def do?

allow you to create your own function (type out the function name to use it) Ex: def my_function(): print("Hello World!") a = 3 b = 4 def my_function2(a, b): return a + b my_function() my_function2() Result Hello World! 7

how do u iterate over dictionaries?

by using the for __ in ___(): method just like a list Ex phonebook = {} phonebook["A"] = 123 phonebook["B"] = 456 phonebook["C"] = 789 for x, y in phonebook.items(): print("%s's number is %s" %(x, y)) Result: A's number is 123 B's number is 456 C's number is 789 (P.S. Yes, .items is a thing. Use it. Jackass.

how does one slice strings

can either be thru [:whatever number] (a slice starting from 0) or [whatever number: with another number] (a slice starting from whatever number to stopping right before another number) or add more to this later

what does del do

deletes from the dictionary Ex phonebook = {} phonebook["A"] = 123 phonebook["B"] = 456 phonebook["C"] = 789 del phonebook["A"] print(phonebook) Result: {'B': 456, 'C': 789}

what does range() do?

gives the thingy a certain range of values and depending on what ur looking for can change what gives the thingy that range of values Ex: for x in range(5): #this only prints 0-4 print(x) for y in range(24, 27): #this says numbers btwn 24 - 27 print(y) for z in range (30, 40, 5): #says btwn 30-40 but skip 5 print(z) Result: 0 1 2 3 4 24 25 26 30 35

methods of try and except

idk look at the lessons

what does pd.read_csv() do

imports csv files that are already stored as a data frame Ex: # Import pandas as pd import pandas as pd # Import the cars.csv data: cars cars = pd.read_csv('cars.csv') # Print out cars print(cars) Result: prints the data abt cars or whatever that's already stored somewhere

how do you get a user input

input()

what does dir do

it showcases all the functions in a module including built ins Ex import Calc dir(Calc) Result: ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'div', 'mult', 'sub']

what's a module

its basically a class but bigger and can be separated into a different file You can use the module by stating: import (whatever module) or from (whatever module) import (whatever function u made in that module) or from (whatever module) import * to import all functions

what does .startswith do

literally exactly as u think it would do check if it starts with something if it does then = True if not then = False

using class, refer to screenshot "stupid class"

look at screenshot "stupid class"

using the "for __ in _____ :" see the screenshot " ur dumb asl"

look at screenshot "ur dumb asl"

what does != mean in python

not equal to

how do turn something into an array

np.array() after importing numpy as np

What does the return method work with

only four things: strings integers handle and objects NOT FUNCTIONS LIKE .randint

What is Pandas

pretty much a data frame; a frame of data; data in rows and columns lol Ex: import pandas as pd #create a dictionary for this example ppsize = {"woah that's way too big" : ["6 in", "5 in", "4 in"], "that's good" : ["3 in", "2 in", "1 in"], "that's avg" : ["0.9 in", "0.5 in", "0.25 in"]} whatgirlssayabtsize = pd.DataFrame(ppsize) print(whatgirlssayabtsize) Result: woah that's way too big 6 in 5 in 4 in that's good 3 in 2 in 1 in that's avg 0.9 in 0.5 in 0.25 in (Pretty much like this but in rows and columns) Check screenshot "Pandas are cool"

what does len() do

pretty much just count the sum of words/numbers like word count including spaces

what does .count do

pretty much just counts a specific letter/word/ or whatever u put

what does sorted() do

returns a sorted list of the specific iterable object alphabetically and numerically Ex: # After creating a certain module called "Calc" right find_stuff = [] for x in dir(Calc): if "u" in x: find_stuff.append(x) print(find_stuff) Result: ['__builtins__', 'mult', 'sub']

what does .get do

returns the value of the item with the specified key (reminder: in setting up the parameters in functions, dont forget to use **)

what does string.ascii_uppercase do

same as string.ascii_lowercase Ex: x = string.ascii_uppercase print(x) Result: ABCDEFGHIJKLMNOPQRSTUVWXYZ

what does .pop do

same as the del method

What does \d in a regular expression match?

single digit

what does \D in a regular match

single letters

what does [ -(whatever number)] do?

the program counts from the end Ex: x = "onetwothree" print("The second letter from the end is %s" %x[-2]) Result: The second letter from the end is e

what does if, elif, else do?

u know exactly what it does just memorize u fkin asshat

what does while do?

u know what this does mf

how do u change the "titles" in the columns area of Pandas

use .index = [] Check screenshot "Pandas are asian, black, and white"

how do you import regular expression (regex) in

use import re

what does string.ascii_lowercase do

will give the lowercase letters 'abcdefghijklmnopqrstuvwxyz' Ex: # importing string library function import string # Function checks if input string # has lower only ascii letters or not def check(value): for letter in value: # If anything other than lower ascii # letter is present, then return # False, else return True if letter not in string.ascii_lowercase: return False return True # Driver Code input1 = "GeeksForGeeks" print(input1, "--> ", check(input1)) input2 = "geeks for geeks" print(input2, "--> ", check(input2)) input3 = "geeksforgeeks" print(input3, "--> ", check(input3)) Result: GeeksForGeeks --> False geeks for geeks --> False geeksforgeeks --> True

what does loc[] do

In data frames, it'll give the specified row of data (this can only work with " " things) Ex: Ex: #below is data after importing a certain csv file cars_per_cap country drives_right S 809 United States True AUS 731 Australia False JAP 588 Japan False IN 18 India False cars = pd.read_csv("cars.csv", index_col = 0) #idk why we use index_col yet; maybe to start from column 0? print(cars.loc["IN"]) Result: cars_per_cap country drives_right IN 18 India False

what does iloc[] do

In data frames, same as loc: gives specified row of data (But can only work with integers) Ex: #below is data after importing a certain csv file cars_per_cap country drives_right S 809 United States True AUS 731 Australia False JAP 588 Japan False IN 18 India False cars = pd.read_csv("cars.csv", index_col = 0) #idk why we use index_col yet; maybe to start from column 0? print(cars.iloc[2]) Result: cars_per_cap country drives_right JAP 588 Japan False

what's the power of dictionaries in python u fk

Its practically a list within a list but u can add associations with that list like (x y) Ex phonebook = {} phonebook["A"] = 123 phonebook["B"] = 456 phonebook["C"] = 789 print(phonebook) Result: {'A': 123, 'B': 456, 'C': 789} The reverse can be done e.g. phonebook = {'A': 123, 'B': 456, 'C': 789}

what does in do?

Just makes sure that a certain something is in a given list Ex x = "onetwothree" if x in ["onetwothree", "fourfivesix"] print("Ur mom") Result Ur mom

what does .split(" ") do?

Literally splits things at wherever depending on what's in the "" Ex: x = "Hello World!" print(x.split(" ")) print(x.split("e")) Result ["Hello", "World!"] ["H", "llo World!"] (notice how the space or the e is not included at the end result)

What are Boolean operators?

NOT, AND, OR

what does [whatever number] do ?

Only focuses on whatever number is placed in the [] Ex: x = "onetwothree" print(x[4]) Result w (Remember counting starts from 0)


संबंधित स्टडी सेट्स

Module 1: Fundamental Considerations in the Wealth Management Process

View Set

Chapter 19 Mindtap -- Incomplete

View Set

Reading 7: Statistical Concepts and Market Returns

View Set

NURS 547 Chap 6/7/8 Review Questions

View Set

Chapter 3: Scales, Keys, and Modes

View Set