If you want to learn just enough Python you will want to focus on three things: 1) Saving Data 2) Manipulating and Comparing Data 3) Reusing code
In order to this you will be learning about variables, data types, methods, and functions. But first, lets learn how to mess up and recover.
The mistake that is most common in Python is having bad indentation.
print "Hi Everyone. Nice to meet you, even this early."
print "You can run this code by clicking on the 'play' button above."
print "Ater you run this code, put some spaces before the second line."
In order to save data for later use you create a variable. Luckily in Python "creating" a variables is as simple as coming up with a name and assigning a value. So:
msg1 = "Good morning" msg2 = "Good afternoon" msg3 = "Good evening" gpa = 3.21 xxyyzz = 5.23
are all examples of variables.
msg1 = "Good morning"
msg2 = "Good afternoon"
msg3 = "Good evening"
gpa = 3.21
xxyyzz = 5.23
print msg1
print msg2
print msg3
print gpa
print xxyyzz
We will talk about four different data types that you use in Python: (Single-ish Values) Numbers -- Integers, Floating Point Numbers, Complex Numbers Strings -- Consecutive characters enclosed in quotes
(Collections) Lists -- A set of data enclosed in [] where elements are separated by commas.
Tuples -- Similar to Lists, but elements are enclosed in () and can not be changed.
Dictionary -- Again, similar to Lists but elements are enclosed in {} and accessed using a key/value pair.
Clearly sometimes you will want to manipuate your data. You can do simple things like add, subtract, multipy, divide, or even find the remainder.
age = 53
print age
print age + 2
print age - 3
print age * 5
print age / 6
print age % 6
This code is very handy for learning about the operators AND experiencing a second common error in new programmers. Usually if you are bothering to perform an operation, you want to save the value somewhere. Lets look at that same code again, but this time with an assignment statement.
age = 53
print age
age = age + 2 #This is the same as age+=2
print age
age = age - 3 #This is the same as age-=3
print age
age = age * 5 #This is the same as age*=5
print age
age = age / 6 #This is the same as age/=6
print age
age = age % 6 #This is the same as age%=6
print age
Strings are used ALL THE TIME in Python. Strings are enclosed in quotes. Python treats single quotes the same as double quotes (but be consistent).
Double quotes allow you to enclose single quotes.
There are also triple double quotes """...""" They allow you to write strings that span multiple lines.
There are many, many built-in functionalities that you will eventually learn. It is impossible to cover (and remember) them all in one sitting.
You can access an entire string variable, or just parts of it. Square brackets are used to specify the index of the data you want. (Indices always start at 0.)
message = "Hello Everyone"
print "The first letter: ", message[0]
print "The 2nd through 9th letters: ", message[1:10]
print "The last letter is ", message[-1]
String operators are special bits of code that ONLY WORK ON STRINGS. So while a "+" will add two numbers, it will concatenate Strings instead of adding them.
Concatenation - Adds values on either side of the operator
Repetition - Creates new strings, concatenating multiple copies of the same string
[] Slice - Gives the character from the given index
[ : ] Range Slice - Gives the characters from the given range
in Membership - Returns true if a character exists in the given string
not in Membership - Returns true if a character does not exist in the given string
a = "Hello"
b = "Python"
print a + b
print a * 5
print "Is H in Hello?", "H" in a
print "Is z in Hello?", "z" in a
print "Is H **NOT** in Hello?", "H" not in a
print "Is z **NOT** in Hello?", "z" not in a
print b[-1]
print b[-2]
print b[-6]
String methods are similar to operators in that they manipulate data, but they are used very differently. Methods use the DOT NOTATION. This means that you put the name of the variable, a dot ("."), the name of the method, and then parentheses.
"123".isdigit()
"one".isdigit()
Sometimes you need to additional information to get a method to work. This information is called a PARAMETER. Parameters are extra pieces of information that are needed to figure out the desired answer.
For instance, one useful method is count, it returns the number of times a substring shows up in a variable. If you want the count method to return something, you better tell it what you are looking for.
a = "Hello Everyone"
print a.count('e')
print a.count('o')
print a.count('z')
Here are some additional String methods: find(), lfind(), rfind(), index(), isalnum(), isalpha(), isdigit(), len(), strip, lstrip(), rstrip(), split()
str = "Value 1, Value 2, Value 3, Value 4";
print str.split( );
print str.split(',');
The value returned by split() is a list. The list is a versatile data type. It is a sequence of comma-separated values encased by square brackets. Items in a list do not have to be of the same type.
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
print me
print you
for info in me:
print info #Try putting a comma after the word info
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
people = [you, me]
print people
print people[0] #Change the 0 to a 1, and then a 2
Lists have a number of functions and methods associated with them. Some functions include: len(list) max(list) min(list) list(seq)
Some of the methods are: count(), index(obj)
Some list methods are in-place. This means that the lists are changed, but the methods don't "return" anything. These include sort(), reverse(), insert(), append(), and remove.
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
her = ["Sally", "James", 25, 'Unknown']
him = ["John", "Doe", 18, 'M']
people = [me, you, her, him]
print people
print "\nList Functions \n"
print "The length of the full list is " ,len(people)
print "The max of the full list is" ,max(people)
print "The min of the full list is" ,min(people)
print "\nList Methods\n"
print "How many times does Colleen appear?", people.count('Colleen')
print "How many times does Colleen list appear?", people.count(me)
print "\nThe initial list is", people
people.sort()
print "Now it is sorted", people
print "\nThe initial list is", people
people.reverse()
print "Now it has been reversed", people
print "\nThe initial list is", people
people.append(['Becca', 'van Lent', 5, 'F'])
print people
print "\nThe initial list is", people
people.insert(2, ['Chris', 'van Lent', 7, 'M'])
print people
Lets do a little input using the raw_input() function.
message = raw_input("Enter your input: ")
print message
print message.find("Colleen")
print message.count("l")
print message.index(" ")
print message.rfind(" ")
Functions and methods are great way to reuse code. Someone wrote some code and you (awesomely) get to use it over and over again. But you can write your own code for reuse as well. One way to do that is to write your own functions. Another way is to use loops.
The real power of computing is selection and repetition. Selection is when you use comparison operators to direct which path the program should take. Repetition is when code is executed multiple times.
num_cookies = 5
while num_cookies > 0:
print "Yum!!"
num_cookies -=1 #Don't unindent this code!!!
print "Only " + str(num_cookies) + " left" #Unindent this code
print "I am full now."
The indentation is VERY, VERY important. You must be consistent, you can't switch back and forth between tabs or individual spaces.
The other thing you need to be VERY worried about is the possibility of infinite loops. Go back up and change the code to num_cookies = 0 or add one instead of subtracting one.
You can use if statements to control which code is executed.
age = raw_input("Enter your age: ")
age = int(age)
if age < 18:
print "Minor"
age = raw_input("Enter your age: ")
age = int(age)
if age < 18:
print "Minor"
else:
print "Adult"
age = raw_input("Enter your age: ")
age = int(age)
if age < 18: #Option 1
print "Minor"
elif age > 100: #Option 2
print "Centenarian"
elif age > 65: #Option 3
print "Senior"
else: #Option 4
print "Adult"
Did you notice the colon : in the if statements? The colon signifies that a block of code is coming. That block of code is indented. You also use the colon when writing loops.
The while loop will execute the block of code over and over until the conditional statement after the word "while" is true.
num = 0
while num <=10:
if num % 2 == 0:
print num
num +=1
The for loop is typically used in two situations. The first is when you know how many time you want to execute a loop. The second is when you want to loop through a collection.
for x in range(0, 3):
print x
for info in me:
print info #Try putting a comma after the word info
list_of_lists = [ [1, 2, 3, 4], [5, 6], [7, 8, 9]]
for list in list_of_lists:
for x in list:
print x #Add another comma here
#print "\n"
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
her = ["Sally", "James", 25, 'Unknown']
him = ["John", "Doe", 18, 'M']
people = [me, you, her, him]
for i in range(len(people)):
print i, people[i]
We have already used functions in this tutorial. A function is a block of reusable code that is used to perform a single (albeit possibly complex) task. Functions allow for code reuse and also allow you to work better as a team. The process of defining a function is as follows:
1) Function blocks begin with the keyword def followed by the function name, parentheses ( ), and colon def myFunction():
2) Any input parameters or arguments should be placed within these parentheses. def printMeALot(msg, times):
3) The code block within every function is indented. def printMeALot(msg, times): for i in range(times): print msg
4) Any return statements will cause an exit from the a function
5) A return statement can pass an expression back to the caller. A return statement with no arguments is the same as return None.
def printMeALot(msg, times):
for i in range(times):
print msg
printMeALot("I am the greatest", 10)
Later you will learn more about using code from others. Below I have two examples of some Python code that uses the Beautiful Soup package. Beautiful soup can parse a webpage, letting you parse the information.
Lets just focus on the code I hope you now can make small changes to. (Start with the for loops.) Can you identify the variables? The loops? Can you find string methods?
import requests
from bs4 import BeautifulSoup
base_url = 'http://www.nytimes.com'
r = requests.get(base_url)
soup = BeautifulSoup(r.text)
for story_heading in soup.find_all(class_="story-heading"):
if story_heading.a:
print(story_heading.a.text.replace("\n", " ").strip())
else:
print(story_heading.contents[0].strip())
import requests
from bs4 import BeautifulSoup
base_url = 'https://www.michigandaily.com/section/opinion'
r = requests.get(base_url)
soup = BeautifulSoup(r.text)
for story_heading in soup.find_all(class_="pane-most-read-panel-pane-1"):
for links in story_heading.find_all(class_="field-content"):
if links.a:
print("\n"+links.a.text.replace("\n", " ").strip())
else:
print("\n"+links.contents[0].strip())