Download Getting Started with Python

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
GETTING STARTED
WITH PYTHON
Part I
of
Minecraft: Pi Edition
October 17, 2015
2
Outlines
• What is Python?
• How to run a Python program?
• Control constructs
• Using language resources
• Designing your program
• Having fun with graphics
• Setting up for Minecraft mod programming
3
What is Python?
• High level programming language
• Easy to use
• Run from the Bang (aka Shell or console) or a file
• A scripting language
• Loosely typed
• Write once and run on all supporting platforms
• Freely available
4
A brief history of Python
• First created by Guido von Rossum in late 1989
• named after the Brit-com Monty Python's Flying Circus
• Python 2.0 was released on 16 October 2000, with many
major new features including
• a full garbage collector, and
• support for unicode
• Python 3.0 was released on 3 December 2008
• backwards-incompatible (to version 2.5 released in 2006)
• Some features were backported to versions 2.6 (‘08) & 2.7 (‘10)
• Latest version is 3.4
5
How Python is used?
• Python is a general purpose programming language
• Can be used on any modern computer operating system
• Used for processing text, numbers, images, scientific
data, and much more
• It is used daily in the operations like
• Google search engine
• the video sharing web site YouTube
• NASA , and
• the New York Stock Exchange
6
Setting in our labs
• The Python shell (the Bang or console or command line)
• Run your code
directly
• IDLE (Integrated DeveLopment Environment), which
provides
• Multi-window text editor
• Python shell
• Integrated debugger
7
Python Shell: easy to learn and use…
• Arithmetic operations
• 123*456
• Print text strings
• print('Hi, There!')
• Using a variable
• prod=123*456
• print(prod)
• A few more runs
• print('Going…')
• print('Going…')
• print('Going…')
• print('Gone!')
8
IDLE: put code in a file
• Create a new file using File | New Window
• Save the file with a .py extension File | Save (As)
• Create directory as needed
• File name conventions
• Run your program using Run | Run Module
• print('Going…')
• print('Going…')
• print('Going…')
• print('Gone!')
• Write a comment line (starting with a #)
• to be read by the programmers
• not to be interpreted by machine
9
Control construct: using a for loop
• Sometimes an operation needs to be repeated many
times
• Going, going, going …
• Using a loop construct can save you some typing (and
your code elegant)
• Try out this for loop
for x in range(1,4):
print('Going…')
• What does range(1, 4) generate?
• Try out
list(range(1, 4))
10
Control construct: using if statement
• In the for loop
• If it’s one of the first 3 iterations:
print('Going…')
• Else, i.e., it’s the last and 4th time:
print('Gone!')
11
Using resources: dealing with strings
• A string object encloses a sequence of characters
• To assign a string value to a variable, use
book_name = 'Programming the Raspberry Pi'
• Try the following with Python shell
book_name  'Programming the Raspberry Pi'
print(book_name)  Programming the Raspberry Pi
• How to get a part of a string? Try the following:
book_name[1]  'r'
book_name[0]  ‘P'
book_name[0:11]  ‘Programming '
book_name[12:]  'the Raspberry Pi'
12
Using resources: dealing with strings
• String concatenation: just use the + operator
book_name + ' by Simon Monk'
 'Programming the Raspberry Pi by Simon Monk'
• The len() method
• A method is a “function” that a class provides to do something
• The method is provided by the String class
[look up it at http://www.tutorialspoint.com/python/string_len.htm]
• len(book_name)  28
• Other methods: try them out on your own
upper()
lower()
capitalize()
13
Using resources: importing a module
• Features defined in one Python file is organized as a
module
• Many modules need to be imported before its features
can be used: the random module
• Generating a random number using:
import random
dice_value = random.randint(1, 6)
• Printing a number of dice values:
import random
for x in range(1, 10):
dice_value = random.randint(1, 6)
print(dice_value)
14
Using resources: The datetime module
• Example: retrieve today’s date and print date/time parts
import datetime
# Get a date object
today = datetime.date.today()
# General functions
print "Year: %d" % today.year
print "Month: %d" % today.month
print "Day: %d" % today.day
print "Weekday: %d" % today.weekday() # Day of week Monday = 0, Sunday = 6
# ISO Functions
print "ISO Weekday: %d" % today.isoweekday() # Day of week Monday = 1, Sunday = 7
print "ISO Format: %s" % today.isoformat() # YYYY-MM-DD format
print "ISO Calendar: %s" % str(today.isocalendar())
# Tuple of (ISO year, ISO week number, ISO weekday)
# Formatted date
print today.strftime("%Y/%m/%d") #
15
Using resources: a list of values
• One variable (like dice_value) can only hold one value
• If we want to store all the random values, a list can help
dice_values
Use one name
to refer to all
values in list
Use indexes (0based) to refer to
individual values
6
dice_values[0]
4
dice_values[1]
3
dice_values[2]
3
dice_values[3]
2
dice_values[4]
6
dice_values[5]
.
.
.
Declare, initialize, & print
dice_values = [2,3,1]
print (dice_values)
Create an empty list and append
dice_values = []
for x in range(1, 10):
dice_values += _
[random.randint(1, 6)]
.
.
.
Print one value in a line
for x in range(1, len(dice_values)):
print(dice_values[x])
16
Structured design: writing a function
• When your program grows bigger, you may break it down
to units known as functions
• A function can be called repeatedly to do the same thing
again and again
• Some functions can return a value that other parts of your
program can use
Use the keyword
def
keep the
indentation
call the function
17
Structured design: code w/ a function
• Executable code in the box below:
import random
dice_values = []
for x in range(1, 10):
dice_values += [random.randint(1, 6)]
def compare_dice_value(your_value, my_value):
return_str = 'Tie'
if your_value > my_value:
return_str = 'You win'
if your_value < my_value:
return_str = 'I win'
return return_str
print compare_dice_value(dice_values[0], dice_values[len(dice_values)-1])
print compare_dice_value(dice_values[0], dice_values[0])
18
Object-orientation: object and class
• When you program (or system) grows even BIGGER, OO
design will be helpful
• OO is about objects, i.e., software entities that combine
data and operations on the data in one place
• We have used objects in our examples (Python is an OO
language after all), such as strings.
>>> 'lower'.upper()
'LOWER'
Invoking the upper()
method of the str
class
An objects
belongs to a
class, which
can be found
out using…
All values are
objects, even
a number!
>>> 'lower'.__class__
<type 'str'>
>>> [1].__class__
<type 'list'>
>>> 12.34.__class__
<type 'float'>
19
Object-orientation: defining a class
• In addition to using other people’s classes, you may make
some of your own!
• Here is one:
ScaleConverter
Use the keyword
class
Keep indentation
for body of the
class
Create an object
of a certain type
Keep indentation
for body of each
method
Call a method
Use a variable
20
Object-orientation: the ScaleConverter class
• Executable code in the box below:
#05_01_converter
class ScaleConverter:
data
def __init__(self, units_from, units_to, factor):
self.units_from = units_from
self.units_to = units_to
self.factor = factor
def description(self):
return 'Convert ' + self.units_from + ' to ' + self.units_to
operations
def convert(self, value):
return value * self.factor
c1 = ScaleConverter('inches', 'mm', 25)
print(c1.description())
print('converting 2 inches')
print(str(c1.convert(2)) + c1.units_to)
21
Object-orientation: inheritance by subclassing
• Observations tell us objects in real world come in types,
and the types are related: such as types and subtypes
• Design can be made easy if we subclass some class and
the subclass can inherit features from the old super class
• Let’s see how to make a ScaleAndOffsetConverter to
extend the ScaleConverter so that we can convert temp.
Link the
two classes
Method inherited
from super class
Override a
method in
the super
class
22
O-O: the ScaleAndOffsetConverter class
• Executable code in the box below:
class ScaleConverter: #implementation details omitted
class ScaleAndOffsetConverter(ScaleConverter):
def __init__(self, units_from, units_to, factor, offset):
ScaleConverter.__init__(self, units_from, units_to,
factor)
self.offset = offset
def convert(self, value):
return value * self.factor + self.offset
c1 = ScaleConverter('inches', 'mm', 25)
#… …
c2 = ScaleAndOffsetConverter('C', 'F', 1.8, 32)
print(c2.description())
print('converting 20C')
print(str(c2.convert(20)) + c2.units_to)
23
GUI Programming: the tkinter module
• Tkinter is the Python interface to the Tk GUI system
• Tk is written in Tcl (tool command language) and is
available for many platforms
• Tkinter is only available for Python 3.x
• From IDLE
• From Python shell
24
GUI Programming: a Temp. Converter
• A more sophisticate GUI with
• A title in the title bar
• A text field with a caption (label) to take input value: temp. in oC
• A label with a caption (label) to display output value: temp. in oF
• A “Convert” button to trigger the conversion
• The ScaleAndOffsetConverter
class is used to do the calculation
• The two converter classes (super- and sub-classes) are
stored in a converters.py file
• It is known as the converters module in the code as shown on
the next slide
• Code listed on the next slide
25
from tkinter import *
from converters import *
class App:
def __init__(self, master):
self.t_conv = ScaleAndOffsetConverter('C', 'F', 1.8, 32)
frame = Frame(master)
frame.pack()
Label(frame, text='deg C').grid(row=0, column=0)
self.c_var = DoubleVar()
Entry(frame, textvariable=self.c_var).grid(row=0, column=1)
Label(frame, text='deg F').grid(row=1, column=0)
self.result_var = DoubleVar()
Label(frame, textvariable=self.result_var).grid(row=1, column=1)
button = Button(frame, text='Convert', command=self.convert)
button.grid(row=2, columnspan=2)
def convert(self):
c = self.c_var.get()
self.result_var.set(self.t_conv.convert(c))
root = Tk()
root.wm_title('Temp Converter')
app = App(root)
root.mainloop()
26
GUI Programming: try it out yourself
• How to change the interface to another style?
• With deg C and deg F after the in- and output values
• How to change the app into a converter from Fahrenheit
to Celsius?
27
GUI Programming: try out the canvas
• There are all kinds of widgets in the tkinter module
• Here is a simple demo for how to use the canvas:
from tkinter import *
class App:
def __init__(self, master):
canvas = Canvas(master,
width=400,
height=200)
canvas.pack()
canvas.create_rectangle(20, 20,
180, 180,
fill='white')
canvas.create_oval(90, 90, 110,
110, fill='#ff2277')
canvas.create_rectangle(220, 20, 380,
180, fill='white')
canvas.create_oval(290, 90, 310, 110,
fill='#ff2277')
root = Tk()
app = App(root)
root.mainloop()
DIY Project: Try to use
random and define some
class(es) to display all
possible dice throws. Add
a button to roll the dices
again and again.
28
Setting up the Raspberry Pi
• Open a web browser on Raspberry Pi
• Visit http://pi.minecraft.net
• Go to the Download page
• Download the latest version of the game
• Save the file in the /home/pi directory
• Open a fresh terminal and enter the
following command:
• tar –zxvf minecraft-pi-<version>.tar.gz
• Change directory with cd mcpi
• ./minecraft-pi
• a new window should pop up with Minecraft: Pi Edition
running inside
29
What’s Next?
• Programming Python on the Pi
• A “Hello, Minecraft!” demo
• 2D list (or array), how to use it?
• Using Minecraft modules
• Coding and testing a 2D board game
• Putting the board game into Minecraft
To be continued next Friday, October 24.