PEP8 : Python Enhancement Proposals, style-guide for Python.
print
is the equivalent of console.log
.
#
is used to make comments in your code.
def foo():
"""
The foo function does many amazing things that you
should not question. Just accept that it exists and
use it with caution.
"""
secretThing()
int()
constructor.Boolean is a subtype of integer in Python.
i
is switched to a j
in programming.# Using Float
print(17) # => 17
print(float(17)) # => 17.0
# Using Int
print(17.0) # => 17.0
print(int(17.0)) # => 17
# Using Str
print(str(17.0) + ' and ' + str(17)) # => 17.0 and 17
The arithmetic operators are the same between JS and Python, with two additions:
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.
++
and --
in Python, the only shorthand operators are:Python uses both single and double quotes.
You can escape strings like so 'Jodi asked, "What\'s up, Sam?"'
Multiline strings use triple quotes.
print('''My instructions are very long so to make them
more readable in the code I am putting them on
more than one line. I can even include "quotes"
of any kind because they won't get confused with
the end of the string!''')
Use the len()
function to get the length of a string.
zero-based indexing
Python allows negative indexing (thank god!)
Python let’s you use ranges
print("Spaghetti"[1:4]) # => pag
print("Spaghetti"[4:-1]) # => hett
print("Spaghetti"[4:4]) # => (empty string)
slice
in JS.# Shortcut to get from the beginning of a string to a certain index.
print("Spaghetti"[:4]) # => Spag
print("Spaghetti"[:-1]) # => Spaghett
# Shortcut to get from a certain index to the end of a string.
print("Spaghetti"[1:]) # => paghetti
print("Spaghetti"[-4:]) # => etti
index
string function is the equiv. of indexOf()
in JScount
function finds out how many times a substring appears in a string.print("Spaghetti".count("h")) # => 1
print("Spaghetti".count("t")) # => 2
print("Spaghetti".count("s")) # => 0
print('''We choose to go to the moon in this decade and do the other things,
not because they are easy, but because they are hard, because that goal will
serve to organize and measure the best of our energies and skills, because that
challenge is one that we are willing to accept, one we are unwilling to
postpone, and one which we intend to win, and the others, too.
'''.count('the ')) # => 4
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.
first_name = "Billy"
last_name = "Bob"
print('Your name is {0} {1}'.format(first_name, last_name)) # => Your name is Billy Bob
Shorthand way to use format function is: print(f'Your name is {first_name} {last_name}')
Some useful string methods.
join
is used on an Array, in Python it is used on String. There are also many handy testing methods.
Duck-Typing : Programming Style which avoids checking an object’s type to figure out what it can do.
Assignment of a value automatically declares.
NaN
does not exist in Python, but you can ‘create’ it like so: print(float("nan"))
null
with none
.
none
is an object and can be directly assigned to a variable.# Logical AND
print(True and True) # => True
print(True and False) # => False
print(False and False) # => False
# Logical OR
print(True or True) # => True
print(True or False) # => True
print(False or False) # => False
# Logical NOT
print(not True) # => False
print(not False and True) # => True
print(not True or False) # => False
By default, Python considers an object to be true UNLESS it is one of the following:
None
or False
True
and False
must be capitalized
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:
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.
print (2 == '2') # => False
print (2 is '2') # => False
print ("2" == '2') # => True
print ("2" is '2') # => True
# There is a distinction between the number types.
print (2 == 2.0) # => True
print (2 is 2.0) # => False
is
and is not
over ==
or !=
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.')
elif
statements matter.Break
statement also exists in Python.continue
statementstry/catch
a = 321
try:
print(len(a))
except:
print('Silently handle error here')
# Optionally include a correction to the issue
a = str(a)
print(len(a)
a = '321'
try:
print(len(a))
except:
print('Silently handle error here')
# Optionally include a correction to the issue
a = str(a)
print(len(a))
pass
commmand to by pass a certain error.pass
method won’t allow you to bypass every single error so you can chain an exception series like so:a = 100
# b = "5"
try:
print(a / b)
except ZeroDivisionError:
pass
except (TypeError, NameError):
print("ERROR!")
else
statement to end a chain of except
statements.# tuple of file names
files = ('one.txt', 'two.txt', 'three.txt')
# simple loop
for filename in files:
try:
# open the file in read mode
f = open(filename, 'r')
except OSError:
# handle the case where file does not exist or permission is denied
print('cannot open file', filename)
else:
# do stuff with the file object (f)
print(filename, 'opened successfully')
print('found', len(f.readlines()), 'lines')
f.close()
finally
is used at the end to clean up all actions under any circumstance.def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result is", result)
finally:
print("Finally...")
# Try a number - nothing will print out
a = 321
if hasattr(a, '__len__'):
print(len(a))
# Try a string - the length will print out (4 in this case)
b = "5555"
if hasattr(b, '__len__'):
print(len(b))
def
keyworddef greeting(name, saying="Hello"):
print(saying, name)
greeting("Monica")
# Hello Monica
greeting("Barry", "Hey")
# Hey Barry
def greeting(name, saying="Hello"):
print(saying, name)
# name has no default value, so just provide the value
# saying has a default value, so use a keyword argument
greeting("Monica", saying="Hi")
lambda
keyword is used to create anonymous functions and are supposed to be one-liners
.toUpper = lambda s: s.upper()