Outline
Week 17
Keywords:
https://bryan-guner.gitbook.io/notesarchive/
2.1.7 Indentation
Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.
First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.
Cross-platform compatibility note: because of the nature of text editors on non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the indentation in a single source file.
A formfeed character may be present at the start of the line; it will be ignored for the indentation calculations above. Formfeed characters occurring elsewhere in the leading whitespace have an undefined effect (for instance, they may reset the space count to zero).
The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows.
Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If it is smaller, it must be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a DEDENT token is generated. At the end of the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero.
Here is an example of a correctly (though confusingly) indented piece of Python code:
def perm(l): # Compute the list of all permutations of l if len(l) <= 1: return [l] r = [] for i in range(len(l)): s = l[:i] + l[i+1:] p = perm(s) for x in p: r.append(l[i:i+1] + x) return r
The following example shows various indentation errors:
(Actually, the first three errors are detected by the parser; only the last error is found by the lexical analyzer – the indentation of return r
does not match a level popped off the stack.)
https://ds-unit-5-lambda.netlify.app/
Python Study Guide for a JavaScript Programmer
Mar 5 · 15 min read
https://miro.medium.com/max/1400/1*3V9VOfPk_hrFdbEAd3j-QQ.png
Applications of Tutorial & Cheat Sheet Respectivley (At Bottom Of Tutorial):
Basics
PEP8 : Python Enhancement Proposals, style-guide for Python.
print
is the equivalent ofconsole.log
.
‘print() == console.log()’
#
is used to make comments in your code.
#
is used to make comments in your code.Python has a built in help function that let’s you see a description of the source code without having to navigate to it… “-SickNasty … Autor Unknown”
Numbers
Python has three types of numbers:
Integer
Positive and Negative Counting Numbers.
No Decimal Point
Created by a literal non-decimal point number … or … with the int() constructor.
3. Complex Numbers
Consist of a real part and imaginary part.
Boolean is a subtype of integer in Python.🤷♂️
If you came from a background in JavaScript and learned to accept the premise(s) of the following meme…
Than I am sure you will find the means to suspend your disbelief.
KEEP IN MIND:
The i is switched to a j in programming.
This is because the letter i is common place as the de facto index for any and all enumerable entities so it just makes sense not to compete for name-space when there’s another 25 letters that don’t get used for every loop under the sun. My most medium apologies to Leonhard Euler.
Type Casting : The process of converting one number to another.
The arithmetic operators are the same between JS and Python, with two additions:
“**” : Double asterisk for exponent.*
“//” : Integer Division.
There are no spaces between math operations in Python.
Integer Division gives the other part of the number from Module; it is a way to do round down numbers replacing
Math.floor()
in JS.There are no
++
and `` in Python, the only shorthand operators are:
Strings
Python uses both single and double quotes.
You can escape strings like so
'Jodi asked, "What\\'s up, Sam?"'
Multiline strings use triple quotes.
Use the len()
function to get the length of a string.
Python uses zero-based indexing
zero-based indexing
Python allows negative indexing (thank god!)
Python let’s you use ranges
You can think of this as roughly equivalent to the slice method called on a JavaScript object or string… (mind you that in JS … strings are wrapped in an object (under the hood)… upon which the string methods are actually called. As a immutable privative type by textbook definition, a string literal could not hope to invoke most of it’s methods without violating the state it was bound to on initialization if it were not for this bit of syntactic sugar.)
The end range is exclusive just like
slice
in JS.
The
index
string function is the equiv. ofindexOf()
in JS
The
count
function finds out how many times a substring appears in a string… pretty nifty for a hard coded feature of the language.
You can use
+
to concatenate strings, just like in JS.You can also use “” to repeat strings or multiply strings.**
Use the
format()
function to use placeholders in a string to input values later on.
Shorthand way to use format function is:
print(f'Your name is {first_name} {last_name}')
Some useful string methods.
Note that in JS
join
is used on an Array, in Python it is used on String.
https://miro.medium.com/max/630/0*eE3E5H0AoqkhqK1z.png
There are also many handy testing methods.
https://miro.medium.com/max/630/0*Q0CMqFd4PozLDFPB.png
Variables and Expressions
Duck-Typing : Programming Style which avoids checking an object’s type to figure out what it can do.
Duck Typing is the fundamental approach of Python.
Assignment of a value automatically declares a variable.
You can chain variable assignments to give multiple var names the same value.
Use with caution as this is highly unreadable
The value and type of a variable can be re-assigned at any time.
NaN
does not exist in Python, but you can ‘create’ it like so:print(float("nan"))
Python replaces
null
withnone
.none
**** is an object and can be directly assigned to a variable.
Using none is a convenient way to check to see why an action may not be operating correctly in your program.
Boolean Data Type
One of the biggest benefits of Python is that it reads more like English than JS does.
https://miro.medium.com/max/1400/0*HQpndNhm1Z_xSoHb.png
By default, Python considers an object to be true UNLESS it is one of the following:
Constant
None
orFalse
Zero of any numeric type.
Empty Sequence or Collection.
True
andFalse
must be capitalized
Comparison Operators
Python uses all the same equality operators as JS.
In Python, equality operators are processed from left to right.
Logical operators are processed in this order:
NOT
AND
OR
Just like in JS, you can use parentheses to change the inherent order of operations.Short Circuit : Stopping a program when a true or false has been reached.
https://miro.medium.com/max/630/0*qHzGRLTOMTf30miT.png
Identity vs Equality
In the Python community it is better to use
is
andis not
over==
or!=
If Statements*
if name == 'Monica': print('Hi, Monica.')if name == 'Monica': print('Hi, Monica.')else: print('Hello, stranger.')if name == 'Monica': print('Hi, Monica.')elif age < 12: print('You are not Monica, kiddo.')elif age > 2000: print('Unlike you, Monica is not an undead, immortal vampire.')elif age > 100: print('You are not Monica, grannie.')
Remember the order of elif
statements matter.
While Statements
Break
statement also exists in Python.
As are
continue
statements
Try/Except Statements
Python equivalent to
try/catch
You can name an error to give the output more specificity.
You can also use the
pass
commmand to by pass a certain error.
The
pass
method won’t allow you to bypass every single error so you can chain an exception series like so:
You can use an
else
statement to end a chain ofexcept
statements.
finally
is used at the end to clean up all actions under any circumstance.
Using duck typing to check to see if some value is able to use a certain method.
Pass
Pass Keyword is required to write the JS equivalent of :
Functions
Function definition includes:
The
def
keywordThe name of the function
A list of parameters enclosed in parentheses.
A colon at the end of the line.
One tab indentation for the code to run.
You can use default parameters just like in JS
Keep in mind, default parameters must always come after regular parameters.
You can specify arguments by name without destructuring in Python.
The
lambda
keyword is used to create anonymous functions and are supposed to beone-liners
.
toUpper = lambda s: s.upper()
Notes
Formatted Strings
Remember that in Python join() is called on a string with an array/list passed in as the argument.Python has a very powerful formatting engine.format() is also applied directly to strings.
Comma Thousands Separator
Date and Time
Percentage
Data Tables
**Python can be used to display html, css, and JS.**It is common to use Python as an API (Application Programming Interface)
Structured Data
Sequence : The most basic data structure in Python where the index determines the order.
ListTupleRangeCollections : Unordered data structures, hashable values.
DictionariesSetsIterable : Generic name for a sequence or collection; any object that can be iterated through.Can be mutable or immutable.Built In Data Types
Lists are the python equivalent of arrays.
You can instantiate
Test if a value is in a list.
Instantiated with parentheses
Sometimes instantiated without
Tuple() built in can be used to convert other data into a tuple
Ranges : A list of numbers which can’t be changed; often used with for loops.
Declared using one to three parameters.
Start : opt. default 0, first # in sequence.Stop : required next number past the last number in the sequence.Step : opt. default 1, difference between each number in the sequence.
Dictionaries : Mappable collection where a hashable value is used as a key to ref. an object stored in the dictionary.
Mutable.
Declared with curly braces of the built in dict()
Benefit of dictionaries in Python is that it doesn’t matter how it is defined, if the keys and values are the same the dictionaries are considered equal.
Use the in operator to see if a key exists in a dictionary.
Sets : Unordered collection of distinct objects; objects that need to be hashable.
Always be unique, duplicate items are auto dropped from the set.
Common Uses:
Removing DuplicatesMembership TestingMathematical Operators: Intersection, Union, Difference, Symmetric Difference.
Standard Set is mutable, Python has a immutable version called frozenset.Sets created by putting comma seperated values inside braces:
Also can use set constructor to automatically put it into a set.
filter(function, iterable) : creates new iterable of the same type which includes each item for which the function returns true.
map(function, iterable) : creates new iterable of the same type which includes the result of calling the function on every item of the iterable.
sorted(iterable, key=None, reverse=False) : creates a new sorted list from the items in the iterable.
Output is always a list
key: opt function which coverts and item to a value to be compared.
reverse: optional boolean.
enumerate(iterable, start=0) : starts with a sequence and converts it to a series of tuples
(0, ‘First’), (1, ‘Second’), (2, ‘Third’), (3, ‘Fourth’)
(1, ‘First’), (2, ‘Second’), (3, ‘Third’), (4, ‘Fourth’)
zip(*iterables) : creates a zip object filled with tuples that combine 1 to 1 the items in each provided iterable.Functions that analyze iterable
len(iterable) : returns the count of the number of items.
max(args, key=None) : returns the largest of two or more arguments.
max(iterable, key=None) : returns the largest item in the iterable.
key optional function which converts an item to a value to be compared.min works the same way as max
sum(iterable) : used with a list of numbers to generate the total.
There is a faster way to concatenate an array of strings into one string, so do not use sum for that.
any(iterable) : returns True if any items in the iterable are true.
all(iterable) : returns True is all items in the iterable are true.
Working with dictionaries
dir(dictionary) : returns the list of keys in the dictionary.Working with sets
Union : The pipe | operator or union(sets) function can be used to produce a new set which is a combination of all elements in the provided set.
Intersection : The & operator ca be used to produce a new set of only the elements that appear in all sets.
Symmetric Difference : The ^ operator can be used to produce a new set of only the elements that appear in exactly one set and not in both.
For StatementsIn python, there is only one for loop.
Always Includes:
The for keyword2. A variable name3. The ‘in’ keyword4. An iterable of some kid5. A colon6. On the next line, an indented block of code called the for clause.
You can use break and continue statements inside for loops as well.
You can use the range function as the iterable for the for loop.
Common technique is to use the len() on a pre-defined list with a for loop to iterate over the indices of the list.
You can loop and destructure at the same time.
Prints 1, 2Prints 3, 4Prints 5, 6
You can use values() and keys() to loop over dictionaries.
Prints red
Prints 42
Prints color
Prints age
For loops can also iterate over both keys and values.
Getting tuples
Prints (‘color’, ‘red’)
Prints (‘age’, 42)
Destructuring to values
Prints Key: age Value: 42
Prints Key: color Value: red
Looping over string
When you order arguments within a function or function call, the args need to occur in a particular order:
formal positional args.
args
keyword args with default values
kwargs
Importing in Python
Modules are similar to packages in Node.jsCome in different types:
Built-In,
Third-Party,
Custom.
All loaded using import statements.
Terms
module : Python code in a separate file.package : Path to a directory that contains modules.init.py : Default file for a package.submodule : Another file in a module’s folder.function : Function in a module.
A module can be any file but it is usually created by placing a special file init.py into a folder. pic
Try to avoid importing with wildcards in Python.
Use multiple lines for clarity when importing.
Watching Out for Python 2
Python 3 removed <> and only uses !=
format() was introduced with P3
All strings in P3 are unicode and encoded.md5 was removed.
ConfigParser was renamed to configparsersets were killed in favor of set() class.
print was a statement in P2, but is a function in P3.
https://gist.github.com/bgoonz/82154f50603f73826c27377ebaa498b5#file-python-study-guide-py
https://gist.github.com/bgoonz/82154f50603f73826c27377ebaa498b5#file-python-study-guide-py
https://gist.github.com/bgoonz/282774d28326ff83d8b42ae77ab1fee3#file-python-cheatsheet-py
https://gist.github.com/bgoonz/282774d28326ff83d8b42ae77ab1fee3#file-python-cheatsheet-py
2021-03-06_Python-Study-Guide-for-a-JavaScript-Programmer-
Week 17
Keywords:
https://bryan-guner.gitbook.io/notesarchive/
2.1.7 Indentation
Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.
First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.
Cross-platform compatibility note: because of the nature of text editors on non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the indentation in a single source file.
A formfeed character may be present at the start of the line; it will be ignored for the indentation calculations above. Formfeed characters occurring elsewhere in the leading whitespace have an undefined effect (for instance, they may reset the space count to zero).
The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows.
Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If it is smaller, it must be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a DEDENT token is generated. At the end of the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero.
Here is an example of a correctly (though confusingly) indented piece of Python code:
def perm(l): # Compute the list of all permutations of l if len(l) <= 1: return [l] r = [] for i in range(len(l)): s = l[:i] + l[i+1:] p = perm(s) for x in p: r.append(l[i:i+1] + x) return r
The following example shows various indentation errors:
(Actually, the first three errors are detected by the parser; only the last error is found by the lexical analyzer – the indentation of return r
does not match a level popped off the stack.)
https://ds-unit-5-lambda.netlify.app/
Python Study Guide for a JavaScript Programmer
https://miro.medium.com/max/1400/1*3V9VOfPk_hrFdbEAd3j-QQ.png
Applications of Tutorial & Cheat Sheet Respectivley (At Bottom Of Tutorial):
Basics
PEP8 : Python Enhancement Proposals, style-guide for Python.
print
is the equivalent ofconsole.log
.
‘print() == console.log()’
#
is used to make comments in your code.
#
is used to make comments in your code.Python has a built in help function that let’s you see a description of the source code without having to navigate to it… “-SickNasty … Autor Unknown”
Numbers
Python has three types of numbers:
Integer
Positive and Negative Counting Numbers.
No Decimal Point
Created by a literal non-decimal point number … or … with the int() constructor.
3. Complex Numbers
Consist of a real part and imaginary part.
Boolean is a subtype of integer in Python.🤷♂️
If you came from a background in JavaScript and learned to accept the premise(s) of the following meme…
Than I am sure you will find the means to suspend your disbelief.
KEEP IN MIND:
The i is switched to a j in programming.
This is because the letter i is common place as the de facto index for any and all enumerable entities so it just makes sense not to compete for name-space when there’s another 25 letters that don’t get used for every loop under the sun. My most medium apologies to Leonhard Euler.
Type Casting : The process of converting one number to another.
The arithmetic operators are the same between JS and Python, with two additions:
“**” : Double asterisk for exponent.*
“//” : Integer Division.
There are no spaces between math operations in Python.
Integer Division gives the other part of the number from Module; it is a way to do round down numbers replacing
Math.floor()
in JS.There are no
++
and `` in Python, the only shorthand operators are:
Strings
Python uses both single and double quotes.
You can escape strings like so
'Jodi asked, "What\\'s up, Sam?"'
Multiline strings use triple quotes.
Use the len()
function to get the length of a string.
Python uses zero-based indexing
zero-based indexing
Python allows negative indexing (thank god!)
Python let’s you use ranges
You can think of this as roughly equivalent to the slice method called on a JavaScript object or string… (mind you that in JS … strings are wrapped in an object (under the hood)… upon which the string methods are actually called. As a immutable privative type by textbook definition, a string literal could not hope to invoke most of it’s methods without violating the state it was bound to on initialization if it were not for this bit of syntactic sugar.)
The end range is exclusive just like
slice
in JS.
The
index
string function is the equiv. ofindexOf()
in JS
The
count
function finds out how many times a substring appears in a string… pretty nifty for a hard coded feature of the language.
You can use
+
to concatenate strings, just like in JS.You can also use “” to repeat strings or multiply strings.**
Use the
format()
function to use placeholders in a string to input values later on.
Shorthand way to use format function is:
print(f'Your name is {first_name} {last_name}')
Some useful string methods.
Note that in JS
join
is used on an Array, in Python it is used on String.
https://miro.medium.com/max/630/0*eE3E5H0AoqkhqK1z.png
There are also many handy testing methods.
https://miro.medium.com/max/630/0*Q0CMqFd4PozLDFPB.png
Variables and Expressions
Duck-Typing : Programming Style which avoids checking an object’s type to figure out what it can do.
Duck Typing is the fundamental approach of Python.
Assignment of a value automatically declares a variable.
You can chain variable assignments to give multiple var names the same value.
Use with caution as this is highly unreadable
The value and type of a variable can be re-assigned at any time.
NaN
does not exist in Python, but you can ‘create’ it like so:print(float("nan"))
Python replaces
null
withnone
.none
**** is an object and can be directly assigned to a variable.
Using none is a convenient way to check to see why an action may not be operating correctly in your program.
Boolean Data Type
One of the biggest benefits of Python is that it reads more like English than JS does.
https://miro.medium.com/max/1400/0*HQpndNhm1Z_xSoHb.png
By default, Python considers an object to be true UNLESS it is one of the following:
Constant
None
orFalse
Zero of any numeric type.
Empty Sequence or Collection.
True
andFalse
must be capitalized
Comparison Operators
Python uses all the same equality operators as JS.
In Python, equality operators are processed from left to right.
Logical operators are processed in this order:
NOT
AND
OR
Just like in JS, you can use parentheses to change the inherent order of operations.Short Circuit : Stopping a program when a true or false has been reached.
https://miro.medium.com/max/630/0*qHzGRLTOMTf30miT.png
Identity vs Equality
In the Python community it is better to use
is
andis not
over==
or!=
If Statements*
if name == 'Monica': print('Hi, Monica.')if name == 'Monica': print('Hi, Monica.')else: print('Hello, stranger.')if name == 'Monica': print('Hi, Monica.')elif age < 12: print('You are not Monica, kiddo.')elif age > 2000: print('Unlike you, Monica is not an undead, immortal vampire.')elif age > 100: print('You are not Monica, grannie.')
Remember the order of elif
statements matter.
While Statements
Break
statement also exists in Python.
As are
continue
statements
Try/Except Statements
Python equivalent to
try/catch
You can name an error to give the output more specificity.
You can also use the
pass
commmand to by pass a certain error.
The
pass
method won’t allow you to bypass every single error so you can chain an exception series like so:
You can use an
else
statement to end a chain ofexcept
statements.
finally
is used at the end to clean up all actions under any circumstance.
Using duck typing to check to see if some value is able to use a certain method.
Pass
Pass Keyword is required to write the JS equivalent of :
Functions
Function definition includes:
The
def
keywordThe name of the function
A list of parameters enclosed in parentheses.
A colon at the end of the line.
One tab indentation for the code to run.
You can use default parameters just like in JS
Keep in mind, default parameters must always come after regular parameters.
You can specify arguments by name without destructuring in Python.
The
lambda
keyword is used to create anonymous functions and are supposed to beone-liners
.
toUpper = lambda s: s.upper()
Notes
Formatted Strings
Remember that in Python join() is called on a string with an array/list passed in as the argument.Python has a very powerful formatting engine.format() is also applied directly to strings.
Comma Thousands Separator
Date and Time
Percentage
Data Tables
**Python can be used to display html, css, and JS.**It is common to use Python as an API (Application Programming Interface)
Structured Data
Sequence : The most basic data structure in Python where the index determines the order.
ListTupleRangeCollections : Unordered data structures, hashable values.
DictionariesSetsIterable : Generic name for a sequence or collection; any object that can be iterated through.Can be mutable or immutable.Built In Data Types
Lists are the python equivalent of arrays.
You can instantiate
Test if a value is in a list.
Instantiated with parentheses
Sometimes instantiated without
Tuple() built in can be used to convert other data into a tuple
Ranges : A list of numbers which can’t be changed; often used with for loops.
Declared using one to three parameters.
Start : opt. default 0, first # in sequence.Stop : required next number past the last number in the sequence.Step : opt. default 1, difference between each number in the sequence.
Dictionaries : Mappable collection where a hashable value is used as a key to ref. an object stored in the dictionary.
Mutable.
Declared with curly braces of the built in dict()
Benefit of dictionaries in Python is that it doesn’t matter how it is defined, if the keys and values are the same the dictionaries are considered equal.
Use the in operator to see if a key exists in a dictionary.
Sets : Unordered collection of distinct objects; objects that need to be hashable.
Always be unique, duplicate items are auto dropped from the set.
Common Uses:
Removing DuplicatesMembership TestingMathematical Operators: Intersection, Union, Difference, Symmetric Difference.
Standard Set is mutable, Python has a immutable version called frozenset.Sets created by putting comma seperated values inside braces:
Also can use set constructor to automatically put it into a set.
filter(function, iterable) : creates new iterable of the same type which includes each item for which the function returns true.
map(function, iterable) : creates new iterable of the same type which includes the result of calling the function on every item of the iterable.
sorted(iterable, key=None, reverse=False) : creates a new sorted list from the items in the iterable.
Output is always a list
key: opt function which coverts and item to a value to be compared.
reverse: optional boolean.
enumerate(iterable, start=0) : starts with a sequence and converts it to a series of tuples
(0, ‘First’), (1, ‘Second’), (2, ‘Third’), (3, ‘Fourth’)
(1, ‘First’), (2, ‘Second’), (3, ‘Third’), (4, ‘Fourth’)
zip(*iterables) : creates a zip object filled with tuples that combine 1 to 1 the items in each provided iterable.Functions that analyze iterable
len(iterable) : returns the count of the number of items.
max(args, key=None) : returns the largest of two or more arguments.
max(iterable, key=None) : returns the largest item in the iterable.
key optional function which converts an item to a value to be compared.min works the same way as max
sum(iterable) : used with a list of numbers to generate the total.
There is a faster way to concatenate an array of strings into one string, so do not use sum for that.
any(iterable) : returns True if any items in the iterable are true.
all(iterable) : returns True is all items in the iterable are true.
Working with dictionaries
dir(dictionary) : returns the list of keys in the dictionary.Working with sets
Union : The pipe | operator or union(sets) function can be used to produce a new set which is a combination of all elements in the provided set.
Intersection : The & operator ca be used to produce a new set of only the elements that appear in all sets.
Symmetric Difference : The ^ operator can be used to produce a new set of only the elements that appear in exactly one set and not in both.
For StatementsIn python, there is only one for loop.
Always Includes:
The for keyword2. A variable name3. The ‘in’ keyword4. An iterable of some kid5. A colon6. On the next line, an indented block of code called the for clause.
You can use break and continue statements inside for loops as well.
You can use the range function as the iterable for the for loop.
Common technique is to use the len() on a pre-defined list with a for loop to iterate over the indices of the list.
You can loop and destructure at the same time.
Prints 1, 2Prints 3, 4Prints 5, 6
You can use values() and keys() to loop over dictionaries.
Prints red
Prints 42
Prints color
Prints age
For loops can also iterate over both keys and values.
Getting tuples
Prints (‘color’, ‘red’)
Prints (‘age’, 42)
Destructuring to values
Prints Key: age Value: 42
Prints Key: color Value: red
Looping over string
When you order arguments within a function or function call, the args need to occur in a particular order:
formal positional args.
args
keyword args with default values
kwargs
Importing in Python
Modules are similar to packages in Node.jsCome in different types:
Built-In,
Third-Party,
Custom.
All loaded using import statements.
Terms
module : Python code in a separate file.package : Path to a directory that contains modules.init.py : Default file for a package.submodule : Another file in a module’s folder.function : Function in a module.
A module can be any file but it is usually created by placing a special file init.py into a folder. pic
Try to avoid importing with wildcards in Python.
Use multiple lines for clarity when importing.
Watching Out for Python 2
Python 3 removed <> and only uses !=
format() was introduced with P3
All strings in P3 are unicode and encoded.md5 was removed.
ConfigParser was renamed to configparsersets were killed in favor of set() class.
print was a statement in P2, but is a function in P3.
https://gist.github.com/bgoonz/82154f50603f73826c27377ebaa498b5#file-python-study-guide-py
https://gist.github.com/bgoonz/82154f50603f73826c27377ebaa498b5#file-python-study-guide-py
https://gist.github.com/bgoonz/282774d28326ff83d8b42ae77ab1fee3#file-python-cheatsheet-py
https://gist.github.com/bgoonz/282774d28326ff83d8b42ae77ab1fee3#file-python-cheatsheet-py
Last updated