Download introduction to python programming - itk.ilstu.edu

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
INTRODUCTION TO PYTHON
PROGRAMMING
Xing Fang
School of Information Technology
ABOUT THE LECTURER
• A new faculty member at the School of
IT.
• Received my Ph.D. in CS in May 2016.
• Beijing, China
• Have been programming since high
school.
• Love Python programming.
OBJECTIVES
• Learn basic Python programming
skills.
• Apply the skills to solve some real
world problems.
PROGRAMMING
• A cool way to use a computer
• Programming Languages
–
–
–
–
–
C
C++
Java
Python
….
PROGRAMMING LANGUAGES
• High-level programming languages
• Requires an “assistant” to run on
computers
• The “assistant” is a compiler or an
interpreter (or combined)
FEATURES OF PYTHON
• Python is interpreted.
• Variables are loosely typed. (Do not
need to declare variables.)
• Indentations are forced to group
statements.
• Python can be learnt interactively.
PYTHON VERSIONS
• Python 2.7 and Python 3
• Minor differences
• We will use Python 2.7
GET READY
• Python download
– https://www.python.org/downloads/
• Online Python shell
– https://www.python.org/shell/
PYTHON PROGRAMMING
101
• The print function
– print “Welcome to ISU IT Camp”
– It is a Python statement.
– The statement will display the information
in between the pair of double quotes.
– “Welcome to ISU Summer Camp” is a
string.
– Python statements are case sensitive.
– print is colored in Python shell, so it is a
reserved keyword.
PYTHON
PROGRAMMING 101
• Try the following statements
– print 3
– print “3”
– print 3+3
– print “3+3”
– print “3”+”3”
– print 3*2
– print “3”*2
PYTHON
PROGRAMMING 101
• Variables
– In simplest terms, a variable is just
a box that you can put stuff in. You
can use variables to store all kinds
of stuff, but for now, we are just
going to look at storing numbers in
variables.
PYTHON
PROGRAMMING 101
• Variables and Numbers
– a = 3 #initialization or definition
– a is a variable and its value now is 3
– = is called the assignment operator
– a’s value can be changed at any
time by assigning a new value to it:
a = 1.2
– Variables are also case sensitive.
PYTHON
PROGRAMMING 101
• Variables and Numbers
– a = 3; b = 4
–a=a+b
– print a/b
– a += b
– a *= b
– a /= b
– a += c
PYTHON
PROGRAMMING 101
• Variables and Strings
– Strings can be enclosed in single
quotes or double quotes: “A” or ‘A’
– Strings can be assigned to
variables: a = “Alice”; b = “Bob”
– Alice = “Alice”
– Strings can be concatenated
together: b = “B”+”o”+”b”
– print a+b
PYTHON
PROGRAMMING 101
• Type Casting
– Transform an floating point number
to an integer: int(3.7)
– Transform an integer to a floating
point number: float(2)
– Transform a string to a floating point
number: float(“3.2”)
– What is the result of int(float(“3.2”))?
PYTHON
PROGRAMMING 101
• Lists
– The most useful data structure
– list_1 = [1,2,3,4]
– Lists can hold different data types
together: list_2 = [1,”2”,3.4]
– Lists can be indexed, concatenated,
and sliced
PYTHON
PROGRAMMING 101
• List Indexing
– Indices start at 0
– List_Name[index]
– list_2 = [1,”2”,3.4]
– list_2[0] gives you 1
– list_2[2] gives you 3.4
– list_2[-1] gives you 3.4
PYTHON
PROGRAMMING 101
• List Concatenation
– list_1+list_2
– list_1*2+list_2
• List Slicing
– sub_list_1 = list_1[:2]
– sub_list_1 = list_1[:-1]
– sub_list_1 = list_1[1:2]
PYTHON
PROGRAMMING 101
• Lists are mutable
– list_2 = [1,”2”,3.4]
– list_2[1] = 2
– list_2 = [1,2,3.4]
– list_2[0] = [9,8,7]
PYTHON
PROGRAMMING 101
• List as an object
– A list is an object.
– An object can use the “.” (dot)
operator to call some methods
– list_1.count(1)
– list_1.append(5)
– list_1.remove(5)
– list_1.pop(0)
PYTHON
PROGRAMMING 101
• Making decisions using if
statement
– The logic:
• If something is True, then take the
action.
• Example:
a=3;b=2
if (a>b):
print “a is larger than b”
PYTHON
PROGRAMMING 101
• The if else statement
– The logic
• If something is true, then take action 1.
Otherwise, take action 2.
• Example:
a=3;b=2
if (a>b):
print (“a is larger than b”)
else:
print(“a is less than b”)
SUMMARY FOR DAY 1
•
•
•
•
•
Python is interpreted.
Python 2.7
Variables, numbers, strings.
Lists
If/If-else statements
PYTHON
PROGRAMMING 101
• for loop
– People use loops to execute a
series of repeatable actions
– for loop involves using the keyword,
for
– Example:
list_1 = [1,2,3,4]
for number in list_1:
print number
PYTHON
PROGRAMMING 101
• for loop
– Another way to do it:
for index in range(len(list_1)):
print list_1[index]
Another example:
square = []
for x in range(10):
square.append(x**2)
PYTHON
PROGRAMMING 101
• Algorithms
– a process or set of rules to be
followed in calculations or other
problem-solving operations,
especially by a computer.
PYTHON
PROGRAMMING 101
• Python scripts
• File extension is .py
• After the execution, whatever
defined in the script will be still
there to use.
PYTHON
PROGRAMMING 101
• Problem solving #1
– Deciding the root conditions of
quadratic equations
PYTHON
PROGRAMMING 101
• Quadratic equations
PYTHON
PROGRAMMING 101
PYTHON
PROGRAMMING 101
• Problem solving #1
The root conditions of quadratic equations
• The algorithm:
1. Get the value of a, b, and c.
2. See if a is equal to zero, if it is, then
return. Otherwise, continue to next
step.
3. Compute delta.
4. Making decisions: If delta is larger
than or equal to zero, if delta is a
negative number.
PYTHON
PROGRAMMING 101
• Problem solving #2
Find the maximum number of a list
–[3,2,1,5,4]
–Computational thinking
–The Algorithm
• Hint: You want to use the if statement
and the for loop
PYTHON
PROGRAMMING 101
• Problem solving #2
Find the maximum number of a list
• The algorithm
1. Initialize a variable with a
sufficiently small value.
2. Start looping through the list, if the
value of the list is larger than the
value of the variable, assign the
value of the list to the variable.
PYTHON
PROGRAMMING 101
• Problem solving #2
Find the minimum number of a list
• The algorithm
PYTHON
PROGRAMMING 101
• while loop
a=0
while (a < 3):
print (“Welcome to ISU.”)
a += 1
PYTHON
PROGRAMMING 101
• The Numerical Python Package
(Numpy)
• For scientific computing
• http://www.numpy.org/
PYTHON
PROGRAMMING 101
• Import the package
– import numpy
– import numpy as np
• The random family
– np.random.randint(0,11,10)
PYTHON
PROGRAMMING 101
• Practice
– Find the maximum number of a
randomly generated list that has
1000 integers
PYTHON
PROGRAMMING 101
• Numpy.random.choice
– np.random.choice([1,2,3,4],3)
– np.random.choice([1,2,3,4],3,replace=False)
• Numpy.random.shuffle
– np.random.shuffle([1,2,3,4])
PYTHON
PROGRAMMING 101
• Problem solving #3
• Rules:
– Fill out the blanks using numbers from 1 to 9
– The numbers can be used more than once
– Follow the sequence and the arithmetic precedence
PYTHON
PROGRAMMING 101
• Solution
– Try to pick up 9 random numbers
and fit each of them in a blank
– If the computation result matches,
then return the 9 numbers as the
solution
PYTHON
PROGRAMMING 101
• Dictionary
– Dictionaries are sometimes found in
other languages as “associative
memories” or “associative arrays”.
– Unlike sequences, which are
indexed by a range of numbers,
dictionaries are indexed by keys,
which can be strings and numbers.
PYTHON
PROGRAMMING 101
• Dictionary
– Examples:
– d = {}
– d = {“apple”:1,”grape”:5,”orange”:7}
– key:value
– Keys are unique
– d is an object
PYTHON
PROGRAMMING 101
• Dictionary
– return a list of keys
• d.keys()
– return a list of values
• d.values()
– loop through a dictionary
d = {1:2,3:4,5:6}
for k,v in d.iteritems():
print k,v
PYTHON
PROGRAMMING 101
• File I/O
– Read from a file
– f = open(“C:\\Users\\xfang13\\Desktop\\infor.txt”)
– f is a file object.
– for line in f:
print line
– f.close() it is always a good behavior to close the
file once you have done with it.
PYTHON
PROGRAMMING 101
• File I/O
– Read from a file
– with open(“C:\\Users\\xfang13\\Desktop\\infor.txt”) as f:
for line in f:
print line
– The file will be closed automatically,
once the lines are printed.
PYTHON
PROGRAMMING 101
• File I/O
– Write to a file
– with open(“C:\\Users\\xfang13\\Desktop\\infor.txt”,”w”) as
f:
f.write(“Xing Fang\n”)
f.write(“Assistant Professor\n”)
f.write(“School of IT\n”)
f.write(“Illinois State University”)
PYTHON
PROGRAMMING 101
• Simple file parsing
– with open(“C:\\Users\\xfang13\\Desktop\\infor.txt”) as f:
for line in f:
print line
– There are some annoying characters, which we
want to remove.
– with open(“C:\\Users\\xfang13\\Desktop\\infor.txt”) as f:
for line in f:
line = line.strip(‘\n.’)
print line
PYTHON
PROGRAMMING 101
• Simple file parsing
– Let’s further extract the words.
– with open(“C:\\Users\\xfang13\\Desktop\\infor.txt”) as f:
for line in f:
line = line.strip(‘\n.’)
print line.split(“ ”)
PYTHON
PROGRAMMING 101
• Counting the appearance of a
word
– We will use a dictionary to save the information