-phython is good for calculations ,they can be automated
Unit 1
“Print” - prints statements onto the console
Boolean - True OR False (written exactly like this)
Ex your_mama = False
Unit 2
String - contains numbers letters and symbols
Ex name = “Ryan”
Escaping characters - (\) <- the command
-some time words in stings like’ makes the string un stringly so you gotta add / to it
● len() - gives the number of letters in a string
Ex: parrot = "Norwegian Blue"
print len(parrot)
This print “14”
● lower() - gets rid of capitalization
Ex:
Parrot (the variable from the last).lower()
● upper() - makes stuff uppercase
The same notation as lower
Ex : print parrot.upper()
● len() -checks the length of string ( it starts readin g aty 0 )
]
-
Ex:
● str() - turns non strings strings
ex :
Pi = 3.24
Print str(pi)
● Dot notation (like .upper)
- Dot notation is used only with strings
Parentheses notation (not formal) ex:len() can work on other data types
Parts of code
- Editor: the part where you write code
- console : results of code
String concatenation
- def : Using strings and math operators (+) to print strings
Ex: print "Spam" + " and" + " eggs
Explicit string conversion
-when you printing a string with non string
String formating
● The faster way to add variables to strings
Date time
- datetime.now()
● Shows the exact date and time
- print now.hour
-now.minute
-now.second
-now.year
-now.month
-now.day
Mad libs
-
-m\
raw _input
- lets user types stuff , solely for strings.
- accepts a string, prints it, and then waits for the user to type something and
press Enter (or Return).
Ex: name = raw_input( “enter a name”)
(Go back to a certain lesson i dont think i wrote it down)
Unit 3 : Conditionals an control flow
- Def: Gives the code the ability to choose among outcomes base on what else is
happening in the program.
Comparators (goes with boolens true and false stuff)
- There are 6
● Equal to (==)
● Not equal to (!=)
● Less than (<)
● Less than or equal to(<=)
● Greater than(>)
● Greater than or equal to(>=)
ex : >>> 2 == 2
True
>>> 2 == 5
False
- Compares values
-
-
-
- There’s an order to these operators
Order of operations:
1. not
2. And
3. Or
You can use parentheses to get everything in the order you want
Conditional Statement Syntax
-make sure the stuff uner if else stuff is indented, thats how
If: executes specified code after checking if the expression is true
indentation before the print statement. This space, called white space, is how
Python knows we are entering a new block of code. (you can indent with b4
spaces )
If the indentation from one line to the next is different and there is no command
(like if) that indicates an incoming block then Python will raise an
IndentationError. These errors could mean, for example, that one line had two
spaces but the next one had three. Python tries to indicate where this error
happened by printing the line of code it couldn’t parse and using a ^ to point to
where the indentation was different from what it expected.
Else /if else: if the the if statement is false then the else statement will run.
- Doesnt depend on an expression,like 8>9
Ex:
def black_knight():
if answer == "'Tis but a scratch!":
return True
else:
return False
Elif: a short for else if
Ex: if 8 > 9:
print "I don't get printed!"
elif 8 < 9:
print "I get printed!"
else:
print "I also don't get printed!"
In this ex the elif statement is only checked if the og if statement is
true
Lesson 6,7,8,9
.isalpha()- can be used to check that a string
-if its not a string it will return false
ex:if len(original) > 0 and original.isalpha():
-You can use and to add on to an if statement
Ex: if 8==9
And 0==7
Print “silly”
-notation: s = ‘charlie’
print s[0] (this will print only the c)
Print s[1:4](this will print har,returing everything at
position one to 4)
Set new_word equal to the slice from the 1st index all the way to the end of new_word.
Use [1:len(new_word)] to do this.
When slicing until the end of the string, instead of providing len(new_word), you can
also not supply the second index:
ex:
Python
my_string = "Python"
my_string[1:] # "ython"
%- combines strings with variables
Ex quarter = 0.25
print "A quarter is %f" % (quarter)
The %f will be replaced with % /,,[;
Functions
- Can be used when you want to reuse a piece of code but with diff values.
Def: Function : -the header, optional comment, and the body
header - includes the def key word, the name of the function, and any requirements the function
needs
Comment-just says what its supposed to do
body - describes what the function carries out. Its always indented.
Ex def hello_world():
"""Prints 'Hello World!' to the console."""
print "Hello World!"
After defining a function it must be called to be used
We do this by putting Name_of_fucntion() ←- just like that, at the end of the
function , or where ever you want the function to be used (im guessing on the
last part)
def square(n):
- You can put a variable inbetween the paranties so when your ready to
the function you can put in a values which will carry out any
calculations what was done inside the function
-
Variables are called parameters in code , its an input to teh function
Values of the parameters passed into a function is called arguments
- Usually the arguments are the same number as the parameters
Functions calling functions
def fun_one(n):
return n * 5
def fun_two(m):
return fun_one(m) + 7
Module: A file that contains definitions-including
variables and functions-v that you can use once imported.
How to import modules
- Use the word import then add what ever
module you want (called genric import)
Ex: import math
Print math.sqrt(25) ← will find the square
root of 25
-
Modules
Math
( lets
you
use
math
functi
ons)
Universal modules
- When you dont want to keep tying
math. And such
- Knowing when to use them is
important.
● They fill up your program with
alot of variables and function
names
SO BASICALLY I GOT LOST EL OH EL
Universal imports may look great on the surface, but they’re not a good idea for
one very important reason: they fill your program with a ton of variable and
function names without the safety of those names still being associated with the
module(s) they came from.
If you have a function of your very own named sqrt and you import math, your
function is safe: there is your sqrt and there is math.sqrt. If you do from math
import *, however, you have a problem: namely, two different functions with the
exact same name.
Even if your own definitions don’t directly conflict with names from imported
modules, if you import * from several modules at once, you won’t be able to
figure out which variable or function came from where.
For these reasons, it’s best to stick with either import moduleand type
module.name or just import specific variables and functions from various modules
as needed.
The format is: from module import *
LESSON 12
MAX(): A function that takes any number of arguments
and returns the largest one
-best to use on integers and floats.
Ex: max(1,2,3) -> will return 3
min(): returns the smallest v alue
abs() : absolute values ,only takes single number
type():prits out the type of data type.
Ex print type(42) -> <type ‘int’>
Python 3
-alot of this stuff is the same so im just leav ing it in the same docs
Lists
List: data structure, allows us to work with a
collection of data in a sequence order
Ex: heights = [61, 70, 67, 64]
1. A list begins and ends with square brackets ([and ]).
2. Each item (i.e., 67 or 70) is separated by a comma (,)
3. It’s considered good practice to insert a space ( ) after each comma, but
your code will run just fine if you forget the space.
- Can have strings, numbers, literally any data type
Empty list: we use when we planning to fill it up
later
Ex: my_dog = []
.append(): Adds element at the end of the list
ex:example_list = [1, 2, 3, 4]
#Using Append
example_list.append(5)
- You can even use append with variables ,i found
its easy to make a variable with a list to add
atthed end of the 2d list
● To add multiple items to a list you can use + to
combine two lists(concatenation)
● Index: location of element
● In python it starts from 0
To call an element from a list type number the item
Ex: print(calls[2])
Will out put: Amamre
hen accessing elements of a list, you must use an int as the index.
To solve this problem, you can force the result of your division to be an int by
using the int() function.
Ex: calls[int(4/2)]
● Can use -1 to se;ect the last element in a list
● Modifying elements
● - just assign values using specif index
Ex: garden[2] = "Strawberries"
print(garden)
.remove(): remove element
Ex: shopping_line.remove("Chris"
Two-Dimensional (2D) Lists
-lists in lists
ex:heights = [["Noelle", 61], ["Ava", 70], ["Sam", 67], ["Mia", 64]]
Lesson 2 of lists
.sort() Python list method will sort the contents of whatever list it is called
on. Numerical lists will be sorted in ascending order, and lists of Strings will be
sorted into alphabetical order. It modifies the original list, and has no return
value.
.insert(): allows us add an element to a specific index in a list
It expects two inputs:
1. The index you want to insert into
2. The element you want to insert at the specified index
-will handle shifting over elements and can be used with negative indices.
-When we insert an element into a list, all elements from the specified index and
up to the last index are shifted one index to the right. This does not apply to
inserting an element to the very end of a list as it will simply add an additional
index and no other elements will need to shift.
.pop(): removes items at specific index
The .pop() method takes an optional single input:
The index for the element you want to remove.
-if you dont put the index it will remove the last element in the list .
- will return the value that was removed
If we wanted to know what element was deleted, simply assign a variable to the
call of the .pop()method. In this case, we assigned it to removed_element.(?????)
Passing in an index that does not exist or calling .pop() on an empty list will
both result in an IndexError.
range():takes a single input and generates numbers starting at 0 and ending at
the number before the input
ex:my_range = range(10)
- Too use rangeas a list ya must convert to list using list()
- list():takes in a single input for the object ya want ot convert
ex : print(list(my_range))
It would Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
if we want our range to start at diff numerers:
- Just put two numbers in range
- Ex: range(2, 9)
- It will make numbers from 2 till 8
If we want the list to skip in increments we put them in then we can put it at the end
len(): used to find the length of an object
ex : long_list_len = len(long_list)
Range objects do not need to be converted to lists in order to determine their
length
Slicing Lists I
-we often only wnat a portion of a list
Slicing: is when we extract only a portion of a list
The structure of slicing
Variable[start:end]
Ex: sliced_list = letters[1:6]
print(sliced_list)
- The end is gonna be one more than the actual index
You can also slice like
Variable[:x]
It will slice the first x items except the last one (like [:3] will print till 2)
Negative indices can also accomplish taking all but n last elements of a list.
.count():counts the appearances of an element
num_i = letters.count("i")
print(num_i)
It will print a number
ex:um_pairs = number_collection.count([100, 200])
print(num_pairs)
If you want to know how often the sublist [100, 200} appears
.sort(): sorts a list in alphabetical order or numerical
- You can sort in reverse by putting .sort(reverse = True)
- Sort doesnt return a value so it doesntg need to assigned a variable
sorted()
- comes before a list, instead of after as all built-in functions do.
It generates a new list rather than modifying the one that already exists.
-you assign a variable to this one
Ex: sorted(names)
Tuples exist - they are like lists exc ept you cant change them