Python (Notes, Ch. 1-7)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

Python

Number are one data type in programing


2nd type is called Boolean. Boolean are like a light switch. It can only have two
values: True or False (remember to Capitalize True and False)
In Python, whitespace is used to structure code. Whitespace is important, so
you have to be careful with how you use it.
The # sign is for comments. A comment is a line of text that Python won't try
to run as code. It's just for humans to read.

The # sign will only comment out a single line. While you could write a multi-line
comment, starting each line with #, that can be a pain.Instead, for multi-line comments,
you can include the whole block in a set of triple quotation marks:

you can combine math with other data types (e.g. booleans) and commands
to create useful programs.
o use ** for ^
Our final operator is modulo. Modulo returns the remainder from a division.

o In computing, the modulo operation finds the remainder after division of one
number by another (sometimes called modulus).
o Given two positive numbers, a (the dividend) and n (the divisor), a modulo n
(abbreviated as a mod n) is the remainder of the Euclidean division of a by n. For
instance, the expression "5 mod 2" would evaluate to 1 because 5 divided by 2
leaves a quotient of 2 and a remainder of 1, while "9 mod 3" would evaluate to 0
because the division of 9 by 3 has a quotient of 3 and leaves a remainder of 0
Recap:

Nice work! So far, you've learned about:

Variables, which store values for later use

Data types, such as numbers and booleans

Whitespace, which separates statements

Comments, which make your code easier to read

Arithmetic operations, including +, -, *, /, **, and %

Tip Calculator:

you're allowed to reassign a variable in terms of itself!

Strings & Console Output


Strings are amongst the most popular types in Python. We can create them simply
by enclosing characters in quotes. Python treats single quotes the same as double
quotes. Creating strings is as simple as assigning a value to a variable.

Another useful data type is the string. A string can contain letters, numbers,
and symbols.

Python thinks the apostrophe in 'There's' ends the string. We can use the backslash to
fix the problem, like this:

In Python, we start counting the index from zero instead of one.


Each character in a string is assigned a number. This number is called the
index.
o Ex: X = something Y [3]

String methods let you perform specific tasks for strings.


o We'll focus on four string methods:

'There\'s a snake in my boot!'

1. len()-gets the length (the number of characters) of a string! Ex;


len(ministry)

2. lower()-get rid of all the capitalization in your strings. ex;


Ryan.lower()

3. upper()-makes it all upper case ex; parrot.upper()


4. str()-turns non-strings into strings! For example: str(2)would
turn 2 into "2".

Methods that use dot notation only work with strings.


o On the other hand, len() and str() can work on other data types.

Printing Strings:

The area where we've been writing our code is called the editor.
The console (the window in the upper right) is where the results of your code is shown.

simply displays your code in the console.


Print has to be spelled all with lower case
Concatenation- combining strings togetherThe + operator between strings will
print

'add' them together, one after the other. Notice that there are spaces inside
the quotation marks
o Ex; print "Life " + "of " + "Brian". You have to make sure there is
space between Life and .so its life and not life

String Formatting with %

The % operator after a string is used to combine a string with variables. The %
operator will replace a %s in the string with the string variable that comes
after it.

o string_1 = "Camelot"
o string_2 = "place"
o
o print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)

Let's not go to Camelot. 'Tis a silly place.

The \ character on line 5 is a continuation marker. It simply tells Python that line 5
continues onto line 6.

Three ways to create strings


'Alpha'
"Bravo"
str(3)

String methods
len("Charlie")
"Delta".upper()
"Echo".lower()

Printing a string
print "Foxtrot"

Advanced printing techniques


g = "Golf"
h = "Hotel"
print "%s, %s" % (g, h)

The datetime Library

from datetime import datetime


o print datetime.now()
o The first line imports the datetime

library so that we can use it.

o The second line will print out the current date and time.

To change format:
o
o
o
o
o
o

from datetime import datetime


now = datetime.now()
current_year = now.year
current_month = now.month
current_day = now.day

Conditionals & Control Flow

Control flow gives us this ability to choose among outcomes based off what
else is happening in the program.

Let's start with the simplest aspect of control flow: comparators. There are six:

1. Equal to (==)
2. Not equal to (!=)
3. Less than (<)
4. Less than or equal to (<=)
5. Greater than (>)
6. Greater than or equal to (>=)
o

Note that == compares whether two things are equal, and = assigns a
value to a variable.

Boolean operators compare statements and result in boolean values. There are three
boolean operators:

1. and, which checks if both the statements are True;

2. or, which checks if at least one of the statements is True;


3. not, which gives the opposite of the statement.

Just like with arithmetic operators, there's an order of operations for boolean operators:
1. not is evaluated first;
2. and is evaluated next;
3. or is evaluated last.
o For example, True or not False and False returns True

True or not False and False. not

gets evaluated first, so we have

True or True and False. and

True or False. As we've seen, True or False


finally returned is True!

goes next, so we get


is True, so the value

Parentheses () ensure your expressions are evaluated in the order you


want. Anything in parentheses is evaluated as its own unit.
Notework on not.fucked that up and shit
o

Conditional Statement Syntax

o
o
o

is a conditional statement that executes some specified code after checking if its
expression is True.
o Here's an example of if statement syntax:
if

if 8 < 9:
print "Eight is less than nine!"
The else statement complements the if statement.

"Elif" is short for "else if." It means exactly what it sounds like: "otherwise, if
the following expression is true, do this!"
In python the indentation is very important !!!
o

return True

PigLatin:
o if and else do NOT need to be indented.
o Let's make sure the word the user enters contains only alphabetical
characters. You can use isalpha() to check this!

o Advanced Tip! When slicing until the end of the string, instead of providing
len(new_word), you can also not supply the second index:

Functions:
o Instead of rewriting the whole code, it's much cleaner to define a function,
which can then be used repeatedly.

o Functions are defined with three components:


o The header, which includes the def keyword, the name of the function,
and any parameters the function requires.

o An optional comment that explains what the function does.


o The body, which describes the procedures the function carries out. The
body is indented, just like for conditional statements.

o comment of your own choosing (enclose it in triple quotes!).


o spam() in the last line told the program to look for the function called spam and
execute the code inside it.

o Don't forget the colon at the end of your function definition!


o When you simply import a module this way, it's called a generic import.
o --- import math
o --- print math.sqrt(25)
o Pulling in just a single function from a module is called a function import,
and it's done with the from keyword:
o

from module import function


o from math import sqrt
don't want to have to constantly type math.?

o Universal import can handle this for you. The syntax for this is:

from module import *

from math import * this imports everything


o maximum = max()
o minimum = min()
o The abs() function returns the absolute value
o Finally, the type() function returns the type of the data it receives as an
argument.

Function:
o

print type(42)
print type(4.2)
print type('spam')

Python will output:

<type 'int'>
<type 'float'>
<type 'str'>

def fruit_color(fruit):
if fruit == "apple":
return "red"
elif fruit == "banana":
return "yellow"
elif fruit == "pear":
return "green"

1. The example above defines the function fruit_color that accepts a string as the
argument fruit.
2. The function returns a string if it knows the color of that fruit.
Lists and Dictionaries:

o Lists are a datatype you can use to store a collection of different pieces of

information as a sequence under a single variable name.


o Datatypes you've already learned about include strings, numbers, and
booleans.
o

list_name = [item_1, item_2]

o with the items in between brackets. A list can also be empty:


empty_list = [].

o You can access an individual item on the list by its index.


o list_name[index]
o You can see how assignment works on line 5:
o

zoo_animals[2] = "hyena"
# Changes "sloth" to "hyena"
You can add to your list later on by doing ____.append()
o .append only can add one at a time
o Len(____) will do the list length

o You can slice a string exactly like a list! In fact, you can think of strings as lists of
characters: each character is a sequential item in the list, starting from index 0.
o
o
o
o
o
o

my_list[:2]
# Grabs the first two items
my_list[3:]
# Grabs the fourth through last items
If your list slice includes the very first or last item in a list
(or a string), the index for that item doesn't have to be
included.
If you want to do something with every item in the list, you can
use a for loop.
A variable name follows the for keyword; it will be assigned
the value of each list item in turn.
Then in list_name designates list_name as the list the loop
will work on. The line ends with a colon (:) and the
indented code that follows it will be executed once per item
in the list.
.sort() modifies the list rather than returning a new list.

o Key
o A dictionary is similar to a list, but you access values by looking up a key instead of an
index. A key can be any string or number. Dictionaries are enclosed in curly braces, like
so:
o

d = {'key1' : 1, 'key2' : 2, 'key3' : 3}


This is a dictionary called d with three key-value pairs. The

key 'key1' points to the

value 1, 'key2' to 2, and so on.


o Dictionaries are great for things like phone books (pairing a name with a phone number),
login pages (pairing an e-mail address with a username), and more!
o Print the values stored under the 'Sloth' and 'Burmese Python' keys.
Accessing dictionary values by key is just like accessing list values by index:
o

residents['Puffin']
# Gets the value 104

o Like Lists, Dictionaries are "mutable". This means they can be changed after they are
created. One advantage of this is that we can add new key/value pairs to the dictionary
after it is created like so:
o

dict_name[new_key] = new_value

o An empty pair of curly braces {} is an empty dictionary, just like an empty pair of
[] is an empty list.
o
o
o

del dict_name[key_name]
<- this deletes
dict_name[key] = new_value <- this adds a new value
removing a new item is
.remove(item)

Looping with Lists and Dictionaries:

o for loops allow us to iterate through all of the elements in a list from the left-most (or
zeroth element) to the right-most element. A sample loop would be structured as follows:
o
o
o

a = ["List of some sort]


for x in a:
# Do something for every x

o This loop will run all of the code in the indented block under the for x in a:
statement.

for item in [1, 3, 21]:


print item

would print 1, then 3, and then 21.

o You can also use a for loop on a dictionary to loop through its keys with the following:

o
o
o
o
o

# A simple dictionary
d = {"foo" : "bar"}
for key in d:
print d[key]

# prints "bar"

o Note that dictionaries are unordered, meaning that any time you loop through a
dictionary, you will go through every key, but you are not guaranteed to get them in any
particular order.
o Create a new dictionary called prices using {} format like the example above.
o Put these values in your prices dictionary, in between the {}:
Remember to use square brackets for a list: [].
5 / 2
# 2
5.0 / 2
# 2.5
float(5) / 2
# 2.5

The above example is a reminder of how division works in Python.


1. When you divide an integer by another integer, the result is always an integer (rounded
down, if needed).
2. When you divide a float by an integer, the result is always a float.
3. To divide two integers and end up with a float, you must first use float() to convert one
of the integers to a float.
o

The \ character is a continuation character. The following line is


considered a continuation of the current line.

Lists and Functions:


o

code to print out the second element in the list.


o n = [1, 3, 5]
o
o # Add your code below
o print n[1]

1. n.pop(index) will remove the item at index from the list and return it to you:
n = [1, 3, 5]
n.pop(1)

# Returns 3 (the item at index 1)


print n
# prints [1, 5]

1. n.remove(item) will remove the actual item if it finds it:


n.remove(1)
# Removes 1 from the list,
# NOT the item at index 1
print n
# prints [3, 5]

1. del(n[1]) is like .pop in that it will remove the item at the given index, but it won't
return it:
del(n[1])
# Doesn't return anything
print n
# prints [1, 5]

The range function has three different versions:


1. range(stop)
2. range(start, stop)
3. range(start, stop, step)
In all cases, the range() function returns a list of numbers from start up to (but not including)
stop. Each item increases by step.
If omitted, start defaults to zero and step defaults to one.
we have two ways of iterating through a list.
Method 1 - for item in list:
for item in list:
print item

Method 2 - iterate through indexes:


for i in range(len(list)):
print list[i]

Method 1 is useful to loop through the list, but it's not possible to modify the list this way.
Method 2 uses indexes to loop through the list, making it possible to also modify the list if
needed. Since we aren't modifying the list, feel free to use either one on this lesson!
1M*(1+x-2*x^2)

You might also like