Phython 2 and 3
Phython 2 and 3
Unit 1
Ex:
Parrot (the variable from the last).lower()
Ex : print parrot.upper()
Ex:
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
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”)
- Def: Gives the code the ability to choose among outcomes base on what else is
happening in the program.
You can use parentheses to get everything in the order you want
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():
return True
else:
return False
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!"
Ex: if 8==9
And 0==7
Print “silly”
-notation: s = ‘charlie’
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"
Functions
- Can be used when you want to reuse a piece of code but with diff values.
header - includes the def key word, the name of the function, and any requirements the function
needs
body - describes what the function carries out. Its always indented.
Ex def hello_world():
"""Prints 'Hello World!' to the console."""
print "Hello World!"
- 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
def fun_one(n):
return n * 5
def fun_two(m):
return fun_one(m) + 7
-
Modules
Math
( lets
you
use
math
functi
ons)
Universal modules
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.
LESSON 12
Python 3
-alot of this stuff is the same so im just leav ing it in the same docs
Lists
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.
Ex: my_dog = []
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
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)]
● Modifying elements
● - just assign values using specif index
Ex: garden[2] = "Strawberries"
print(garden)
Ex: shopping_line.remove("Chris"
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.
-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:
-if you dont put the index it will remove the last element in the list .
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.
ex:my_range = range(10)
ex : print(list(my_range))
If we want the list to skip in increments we put them in then we can put it at the end
ex : long_list_len = len(long_list)
Slicing Lists I
Variable[start:end]
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.
If you want to know how often the sublist [100, 200} appears
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.
Tuples exist - they are like lists exc ept you cant change them