Programming with python
-
Upload
sarogarage -
Category
Documents
-
view
106 -
download
6
Transcript of Programming with python
![Page 1: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/1.jpg)
{
Introduction To Programming
with
Presenters: Patrick Smyth & Kenneth Ezirim{
![Page 2: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/2.jpg)
What is Python?
![Page 3: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/3.jpg)
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
![Page 4: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/4.jpg)
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 installedIDLE and Python already computers Let’s dive in!!!
![Page 5: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/5.jpg)
Simple ProgramsOpen IDLE and type the following
Basic Math in Python
>>> print “Hello, World!”
>>> 1 + 12
>>> 20 * 15300
>>> 30 / 56
Command Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
** Exponent
>>> 4 – (2 + 4)-2
>>> 2 * “Hello, World!”
>>> #I am a comment, Fear my wrath!!!
Comments, Please
![Page 6: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/6.jpg)
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”
![Page 7: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/7.jpg)
Writing Python code in a fileOpen 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
![Page 8: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/8.jpg)
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
![Page 9: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/9.jpg)
Storing Values in Python: Variables
- Stores values
- Values can be changed
- Let’s write a program that uses variables#Program: variables.py#examples using variablesv = 1print “The value of v now is”, vv = v + 1print “The value of v is itself plus one, which is equal to ”, vu = v * 2print “The value of u equals value in v multiplied by 2,”,print “ which is equal to ”, u
![Page 10: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/10.jpg)
Storing Values in Python: Variables
Variables can also store text, for instance
text1 = “Good Morning”text2 = “Mary Jane”text3 = “Mrs.”print text1, text2sentence = text1 + “ ” + text3 + text2print sentence
Expected Output:Good Morning Mary JaneGood Morning Mrs. Mary Jane
Next we look at conditionals and loops…
![Page 11: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/11.jpg)
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 = 0while a < 10 :
a = a + 1
print a
The ‘while’ Loop:
![Page 12: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/12.jpg)
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."
![Page 13: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/13.jpg)
Conditionals & LoopsBoolean 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
![Page 14: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/14.jpg)
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 = 1if y == 1:
print ‘y still equal to 1’
x = 10if x > 11:
print x
![Page 15: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/15.jpg)
Conditionals & Loops
Conditionals can be used together with a loop. For instance,
print "We will show the even numbers up to 20" n=1while n <= 20:
if n % 2 == 0: print n
n=n+1print "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.
![Page 16: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/16.jpg)
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
![Page 17: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/17.jpg)
Conditionals & Loops
a = 1if a > 5:
print "This shouldn't happen." else:
print "This should happen."
z = 4if z > 70:
print "Something is very wrong" elif z < 7:
print "This is normal"
![Page 18: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/18.jpg)
Conditionals & LoopsGeneral 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.
![Page 19: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/19.jpg)
Conditionals & LoopsGeneral 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 - 1print "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!"
![Page 20: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/20.jpg)
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
![Page 21: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/21.jpg)
Python and FunctionsUsing 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 = 350Note: multiply() is not a real function!!!
![Page 22: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/22.jpg)
Python and FunctionsSo 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.
![Page 23: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/23.jpg)
Python and FunctionsAssuming 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
![Page 24: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/24.jpg)
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}
![Page 25: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/25.jpg)
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’
![Page 26: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/26.jpg)
User-defined Functions#Program: add.py#function to adddef add(a, b):
sum = a+ breturn sum
#program starts herea = 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!
![Page 27: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/27.jpg)
Tuples, Lists and DictionariesTuple
months = ('January','February','March','April','May','June',\'July','August','September','October','November',' December')
List
cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']
Dictionary
phonebook = {'Andrew Parson':8806336, \'Emily Everett':6784346, 'Peter Power':7658344, \'Lewis Lame':1122345}
![Page 28: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/28.jpg)
Tuplesmonths = ('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’
![Page 29: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/29.jpg)
Listscats = ['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]
![Page 30: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/30.jpg)
Dictionariesphonebook = {'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']
![Page 31: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/31.jpg)
Dictionaries: Sample program#define the dictionaryages = {}#add names and ages to the dictionaryages['Sue'] = 23ages['Peter'] = 19ages['Andrew'] = 78ages['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() functionkeys = ages.keys();keys.sort()print keys
values = ages.values()values.sort()print values
![Page 32: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/32.jpg)
The For loopUsed 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
![Page 33: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/33.jpg)
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 + "!"
![Page 34: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/34.jpg)
Operations with ListsConditionals:>>> 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’
![Page 35: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/35.jpg)
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
![Page 36: Programming with python](https://reader031.fdocuments.in/reader031/viewer/2022020713/559277e01a28ab18238b4675/html5/thumbnails/36.jpg)
CreditsSome materials from Sthurlow.com