Intro to Python

¡Supera tus tareas y exámenes ahora con Quizwiz!

class X(object): def M(self, J)

#must have self parameter or it will not work class X has-a function that takes parameter self and J

What is the correct output for the following code: a = [10, 20, 30] mysum = a[1] + a[2] print(mysum)

50

Syntax to change data type of a *var* to integer

>>> int(var) Example >>> int (19.8) = 19 >>>int("9") = 9

Syntax to get the length of a string

>>> len(string)

Does Python have *constant* variable?

No

What would the code generate? a=["Trickier"] for i in a: print(i)

Trickier

How to quit Python in Terminal?

Type *"Ctrl" + "Z", "Enter"*

Is Python case sensitive?

Yes

What output would the following code generate? a=[1,2,3,4,5] a.remove(3) print(a)

[1,2,4,5]

while running a while loop while True: .... .... how to escape this loop?

if key==ord('q'): break

Mode of opening a file file.open( )

"r" open a file for reading only. The file pointer is placed at the beginning of the file. Default mode "r+" open a file for both reading and writing. The file pointer is placed at the beginning of the in_file "w" open a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a file for writing "w+" open a file for both writing and reading. Overwrite the file if it already exists. If the file does not exist, create a file for writing "a" open a file for appending. The file pointer is at the end of the file if the file exists. "a+" open a file for both reading and appending. The file pointer is at the end of the file if the file exists.

difference between *del*, *pop*, *remove*

#*remove* removes the first matching value (not all the matching value), not a specific index list.remove(item) #del removes the item at a specific index *del* array[index] #pop removes the item at a specific index and returns it. >>> a = [4, 3, 5] >>> a.pop(1) 3 >>> a [4, 5]

when accessing a dictionary, how to determine whether a key exists before you try to use it to retrieve its value?

#use keyword *in* and *not in* if 'key' in dictionary_name: #do something Example: dict = { "name": "Anh", "age": 22, "mood": "calm" } if "gender" not in dict: print ("gender is not found")

using Jupyter Notebook, import a json file from this URL *http://pythonhow.com/supermarkets.json* to a Python variable/table, then replace the index with Address

$ipython import pandas df = pandas.read_json(""http://pythonhow.com/supermarkets.json"" df.set_index("Address", inplace=True)

How to create a Jupiter Notebook? (formerly known as Python notebook?)

$jupyter notebook copy link after "The Jupyter Notebook is running at:" to any web browser

What is the correct output for the following code: print("Python is fun"[-3:][-1])

'n' We're dealing with two consecutive slicings here. The first one extracts the string 'fun' from string 'Python is fun' while the second extracts string 'n' from string 'fun'.

Syntax to duplicate string?

* Example: >>> start = 'Na ' * 4 + '\n' >>> middle = 'Hey ' * 3 + '\n' >>> end = 'Goodbye.' >>> print(start + start + middle + end) Na Na Na Na Hey Hey Hey Goodbye

create a variable that contains a 2D table with n rows and m columns (n and m is arbitrary)

* $ipython import pandas #Example 1: each list will be a row df1 = pandas.DataFrame([ [2,4,6], [10,30,50] ]) df1 >>> 0 1 2 0 2 4 6 1 10 30 50 #Example 2: same as example 2 but each column and each row has name df2 = pandas.DataFrame([ [2,4,6], [10,30,50] ], columns = ["Day1", "Day2", "Day3"], index = ["Morning", "Afternoon"]) df3 >>> Day1 Day2 Day3 Morning 2 4 6 Afternoon 10 30 50 #Example: each entry is a row df3 = pandas.DataFrame([{"Name": "J", "Last Name": "Jon","Age": ...: "21"}, {"Name":"Elton", "Last Name":"Zhao","Age": "19"} , {"Name": "Kyle ...: ", "Last Name": "Muldoon", "Age":"20"}, {"Name": "Jack"]) #dictionary Age Last Name Name 0 21 Jon J 1 19 Zhao Elton 2 20 Muldoon Kyle 3 NaN NaN Jack

How to change directory in terminal to a directory called "Learn Python the hard way"?

*"cd \"Learn\ Python\ the\ hard\ way\"\ exercises/"*

How to list all the current subdirectory in the current directory?

*"ls"*

How to know which folder/directory is terminal in?

*"pwd"* print (current) working directory Example: Anhs-MacBook-Pro-2:Documents anhpham$ cd \"Learn\ Python\ the\ hard\ way\"\ exercises/ Anhs-MacBook-Pro-2:"Learn Python the hard way" exercises anhpham$ pwd /Users/anhpham/Documents/"Learn Python the hard way" exercises

after you code for a while, your terminal looks messy. How do you clear them all up ?

*$clear*

how to create a new file in terminal

*$touch file_name* will create a new file in the current working directory Example: $ touch index.html $ touch one.txt two.txt three.txt #create multiple $touch script.py

What is the difference between *%s* and *%r*?

*%r* displays "raw" code, for debug, use *repr( )* *%s* displays for users, use *str( )* %d will format a number for display. Example: >>> import datetime >>> d = datetime.date.today() >>> str(d) '2011-05-14' >>> repr(d) 'datetime.date(2011, 5, 14)'

what is the difference between *=* and *==*?

*=* is for assigning values *==* is for comparison

Syntax to extract a substring from a string

*[start:end:step]* Example: letters = 'abcdefghijklmnopqrstuvwxyz' >>> string2 = letters[:] >>> string2 'abcdefghijklmnopqrstuvwxyz' >>> letters[20:] 'uvwxyz' >>> letters[12:15] 'mno' #from index 4 to 19, by 3 >>> letters[4:20:3] 'ehknqt'

carriage return line feed

*carriage return (\r)* moves the cursor to the beginning of the current line and overwrite *line feed (\n)* moves the cursor to the next new line Example >>> print "stackoverflow\rnine" ninekoverflow

How to change to the previous directory?

*cd ../* move back 1 directory *cd ../../* move back 2 directory *cd ../../../* move back 3 directory

get( )

*dict.get(key, default = None)* returns a value for the given key. If key is not available then returns default value *None*. Example: dict = { 'Name': 'Zabra', 'Age': 7 } print "Value : %s" % dict.get('Age') print "Value: %s " % dict.get('Home') print "Value : %s" % dict.get('Education', "Never") ''' Value: 7 Value: None Value: Never '''

python3 built-in reference in MacOS terminal Good to look up function definition, function parameters

*dir(object)* shows all the attributes and methods of a particular object's class. *help(object Example raw_input(...) raw_input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading. (END)q

the difference between *file.readline()* and *file.readlines( )*

*file.readline( )* only reads the first line *file.readlines( )* reads all the lines in file and store each one as list

what is the difference between *import module* and *from module import foo*

*import module* + Less maintenance of your import statements. Don't need to add any additional imports to start using another item from the module - Typing module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo) *from module import foo* + Less typing to use foo More control over which items of a module can be accessed - To use a new item from the module you have to update your import statement You lose context about foo. For example, it's less clear what ceil() does compared to math.ceil()

dataframe - syntax?

*import pandas variable = pandas.dataframe((data=None, index=None, columns=None, dtype=None, copy=False)* to create a data structure, a (heterogeneous) tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure

Write code to test if a value exists in a sequence (list, tuple, string etc.) ?

*in* Example: list = ["string to look up", "string2 to look up"] file = open("file_path", "r+") content = file.read( ) for val in list: if val in content: print("Found")

how to get the length of a string?

*len(string)* example: >>> string = "Hello World!" >>> len(string) 12

how to create a list ?

*list = []* Example: list = ["hello", 234, "m", object]

how to add an element to the end of the list

*list.append(element)*

how to remove an element from the list, knowing the value of the element but not the index?

*list.remove(element's value)* Example: list = ["Hi", 2134, "m", object, -434.23] list.remove(2134); #list = ["Hi", "m", object, -434.23] list.remove("a"); #return ValueError if value is not present

how to get the mean of each column in a table of data created by panda module in iPython?

*mean( )* Example: import pandas df3 = pandas.DataFrame([[2,4,6],[10,20,30]], columns=["Price","Age","Value"], index=["First","Second"]) df3 >>> Price Age Value First 2 4 6 Second 10 20 30 >>> df3.mean( ) >>> Price 6.0 Age 12.0 Value 18.0 dtype: float64 #To calculate the mean of 6,12,18 df3.mean( ).mean( ) >>> 12

syntax to convert number to a string (to concatenate with another string)?

*str(number)*

*join( )*

*str.join(sequence)* ---> concatenate a string sequence − This is a sequence of the elements to be joined. returns a string, which is the concatenation of the strings in the sequence seq *Example 1*: connector = "-"; seq = ("a", "b", "c"); # This is sequence of strings. print connector.join( seq ); >>> a-b-c *Example 2*: join individual element into a sentence print ' '.join(["Day", "Night","Sheep","Sleep"]); >>> Day Night Sheep Sleep Ex 3: join individual element from index to index list = [""Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy", "Music", "Love"] print '#'.join(stuff[3:6]) >>> Frisbee#Corn#Banana

how to convert a string to lowercase?

*string.lower( )*

What command will replace a letter/string in a string with another letter/string

*string.replace("letter/string", original_string, number")* number is the number of occurrence letter is going to replace. Example: >>> name = 'Henny' >>> name.replace('H', 'P') 'Penny' >>> name2 = name.replace("n", "r") "Perrry"

how to convert all of the string to uppercase?

*string.upper( )*

how to get a substring from string ?

*string[starting_index, ending_index+1]* splitting string in python is upper bound exclusive Example: string = "Adam apple organic" Adam_app = string[0:8] #Adam app

what are 2 drawbacks of shell scripts (script that is written in shell)

+ They don't scale well beyond few hundred lines + slower than other languages

Advantage and disadvantage of using C/C++ to build programs?

+ speed is important - hard to learn and fix bugs - static language

how to add 1 string to another

+= Example: s = "Python is easy" s += "yet powerful" print s >>> Python is easy yet powerful

why choose Python?

- general-purpose - high-level - quick to write - easy to read - shorter syntax compare to others --> shorter code - use free everywhere - there's a poem imbedded in it

Panda - What is it? - Its purpose? - Example of usage?

- library providing data structures & data analysis tools - allows you to load data from different sources into Python and then use Python code to analyze those data and produce results (in forms tables, text, visualization) Example: load text files with data constructed of rows and columns into Python object efficiently, web scrapping, load & analyze Excel files

3 types of python program's interface?

1) Terminal/command line 2) GUI 3) Web app

In python3, what is the difference between 12*4 12*4.0 54/7 54.54/7 4*9.23 4 * 9.4234 1/4 1.0/4

12*4 = 48 12*4.0 = 48.0 54/7 = 7.714285714285714 54.54/7 = 7.791428571428571 4*9.23 = 36.92 4 * 9.4234 = 37.6936 1/4 = 0.25 1.0/4 = 0.25

What would the following code output? for i in (1,2,3): print(i+1)

2 3 4 #must be on different lines

What is the correct output for the following code: a = ["10", "20", "30"] mysum = a[1] + a[2] print(mysum)

2030 adding 2 strings

What would the following code generate? a=[1,2,3,4,5] a.remove(3) print(a[3])

5

Syntax for New style string formatting, specifically left-alignment

>>> "{:7d}{:11f}{:3s}".format(42, 7.004, "pizza") ' 42 7.004000pizza' #minimum 7 space for 42, minimum 11 space for 7.004, minimum 3 space for pizza. All left-alignment

Syntax for New style string formatting, specifically right-alignment

>>> '{0:>10d} {1:>10f} {2:>10s}'.format(42, 7.03, "pizza") 42 7.030000 pizza

Syntax for modulus Example: 8 mod 5 = 3

>>> 8 % 5 = 3

Syntax for integer division Example: 8 divided by 5 = 1

>>> 8 // 5 1

Syntax for floating-point division Example: 8 divided by 5 = 1.6

>>> 8/5 1.6

What does this do? *print ("I","love","Money")*

>>> I love Money Comma *,* helps print string on the same line, separated by a *whitespace*

Associate two String variables named background and selectionColor with the values "white" and "blue" respectively.

>>> background, selectionColor = "white", "blue"

python method to see all the method of an object /string?

>>> dir(object) Example: >>> dir(os) ['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_ NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX _PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', '_make_stat_r ... ]

coming to get both quotient and remainder as a tuple in division Example: 9/5 = (1,4)

>>> dived(9,5) (1,4)

Syntax for getting both quotient and remainder of division Example: 8 / 5 --> quotient = 1, rem = 3

>>> divmod(8,5) (1,3)

Write a statement that reads a word from standard input into firstWord.

>>> firstWord = input().split(" ")[0]

Syntax to change data type of a *var* to float

>>> float(True) 1.0 >>> float(False) 0.0 >>> float("99.4") 99.4

Math Syntax to get the integer above a number

>>> import math >>> math.ceil( ) Example: >>> math.ceil(98.6) 99 >>> math.ceil(-271.1) -271

Math Syntax to find the absolute value of a number

>>> import math >>> math.fabs(-434.837) 34.837

Math Syntax to calculate logarithm Example: calculate the log of 8 base 2

>>> import math >>> math.log(8,2)

Math syntax to calculate square root of a number

>>> import math >>> math.sqrt(100.0) 10.0

command to find the square root of a number?

>>> import math >>> math.sqrt(num)

how to check if a key exists or not in a dictionary?

>>> key *in* dictionary True >>> fdssaf *in* dictionary False

Given a String variable named "sentence" that has been initialized, write an expression whose value is the number of characters in the String referred to by sentence

>>> len(sentence)

Syntax to reverse a string Example: letters = 'abcdefghijklmnopqrstuvwxyz' Get 'zyxwvutsrqponmlkjihgfedcba'

>>> letter[ : : -1] 'zyxwvutsrqponmlkjihgfedcba'

Syntax to get the last 1,2,3 characters Example: letters = 'abcdefghijklmnopqrstuvwxyz'

>>> letters[-3:] 'xyz'

write a variable that is a dictionary about your name, age, height. then add a keyword "city" and a value to the dictionary

>>> my_dict = { ... "name": "Anh", ... "age" : 22, ... "weight": 50*2+20 ... } >>> #in terminal, use Shift+return to go down a line >>> my_dict["name"] 'Anh' >>> #add city >>>dict["city"] = "san jose"

Syntax to round real number to 1,2,3... decimal place Example: print 3.141519 rounded to 4 decimal place

>>> print(str(round(3.14159, 4))); 3.1416

Syntax to round a number to nearest tenth, hundred? Example: 186282 rounded to the nearest hundred

>>> round(186282, -2) #186300

how to capitalize only the first word of the string Example: s = "a duck goes into a bar ... "

>>> s.capitalize( ) "A duck goes into a bar ... "

how to convert all characters in a string to uppercase? Example: s = "A ducK goes into a bar ... "

>>> s.lower( ) s = "a duck goes into a bar ... "

how to capitalize all word in a string Example: s = "a duck goes into a bar ... "

>>> s.title( ) 'A Duck Goes Into A Bar...'

how to convert all characters in a string to uppercase? Example: s = "a duck goes into a bar ... "

>>> s.upper( ) s = "A DUCK GOES INTO A BAR ..."

Syntax to find how many times "word" appear in string?

>>> string.count("word")

Syntax to find the index of the first occurrence of a 'word' in 'string', return -1 if not found

>>> string.find('word') Example: >>> word.find('h') 5 >>> word.find('q') -1

Syntax to test for alphabetic character return true if string only contains alphabetic character false if string contains at least 1 digit or white space ....

>>> string.isalpha( )

Syntax to test for digits in a string return true if string only contains digit, false otherwise

>>> string.isdigit( )

Syntax to find if the string only contains all uppercased characters, return false if string contains at least one lowercase letters or no letter at all.

>>> string.isupper()

given a string, how to get the first word example: string = "Box O' Kitten"

>>> string.split(" ")[0] 'Box'

Syntax for converting all character in string to uppercase?

>>> string.upper( )

Python syntax find out the *data type* of a variable

>>> type(var)

Given 2 list x and y >>> x = [1, 2, 3] >>> y = [4, 5, 6] Write a method that will combine those two list into a list of (1, 4), (2, 5), (3, 6)

>>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> list(zipped) [(1,4), (2,5), (3,6)] >>> for i, j in zip(x,y): >>> print(i, "and", j) 1 and 4 2 and 5 3 and 6

Syntax to convert number from base-2 to base-10 Example: convert 1001 = 9

>>>0b1001 9

command to calculate the difference between two number? Example: 4 and 9

>>>abs(4-9) 5

Syntax to change data type of a *var* to string

>>>str(var)

What is list? what is dictionary? What's the difference? When use list? When use dictionary

A list is for any sequence of things that need to go in order, and you only need to look them up by a numeric index. Use a *dictionary* when you have to take one value and "look up" another value.

what's the difference between parameter and argument?

A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters

what does "CSV file" stand for?

Comma-separated values

Are string in Python immutable?

Every string operation produces a new string as its result, because strings are immutable in Python—they cannot be changed after they are created

how to create a substring starting from an index to the last index in the string?

Example: string = "Peterson has a daughter" son_has_a_daughter = string[5:] #son has a daughter

how to print both index and item of the list ?

If you need both the index and the item, use the enumerate function: for index, item in enumerate(L): print index, item

how to print all the index of a list?

If you need only the index, use range and len: for index in range(len(L)): print index

In Python, which data type is considered an *object*?

In Python, everything—booleans, integers, floats, strings, even large data structures, functions, and programs—is implemented as an object.

class X(Y)

Make a class named X that inheres from class Y

Given a list states = { "Oregon": "OR", "Florida": "FL", "California": "CA", "New York": "NY", "Michigan": "MI" }; Write a loop in two different ways that will print all the keywords and values

Method 1: for index in states: print "The abbreviation of %s is %s" %(index, states[index]); Method 2: for key, value in states.iteritems(): print "The abbreviation of %s is %s" %(key,value); ''' dict.items() returns a list of 2-tuples ([(key, value), (key, value), ...]), whereas dict.iteritems() is a generator that yields 2-tuples. The former takes more space and time initially, but accessing each element is fast, whereas the second takes less space and time initially, but a bit more time in generating each element. '''

how to print the content of an input file inside a python program?

Method 1: Pass input file name as argument from sys import argv script, inFile = argv print "Here's the inFile's content" content = open(inFile, 'r') #r/w/r+ print content.read( ) #read( ) extract a string that contains all characters in the file

Which data type is mutable? Which one is not? int, float, bol, str, tuple, list, set, dict

Objects of types like (int, float, bool, str, tuple, unicode) are immutable. Objects of types like (list, set, dict) are mutable

how to create a python file, write code and run it in terminal?

Open a text editor (Sublime text) save a file as *file_name.py" back in terminal, change directory to the directory that contains the file type *"$python file_name.py"* in terminal

open( )

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised. *open("file_path")*

What does "Data analysis" do?

Organize data in data structure (tables, graphs...) and analyze them

when we assign a different value to a variable, what changes in that variable? a) the value b) the variable c) something else

Python create a new object with the new value and change the reference of the variable to that new object

Which one is upper bound exclusive?

Range is upper bound exclusive Single index is not upper bound exclusive

What would the following code output? a="Tricky" for i in a[:3]: print(i)

T r i

What would the following tricky code generate this time? * lst=["Terribly Tricky"] for word in lst: for letter in word[-6:]: print(letter) *

T r i c k y

Assume that month is an int variable whose value is 1 or 2 or 3 or 5 ... or 11 or 12. Write an expression whose value is "jan" or "feb" or "mar" or "apr" or "may" or "jun" or "jul" or "aug" or "sep" or "oct" or "nov" or "dec" based on the value of month. (So, if the value of month were 4 then the value of the expression would be "apr".)

There's no "switch-case" in Python Use if-else or dictionary options = { 1 : sqr, 4 : sqr, 9 : sqr, 2 : even, 3 : prime, 5 : prime, 7 : prime, } def sqr(): print "n is a perfect square\n" def even(): print "n is an even number\n" def prime(): print "n is a prime number\n"

What is *not None* equal to?

True (not true, TRUE) (Python is case sensitive)

how to assign multiline string into a variable in Python in shell?

Use triple quote >>> poem = '''There was a Young Lady of Norway, ... Who casually sat in a doorway; ... When the door squeezed her flat, ... She exclaimed, "What of that?" ... This courageous Young Lady of Norway.'''

What do these escape sequences do \\ \' \" \n \r \t \a \b \f \N \uxxxx \Uxxxxxxxx \v ASCII vertical tab (VT) \ooo Character with octal value oo \xhh Character with hex value hh

\\ Backslash (\) \' Single-quote (') \" Double-quote (") \n ASCII linefeed (LF) \r ASCII carriage return (CR) \t ASCII horizontal tab (TAB) \a ASCII bell (BEL) \b ASCII backspace (BS) \f ASCII formfeed (FF) \N{name} Character named name in the Unicode database (Unicode only) \u xxxx Character with 16-bit hex value xxxx (Unicode only) \Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only) \v ASCII vertical tab (VT) \ooo Character with octal value oo \xhh Character with hex value hh

module in Python

a file containing Python definitions and statements file with .py

What is a *variable*?

a name that refer to a memory address that store value, data type

script

a python file a program piece of code

in 1 line, swap the values of a and b

a, b = b, a

Comparison and logic: what is the Python keyword that is equivalent to *&&* in C++ what is the Python keyword that is equivalent to *||* in C++ what is the Python keyword that is equivalent to *!* in C++

and or not

What does *split(separator)* do?

break a string into a list of smaller strings based on some separator Example: >>> ' 1 2 3 '.split() ['1', '2', '3'],

What does *split( )* do to this string? >>>todos = 'get gloves, get mask, give cat vitamins, call ambulance' >>> todos.split(',')

break a string into a list of smaller strings based on some separator ['get gloves' , 'get mask', 'give cat vitamins', 'call ambulance']

class X(object): def __init__(self, J)

create a class X that has-a constructor function that takes parameter self and J

Which one is mutable in Python and which one is not mutable: data type, value?

data type of a variable doesn't change variable's value is mutable

write a function that will take an integer from user (not string, not float) and will not stop asking for an integer until it gets an integer

def input ( ): while True: try: user_input = int(input("Enter a number:" )) except ValueError: print("Enter again a number: ") continue else: break

Create a function and name it power. This function should take two arguments, the base and the exponent and should return the power of any base given any exponent.

def power(base, exponent) return base

what's the difference between *argv* and *raw_input( )*

depends on where the user gives inputs if user give inputs on the command line, use *argv* if user gives input on keyboard while the script is running, use *raw_input( )* Example of *argv* $ python script_name.py anh, 2nd_var, last_var The script is called: script_name.py Your first variable is: anh Your second variable is: 2nd_var Your third varaible is: last_var Example of raw_input( ) print "How much do you weigh?", weight = raw_input();

method to get a list of all the keys in a dictionary?

dictionary.keys( ) returns a dict_key objects behaves like a list

how to retrieve a value from a dictionary?

dictionary_name[key] Example: >>> dictionary["zoo"] ['Area in which animals, especially wild animals, are kept so that people can go and look at them, or study them.']

how to view all methods an object/library

dir(object) Example: dir(geopy) #geopy is a geocoding library

Ipython - What is it? - Pros? - How to use?

enhanced Python interactive shell Pros: >> better printing of large output. >>> Suitable for data analysis as it prints data in a well structured format >>> press tab to auto-complete functions >>> run any python script using "%run" >> see which variables you have defined in your script using "whos" >>>embed your graphs directly >>> re-run part of a program, rather than the entire thing (convenient for experimenting with big data sets) How to use? Open terminal, $ipython

which of these in Python is considered an "object": object, booleans, integers, floats, strings, functions, programs

everything in Python is implemented as an "object"

in python 3, what is the type of the result of division of 2 integer?

float Example: 10 / 2 = 5.0

What is "directory"?

folder //from Unix //Unix 69, Microsoft 80s

class X: def __init__(self): pass; how to create an instance of class X?

foo = X( )

how to create an instance of class X and change an attribute in class X?

foo = X( ) foo.k = Q from foo get the k attribute and change it to Q

class X(object): def M(self, J) how to create an instance of class X and call member function?

foo.M(j)

how to access Numpy array by column?

for i in numpy_array.T: print(i) #transpose: switch rows and columns' position

how to access Numpy array value by value?

for i in numpy_array.flat: print(i) #flat is the method transform ndarray into 1D array

how to access Numpy array by row?

for i in numpy_array: print(i) #i is each row

Write code in Python so that we/user can pass argument(s) (like below) before running the python's script in terminal? *Anhs-MacBook-Pro-2:"Learn Python the hard way" exercises anhpham$ python file_name.py argument1 argument2 argument3*

from sys import arg script_name, first_arg, second_arg, third_arg = argv #takes whatever is in argv, unpack argv, and assign it to all these variables on the left in order

range( ) + Syntax? + Purpose?

generates a list of numbers, which is generally used to iterate over with for loops Example: >>> for i in range(5): ... print(i) ... 0 1 2 3 4 >>> for i in range(3, 6): ... print(i) ... 3 4 5 >>> # Three parameters >>> for i in range(4, 10, 2): ... print(i) ... 4 6 8 >>> # Going backwards >>> for i in range(0, -10, -2): ... print(i) ... 0 -2 -4 -6

write conditional statement to check if variable *var* is a list or not

if type(var) == list: blahblah else: blah

how to convert an image into an array of numbers that represent the image?

import cv2 numpy_array= cv2.imread("smallgray.png",0) #0 to read image in gray scale, 1 to read image in bgr/gbr #each number in the numpy array represent the color #if photos is interpreted in gray scale, numpy_array is 2D array. Row = each pixel along the width and column = each pixel along the height of picture #if photo is interpreted in rgb scale, numpy_array is 3D array, where each pixel is represented in red/green/blue scale in each layer

how to get today's date and store in a varaible?

import datetime now = datetime.datetime.now( ) day_now = datetime.datetime.now( ).day year_now = datetime.datetime.now( ).year month_now = datetime.datetime.now( ).month now.hour, now.minute, now.second

compute the similarity ratio between two strings

import difflib from difflib import SequenceMatcher SequenceMatcher(None, "word1", "word2").ratio( ) #None or a function to ignore whitespaces/markups

How to save data from .json file into a variable in Python script?

import json dictionary = json.load(open("data.json"))

in Jupiter Notebook (aka iPython), how to know the number of rows and columns of a DataFrame (table) object?

import panda #create a table from a CSV file df1 = pandas.read_csv("file_name.csv) df1.shape > (row, col)

how to load txt file (data separated by commas) into Python script's variable in Jupiter Notebook? Example of txt file: ID,Address,City,State,Country,Name,Employees 1,3666 21st St,San Francisco,CA 94114,USA, Madeira,8 2,735 Dolores St,San Francisco,CA 94119,USA,Bready Shop,15 3,332 Hill St,San Francisco,California 94114,USA,Super River,25

import pandas df = pandas.read_csv("file_name.txt")

how to load txt file (data separated by other character other than commas) into Python script's variable in Jupiter Notebook? Example of txt file: ID;Address;City;State;Country;Name;Employees 1;3666 21st St;San Francisco;CA 94114;USA;Madeira;8 2;735 Dolores St;San Francisco;CA 94119;USA;Bready Shop;15 3;332 Hill St;San Francisco;California 94114;USA; Super River;25

import pandas df = pandas.read_csv("file_name.txt", sep=";")

how to import a text file, which is in a comma-separated format? Then how to get the columns' title and store in a variable?

import pandas df = pandas.read_csv("filename.txt") column_list = df.columns print(column_list) ''' Index(['VOLCANX020', 'NUMBER', 'NAME', 'LOCATION', 'STATUS', ' ELEV', 'TYPE','TIMEFRAME', 'LAT', 'LON'], dtype='object') '''

how to load Json file into Python script's variable in Jupiter Notebook?

import pandas df = pandas.read_json("file_name.json")

using Jupyter Notebook, import a json file from this URL *http://pythonhow.com/supermarkets.json* to a Python variable/table, then replace the index with Address, then create a sub-table that shows like this Country Emp ID Address 735 Dolores USA 15 2 St 332 Hill St USA 25 3 3995 23rd St USA 10 4

import pandas df = pandas.read_json("http://pythonhow.com/supermarkets.json") df.set_index("Address", inplace=True) df.loc["735 Dolores St":"3995 23rd St", "Country":"ID"]

how to load CSV file into Python script's variable using Jupiter Notebook?

import pandas df1 = pandas.read_csv("file_name.csv")

how to load Excel file into Python script's variable in Jupiter Notebook?

import pandas df3 = pandas.read_excel("file_name.xlsx", sheet_name=0) #excel file may have multiple sheets. sheet name specify which sheet. First sheet is 0

Syntax to find regex match at the beginning of the string. #If no match can be found, return None. #If found matches, a match object instance is returned, containing information about the match: where it starts and ends, the substring it matched, and more.

import re >>> newObj = re.match("regex", sourceString) Example:

how to open and print the content of an input file in Python

in_file = open(file_name, "r") #file_name is a string of input file's name ''' Modes: r: reading only, no w: content of in_file will be erased after this line is execute r+: File will be read but content of in_file_name is not wiped cleaned, instead, appened at the end of the file a: append at the end of the file with file.write( ) #If mode is omitted, default to open file in "read" mode #other mode includes "w", "r+",

Command to change other Python data type to integer

int( ) Example: >>>int(True) 1 >>>int(False) 0 >>>int(1.0e4) #float 10000 >>>int("-12") #string -12

how to convert string to int?

int(string) function int( ) returns an integer object constructed from a number or string x,

in python 2, what is the type of the result of division ?

integer Example: 10 / 4 = 2

select the correct output for the following code: s = "Python is fun" print(s[7:9])

is

If you use terminal/terminal window, what is the program that reads what you type, runs it and displays the results is called?

it is called shell program

dynamic languages

languages do not force you to declare variable types before using them because they are interpreted languages Example: Python, Pearl, PHP, Ruby,

Definition of static language? Example?

languages that require you to specify low-level details (ex: type) for the computer and variable can't change that detail (an integer is an integer, forever) Example: C,C++, Java

how to get the number of items in a container

len(object)

how to know how many items are there in a list?

list = [ ] len(list)

what does *append()* do

list.append(number/string) adds a single element to the end of the list

how to add a certain item in a certain index of a list?

list.insert(index, item)

*pop( )*

list.pop( ); removes and return the last item in the list (array)

how to access the third element of the list? Example: list = ["Apple", 324, "McGrovey", object,

list[2]

How to print a list in the same line for Python3?

lst = [1, 1, 2, 3, 5, 8, 13, 221, 34, 55, 89] for i in lst: print(i, end= " ")

what's the difference between library and module?

module is a python file that has all the functions that coder don't use too often. When the coder needs a specific module (Example: os), *import* that module library is a collection of module module is like header file in C++

create a list and iterate the list using for loop?

my_list = ["anh", "dima", "kyle"] for item in my_list: print (item)

what is a variable in Python?

name for values in your Python script

given a list of lines list = ["line 1\n", "line 2 \n", "line 3 \n"] create a new list of string that is a copy of list but remove the "\n"

new_list = [i.rstrip("\n") for i in list]

what are floats number?

numbers with decimal points

how to get the number of columns and rows in a numpy array?

numpy_array.shape

is-a

one class inherits from another Example: Fish is an animal

has-a

one class is composed of another class Example: Fish has a mouth

How to run Python on MacOS

open terminal and type *"python3 Enter"* (Must have installed Python to MacOS before)

how to pause the program while it's running and wait for user's input to continue?

print "Pause the program. Hit enter to continue or CTRL-C to terminate" input( )

which of the following statements would generate the string 'fu'? 1) print("Python is fun"[10:11]) 2) print("Python is fun"[-3:-3]) 3) print("Python is fun"[-3:1])

print("Python is fun"[-3:1]) will produce what?

Which of these files can python handle: binary file text file

python can handle *both* types of files

check if a string s only contains alphabetic letter

s.isalpha( )

check if a string s only contains number

s.isdigit( )

check if a string s only contains number

s.isnumeric( )

which method returns a copy of the string in which first characters of all the words are capitalized?

string.capwords(str) Example: >>> name = "julie berry" >>> name = string.capwords(name) Julie Berry

how to access last item in the list (string/array)? how to access the second last item in the list? how to access the third last item in the list?

string[-1] string[-2] string[-3]

how to create a tuple? why use a tuple?

t = ("3.1415, "pi", "I hate Math", [4,3,2,1], {"name":"Anh"}) >>> t (3.1415, 'pi', 'I hate Math', [4, 3, 2, 1], {'name': 'Anh'})

what does *%s* , *%d*, *%r* do ?

they tell Python to take the variable on the right and put it in

What is the difference between tuple and list?

tuples are not mutable lists are mutable

How to run/execute a python file in terminal?

type "python file_name.py"

How to change directory/folder in terminal?

type *"cd" + "the_subdirectory_in_the_current_directory"*

How to make a directory/folder in terminal?

type *"mkdir + name_of_new_subdirectory"*

How to delete a file (not a directory/folder) in terminal?

type *"rm + file_name* in terminal

how to know the type of an object (example: string, int, float)

type(object) return the object's type example: c = "Hi there!" type(c[4]); #<class 'str'> type(40.034) #<class 'float'>

how to see the type of an object in iPython

type(variable) Example: import pandas df1 = pandas.DataFrame([10,20],[30,40] ) df1 >>> 0 1 0 10 20 1 30 40 type(df1) >>> pandas.core.frame.DataFrame

What is the name of this character *_*

underscore

How to write an empty function?

use *pass* statement. pass is a special statement in Python that does nothing. It only works as a dummy statement. def empty( ): pass;

when to use *for* loop? when to use *while* loop?

when we know the number of loop iteration, use *for* when we don't know the number of loop iteration but want to repeat something while the condition is true, use *while* Example: User keep entering password until it is correct to log in -> use *while* loop


Conjuntos de estudio relacionados

CSC Chapter 2 - The Capital Market

View Set

Experiencing the Lifespan Chapter 5

View Set

RN Maternal Newborn Online Practice 2019 A

View Set

#8 Reading Assignment Test "The Ground On Which I Stand"

View Set

Marketing Exam 4: Ch. 14, 15, 16, 17

View Set

Microeconomics Econ 101 Chapter 9: International Trade Notes

View Set