There are very few things you need to know as languages change from one version to another. The biggest problem is knowing which language your packages are expecting. In the past few years more and more applications have moved to Python3 which is why we are switching too. Unfortunately, even though the changes may not seem very big it is important to run the proper version else your program may crash. Spectacularly.
In almost all cases, programming is about three things: 1) Saving data as variables. 2) Manipulating and comparing data (usually using fuctions). 3) Looping
message = "Colleen"
print (message)
age = 5
print (age)
Just assigning values and then printing them is boring. Same with big data, sometimes you will want to manipuate your data. You can do simple operations like add, subtract, multipy, divide, and concatenate very easily.
age = 35
print (age)
print (age + 2) //IF the value stored in the variable "age" is a number, print the value + 2 (String would concatenate)
print (age / 5) //IF the value stored in age is a number, divide it by 5
print (age / 6) //IF the value stored in age is a number, divide it by 6
print (age % 6) //IF the value stored in age is a number find the remainder when divided by 6
The computer will let you add numbers, but not numbers and strings.
age = int("35")
print (age)
print (age + 2)
print (age)
print (age / 5)
print (age / 4)
print (age % 4)
print (age)
#name = "Colleen"
#print (name+2)
Strings are an extremely popular data type in Python. This may be because computers often "read" numbers as strings. Python treats single quotes the same as double quotes, the main difference is that double quotes do allow you to enclose single quotes. You can use either convention, but the key is CONSISTENCY.
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 antire string variable, or just parts. To access just parts you use square brackets to specify the index of the data you want.
message = "Hello Everyone"
print (message);
print ("The first letter in message is: " , message[0])
print ("The 2nd through 9th letters are: ", message[1:35])
String operators are special bits of code that ONLY WORK ON STRINGS. For instance, we have already seen that "+" does addition on numbers, but will perform concatenation on Strings.
+ Concatenation - Adds values on either side of the operator
* Repetition - Creates new strings, concatenating multiple copies of the same string a
[] Slice - Gives the character from the given index (A negative number starts from the end)
[ : ] 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 ("h" in a)
print ("H" in a)
print ("z" in a)
print ("H" not in a)
print ("z" not in a)
print (b [-1])
print (b [-2])
print (b [-3])
The string operators return information about a string and they are a part of the Python language. There is another set of tools called methods. 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 parantheses. For instance, since you don't always know if the person typed in a number or not, you can use the method isdigit() to find out.
variable.isdigit()
Sometimes you need to put parameters in the parantheses. 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 gorgeous"
print (a.count('l'))
print (a.count('o'))
print (a.count('O'))
a = "Hello there awesome super super awesome programmers"
print (a.count('l')) #This is a lowercase letter l, not the number 1.
print (a.count('o'))
print (a.count('O')) #This is an uppercase O, not the number 0
print (a.count('super'))
Some methods have optional parameters. These are pieces of information you can give, but aren't necessary. For instance, the count method can also take a start and end index.
a = "Hello there Sheila"
print (a.count('l', 5))
print (a.count('l', 5, 10))
Here are some additional String methods: find(), rfind(), index(), isalnum(), isalpha(), isdigit(), len(), strip, lstrip(), rstrip(), split()
print (a.find('t'))
print (a.find('z'))
print (a.index('t'))
#print (a.index('z')) #What happens if I run this command?
Just because a method exists doesn't mean you can always use it. In the example above we are asking Python to do find the index of a character that doesn't exist. Sometimes you need to combine commands, e.g. first make sure it exists, and then find it. This idea of "If/then" is something we will get to a little later.
str1 = "Value 1, Value 2, Value 3, Value 4";
print (str1.split( ));
print (str1.split(',')); #I picked the comma for a reason, can anyone guess why?
The value returned by split is a LIST. The list is THE most versatile datatype available in Python. 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[0])
print (me[1])
print (me[2])
print (me[3])
#print (you)
#print (me + you)
for info in me:
print (info)
#for info in me:
# print(info,"\t", end="") #You can replace that \t with an empty space
Lists of lists
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
people = [you, me]
print (people)
Lists have a number of functions and methods associated with them Some of the functions are:
Some of the list methods are:
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 (len(people))
print (max(people))
print (min(people))
print ("\nList Methods\n")
print (people.count('Colleen'))
print (people.count(me))
people.sort()
print (people)
people.reverse()
print (people)
people.append(['Becca', 'van Lent', 5, 'F'])
print (people)
people.insert(2, ['Chris', 'van Lent', 7, 'M'])
print (people)
Lets do a little input using the input() function.
message = input("Enter your input: ")
print (message)
print (message.find("Colleen"))
print (message.count("e"))
print (message.index(" "))
print (message.rfind(" "))
The real power of computing is selection and repetition. Selection is when you use comparison operators to direct which path the program should take.
Iteration (also called repetition by some) is when code is executed multiple times even though you only wrote it down once. You signal to the computer that you may want to loop with a keyword such as for or while. You must include a test case with this word so the computer can figure out when to execute the code. The code you want to repeat must be indented.
num_cookies = 5
while num_cookies > 0: ## Very important colon at the end of this line.
print ("Yum! I love eating cookies!") ## Notice that this line is indented
num_cookies -=1 ## Notice that this line is indented
print ("Only " + str(num_cookies) + " left..") ## Notice that this line is indented
print ("I feel a little full now.") ## Not indented here...
The indentation is VERY, VERY important. You must be consistent, I recommend that you don't use tabs, use 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.
##Can you write a program that prints the numbers from 0 to 10 by 2?
print(0)
print(2)
print(4)
print(6)
print(8)
print(10)
Can you fix the code below to get the correct output?
num = 0
while num < 10:
print(num)
num+=2
If were to combine the looping construct for with the range function we get close, but not quite...
for num in range(10):
print(num)
One problem with the example below is that we are executing all of the statements, even if we sometimes would rather skip them. What we want to do is use an if statement to only execute some students under certain situations. Here is a simple example.
age = 25
if age < 18:
print ("Minor")
elif age > 100:
print ("Centenarian")
elif age > 65:
print ("Senior")
else:
print ("Adult")
Can you use selection to fix our earlier code? Here is a tip, don't forget about the modulus operator %. It will find the reminder.
for num in range(10):
print(num)
Because lists can contain a lot of data, it makes sense that we may want to use selection and iteration when using them.
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])
There is a shortcut you can use when you wan to loop through lists..
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 person in people:
print (person)
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). 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)
In the example above we wrote a function, called a built-in function (range), and called our own function. We also called the print function. In the latest versions of Python, print has been changed to a function again.
I am going to introduce something new that doesn't work particularly well in iPython Notebook. The key to know is that the square icon above will stop the program from running. (Also useful to know in the case of infinite loops.) The Turtle program is simple to use and is meant to help beginner programs with a visual representation of a "turtle" moving around the screen. To use the Turtle program you will need to import it from the libraries. The first program is a sample from python.org. The second program is a simple block. The third adds some random functions and colors.
When this eventually crashes your machine, use the restart icon above. It is the "refresh" arrow.
Can you make a block M?
##FROM https://docs.python.org/3.2/library/turtle.html
from turtle import *
color('red', 'yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()
from turtle import *
color('blue')
pencolor('yellow')
pensize(20)
pendown()
begin_fill()
forward(250)
right(90)
forward(250)
right(90)
forward(250)
right(90)
forward(250)
end_fill()
done()
from turtle import *
import random
pencolor(.5, 0, .2) #RGB
goto(-300, 300)
pendown()
begin_fill()
for x in range(10):
# choose a random spot
xpos = random.randint(-500,500)
ypos = random.randint(-500,500)
goto(xpos, ypos)
# generate a random color
r = random.random() # returns a number between 0 and 1
g = random.random()
b = random.random()
pencolor(r, g, b)
color(r,g, b)
end_fill()
done()