3. What is Python?
• Programming Language
- Tells computer what to do
• Interpreted Language
- Different from Compiled Languages
- Executes Program Line by Line
- Turns code into 0s and 1s for
4. Requirements for Python
• To program and run your Python code
- Need a Python Interpreter
- Download and Install IDLE
- Check if Python is installed using command “python -V”
- Should show the version of Python installed
IDLE and Python
already computers
Let’s dive in!!!
5. Simple Programs
Open IDLE and type the following
>>> print “Hello, World!”
Comments, Please
>>> #I am a comment, Fear my wrath!!!
Basic Math in Python
>>> 1 + 1
2
>>> 20 * 15
300
>>> 30 / 5
6
Command Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
** Exponent
>>> 4 – (2 + 4)
-2
>>> 2 * “Hello, World!”
6. Writing Python code in a file
- Very easy to create
- simple text document
- you can open them in notepad
- save with a filename and an extension “.py”
7. Writing Python code in a file
Open notepad and type the following:
#Program: maryjane.py
#Simple program
print “Mary Jane had a small cat”
print "it's fleece was white as snow;"
print "and everywhere that Mary went",
print "her lamb was sure to go.”
Save file as maryjane.py
8. Writing Python code in a file
Using the IDLE environment
- File > Open > Search for maryjane.py
- Run > Run Module to run program
Note:
- Comment was not printed
- 3rd and 4th lines were merged
- maryjane.py can also be run from the
command line
>>> python maryjane.py
9. Storing Values in Python: Variables
- Stores values
- Values can be changed
- Let’s write a program that uses variables
#Program: variables.py
#examples using variables
v = 1
print “The value of v now is”, v
v = v + 1
print “The value of v is itself plus one, which is equal to ”, v
u = v * 2
print “The value of u equals value in v multiplied by 2,”,
print “ which is equal to ”, u
10. Storing Values in Python: Variables
Variables can also store text, for instance
text1 = “Good Morning”
text2 = “Mary Jane”
text3 = “Mrs.”
print text1, text2
sentence = text1 + “ ” + text3 + text2
print sentence
Expected Output:
Good Morning Mary Jane
Good Morning Mrs. Mary Jane
Next we look at conditionals and loops…
11. Conditionals & Loops
• You need a program to do something a number of times
• For instance, print a value 20 times?
'a' now equals 0
As long as 'a' is less than 10, do the following:
Make 'a' one larger than what it already is.
print on-screen what 'a' is now worth.
a = 0
while a < 10 :
a = a + 1
print a
The ‘while’ Loop:
12. Conditionals & Loops
while {condition that the loop continues}:
{what to do in the loop}
{have it indented, usually four spaces or tab}
{the code here is not looped because it isn't indented}
#EXAMPLE
#Type this in, see what it does
x = 10
while x != 0:
print x
x = x - 1
print "wow, we've counted x down, and now it equals", x
print "And now the loop has ended."
13. Conditionals & Loops
Boolean Expressions (Boolean... what?!?)
- what you type in the area marked {conditions that the loop continues}
Expression Function
< less than
<= less that or equal to
> greater than
>= greater than or equal to
!= not equal to
<> not equal to (alternate)
== equal to
Examples
• My age < the age of the person sitting opposite to me
• Cash in my wallet == 100
• Cost of an iPhone is >= 660
14. Conditionals & Loops
• Conditional – a section of code that is executed if certain
conditions are met
• Different from While loop – run only once!
• Most common is the IF - statement
Syntax:
if {conditions to be met}:
{do this}
{and this}
{and this}
{but this happens regardless}
{because it isn't indented}
Example:
y = 1
if y == 1:
print ‘y still equal to 1’
x = 10
if x > 11:
print x
15. Conditionals & Loops
Conditionals can be used together with a loop. For instance,
print "We will show the even numbers up to 20"
n=1
while n <= 20:
if n % 2 == 0:
print n
n=n+1
print "there, done."
Note:
n % 2 implies the remainder after the value in n is divided
wholly by 2. The expression is read as ‘n modulus 2’. For
instance, 4 % 2 = 0 and 7 % 2 = 1.
16. Conditionals & Loops
- When it Ain't True
Using 'else' and 'elif’ when IF conditions fails
- ‘else’ simply tells the computer what to do if the
conditions of ‘if’ are not met
- ‘elif’ same as ‘else if’
- ‘elif’ will do what is under it if the conditions are
met
17. Conditionals & Loops
a = 1
if a > 5:
print "This shouldn't happen."
else:
print "This should happen."
z = 4
if z > 70:
print "Something is very wrong"
elif z < 7:
print "This is normal"
18. Conditionals & Loops
General Syntax:
if {conditions}:
{run this code}
elif {conditions}:
{run this code}
elif {conditions}:
{run this code}
else:
{run this code}
- You can have as many elif statements as you need
- Anywhere from zero to the sky.
- You can have at most one else statement
- And only after all other ifs and elifs.
19. Conditionals & Loops
General Example:
a = 10
while a > 0:
print a
if a > 5:
print "Big number!"
elif a % 2 != 0:
print "This is an odd number"
print "It isn't greater than five, either"
else:
print "this number isn't greater than 5"
print "nor is it odd"
print "feeling special?”
a = a - 1
print "we just made 'a' one less than what it was!"
print "and unless a is not greater than 0, we'll do the loop again
print "well, it seems as if 'a' is now no bigger than 0!"
20. Python and Functions
Writing interactive program involves:
- User input
- Function to process user input
- Function Output
What is a Function?
- self-contained code
- perform a specific task
- can be incorporated in larger programs
- can be used more than once
21. Python and Functions
Using functions
- Python have predefined functions
- give an input and get an output
- calling a function
Function_Name(list of parameters)
For instance,
a = multiply(70)
Computer sees
a = 350
Note: multiply() is not a real function!!!
22. Python and Functions
So what about a real function?
Let’s try a function called raw_input()
#Program: echo.py
#this line makes ‘in' equal to whatever you type in
in = raw_input("Type in something, and it will echoed on screen:")
# this line prints what ‘in' is now worth
print in
The function raw_input asks the user to type in
something. It then turns it into a string of text.
23. Python and Functions
Assuming you typed “hello”, the computer will see the
program as:
in = “hello”
print “hello”
Note:
- Variable ‘in’ is stored value
- Computer does not see ‘in’ as in
- Functions are similar: input and output
24. User-defined Functions
- Decide what your function does
- Save time looking other people’s functions
- Use in subsequent programs
Syntax:
def function_name(parameter_1,parameter_2):
{this is the code in the function}
{more code}
{more code}
return {value to return to the main program}
{this code isn't in the function}
{because it isn't indented}
25. User-defined Functions
# Below is the function
def hello():
print “HELLO"
return 1234
# And here is the function being used
print hello()
So what happened?
1. When 'def hello()' was run, a function called 'hello' was created
2. When the line 'print hello()' was run, the function 'hello' was
executed
3. The function 'hello' printed ‘HELLO’ onscreen, then returned the
number '1234' back to the main program
4. The main program now sees the line as 'print 1234' and as a result,
printed '1234’
26. User-defined Functions
#Program: add.py
#function to add
def add(a, b):
sum = a+ b
return sum
#program starts here
a = input(“Add this: ”)
b = input(“ to this: ”)
print a , “+”, b, “=”, add(a,b)
#program ends here
print a , “+”, b, “=”, add(input(“Add this: ”), input(“ to this: ”))
{
Function input returns what you typed in, to the main program.
But this time, it returns a type that is a number, not a string!
28. Tuples
months = ('January','February','March','April','May','June',
'July','August','September','October','November',' December')
- Used for coordinate pairs, employee records in database
- Python organizes the values by indexing
>>> months[0]
‘January’
- Create tuple from command line
>>> t = 12345, 54321, ‘hello!’
>>> t
>>> (12345, 54321, ‘hello’)
- Determine size of tuple
>>> len(t)
3
- Packing and Unpacking tuple
>>> x , y, z = t
>>> z
‘hello’
29. Lists
cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']
Print size of list: print len(cats)
Print an element of a list: print cats[2]
Print a range of a list: print cats[0:2]
Add a value to the list: cats.append(‘Catherine’)
Delete an element of a list: del cats[1]
30. Dictionaries
phonebook = {'Andrew Parson':8806336, 'Emily Everett':6784346,
'Peter Power':7658344, 'Lewis Lame':1122345}
Access a person’s phone number:
>>> phonebook[‘Andrew Parson’]
8806336
Change a person’s phone number:
>>> phonebook[‘Lewis Lame’] = 5432211
Add a person to the phonebook
>>> phonebook['Gingerbread Man'] = 1234567
Delete a person from phonebook
>>> del phonebook['Andrew Parson']
31. Dictionaries: Sample program
#define the dictionary
ages = {}
#add names and ages to the dictionary
ages['Sue'] = 23
ages['Peter'] = 19
ages['Andrew'] = 78
ages['Karren'] = 45
#function keys() - is function returns a list of the names of the keys.
print "The following people are in the dictionary:”, ages.keys()
#Use the values() function to get a list of values in dictionary.
print "People are aged the following:", ages.values()
#You can sort lists, with the sort() function
keys = ages.keys();
keys.sort()
print keys
values = ages.values()
values.sort()
print values
32. The For loop
Used to iterate through values in a list
# Example 'for' loop
# First, create a list to loop through:
newList = [45, 'eat me', 90210, "The day has come,
the walrus said, to speak of many things", -67]
# create the loop:
# Go through newList, and sequentially puts each list item
# into the variable value, and runs the loop
for value in newList:
print value
33. The For loop
#cheerleading program
word = raw_input("Who do you go for? ")
for letter in word:
call = "Gimme a " + letter + "!"
print call
print letter + "!"
print "What does that spell?"
print word + "!"
34. Operations with Lists
Conditionals:
>>> sent = ['No', 'good', 'fish', 'goes', 'anywhere', 'without', 'a', 'porpoise', '.']
>>> all(len(w) > 4 for w in sent)
False
>>> any(len(w) > 4 for w in sent)
True
Slicing:
>>> raw = ‘Man in the mirror’
>>> raw[:3]
Man
>>> raw[-3:]
ror
>>> raw[3:]
‘ in the mirror’
35. Importing Modules
- Import modules using the keyword ‘import’
- can be done via command line as well as in text file mode
Example:
>>> import random
>>> random.randint(0,10)
3