6.1 KiB
Codecademy's Python 2 Course
https://www.codecademy.com/courses/learn-python/lessons/python-syntax/
It's gratis and accepts Python 3 syntax.
Object-oriented
"The main goal of an object oriented language is to make code reusable – we do this through the use of classes and objects. If we want to design a new type of car, we can start with what they all have in common: wheels, seats, a frame. Now that we’ve determined what cars have in common, we can more easily implement any type of car we want by starting from that basic blueprint."
https://discuss.codecademy.com/t/what-does-it-mean-that-python-is-an-object-oriented-language/297314
Errors (ex6, CH1, P3)
"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.
A NameError occurs when the Python interpreter sees a word it does not recognize. Code that contains something that looks like a variable but was never defined will throw a NameError."
SyntaxError example: SyntaxError: EOL while scanning string literal
Math (ex6)
mirthful_addition = 12381 + 91817
amazing_subtraction = 981 - 312
trippy_multiplication = 38 * 902
happy_division = 540 / 45
sassy_combinations = 129 * 1345 + 120 / 6 - 12
exponents = (16 ** 0.5) # 16 to the 1/2th power. (4)
remainder = (15 % 2) # The remainder (and thus the result) equals 1
Find the remainder of a number using %
is_this_number_odd = 15 % 2
is_this_number_divisible_by_seven = 133 % 7
Updating variables / operators.
sandwich_price += sales_tax
is the same as:
sandwich_price = sandwich_price + sales_tax
but is much shorter.
Comments
Are indicated by # or """This is not for running"""
Numbers
An integer is like 5
, a float is a number with a decimal point like 5.0
. They can also be in scientific notation like 2.3e7
In Python 2, you need to make sure math like 7/2
= 3.5
is correct is by inputting it into Python like 7./2.
or float(7)/2
Limitations of floats
Floats are limited by the number of digits. For example 1/3 = 0.3
>>> format(math.pi, '.12g') # give 12 significant digits
'3.14159265359'
>>> format(math.pi, '.2f') # give 2 digits after the point
'3.14'
Strings
Multi-line strings are marked by
Mulit-
line
strings"""
Booleans (True/False)
True = int(1) False = int(0)
Relational Operators (ch.4, ex. 3)
==
returns True
if is is equal and returns False
otherwise.
!=
returns True
if is is NOT equal and returns False
otherwise.
Here are more of he same kind of operator:
>
greater than
<
less than
>=
greater than or equal to
<=
less than or equal to
Datatypes
Force treating as a string: str(7) Force treating as an integer: int("7") Froce treating as a float: float(7)
Check Datatypes
Check datatypes using type(var)
Escaping Characters
Simply add a \
to escape a character that would otherwise cause issues.
Arrays / Indexes
cows = "cows"[0]
This sets the variable cows
to the 0th letter of the string "cows"
which is c
. These indexes start at 0, not 1.
Strings
String Methods
len(var)
Get length of string.
var.lower()
Force lowercase
var.upper()
Force uppercase
str(var)
Force treating variable as a string.
If it uses dot notation like .lower()
, it works exclusively on strings.
Concatenation
"Ten times a cow is equal to " + result + " with 10 times as many breeding opportunities."
or
print(var, var2, var3)
or
string1 += string2
String Formatting with %
"%s %s - 2020" % (month, day) # Replace %s with a variable. First the month, then the day.
Add %03d to specify a signed integer padded 2 places with zeros. For example, 2 becomes 02.
This is super useful for displaying dates like this: print("%02d-%02d-%02d") % (now.month, now.day, now.year)
or time like this: print '%02d:%02d:%04d' % (now.hour, now.minute, now.second)
(Ch3, Ex. 4)
Date and Time (Ch3)
Grab the current time:
from datetime import datetime
now = datetime.now()
year = now.year
month = now.month
day = now.day
Function P3 Ch.2
Defining a Function
def greet_customer():
print("Welcome!")
Calling Functions
```
greet_customer()
```
or if it has parameters:
greet_customer(1,ten)
Passing Arguments
greet_customer(special_item):
print(special_item)
greet_customer(beef)
Result:
beef
Using Keyword Arguments
Keyword arguments are nice for specifying a default but changeable argument.
Here's an example from P3, Ch2, ex7
def create_spreadsheet(title, row_count = 1000):
row_count = str(row_count)
print("Creating a spreadsheet called " + title + " with " + row_count +" rows.")
create_spreadsheet("Applications", row_count = 10)
row_count = 1000
is the default
row_count = 10
is the passed argument and thus what is used for a result:
Creating a spreadsheet called Applications with 10 rows.
Returning Stuff
You can return stuff like this to store for later:
def addfour(number, cow):
addedfour = number + 4
cat = number - 4
return addedfour, cat # All returned arguments must be on the same return call.
I'll make it add four to 456
yo, cow = addfour(456)
print ("456 + 4 equals " + str(yo) )
460
You can also do this with multiple arguments:
x_squared, y_squared = square_point(1, 3)
Fun Projects
Design a shop using Ex7 and Ex9 as a frame:
7:
money_in_wallet = 40
sandwich_price = 7.50
sales_tax = .08 * sandwich_price
sandwich_price += sales_tax
money_in_wallet -= sandwich_price
9:
cucumbers = 1
price_per_cucumber = 3.25
total_cost = cucumbers * price_per_cucumber
print(total_cost)
total_price += nice_sweater
Cool concept from Ch2 Ex15:
name = raw_input("What is your name? ")
quest = raw_input("What is your quest? ")
color = raw_input("What is your favorite color? ")
print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)