29
GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

Embed Size (px)

Citation preview

Page 1: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

GETTING STARTED WITH PYTHONPart Iof

Minecraft: Pi Edition

October 17, 2015

Page 2: 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

Page 3: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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

Page 4: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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

Page 5: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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

Page 6: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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

Page 7: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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!')

Page 8: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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

Page 9: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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 outlist(range(1, 4))

Page 10: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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!')

Page 11: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

11

Using resources: dealing with strings

• A string object encloses a sequence of characters• To assign a string value to a variable, usebook_name = 'Programming the Raspberry Pi'

• Try the following with Python shellbook_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'

Page 12: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

12

Using resources: dealing with strings

• String concatenation: just use the + operatorbook_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 ownupper()lower()capitalize()

Page 13: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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 randomdice_value = random.randint(1, 6)

• Printing a number of dice values:import randomfor x in range(1, 10): dice_value = random.randint(1, 6) print(dice_value)

Page 14: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

14

Using resources: The datetime module

• Example: retrieve today’s date and print date/time partsimport datetime # Get a date objecttoday = datetime.date.today() # General functions print "Year: %d" % today.yearprint "Month: %d" % today.monthprint "Day: %d" % today.dayprint "Weekday: %d" % today.weekday() # Day of week Monday = 0, Sunday = 6 # ISO Functionsprint "ISO Weekday: %d" % today.isoweekday() # Day of week Monday = 1, Sunday = 7print "ISO Format: %s" % today.isoformat() # YYYY-MM-DD formatprint "ISO Calendar: %s" % str(today.isocalendar()) # Tuple of (ISO year, ISO week number, ISO weekday) # Formatted dateprint today.strftime("%Y/%m/%d") #

Page 15: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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

6

4

3

3

2

6

dice_values dice_values[0]

dice_values[1]

dice_values[2]

dice_values[3]

dice_values[4]

dice_values[5]

.

.

.

.

.

.

Use one name to refer to all values in list

Use indexes (0-based) to refer to individual values

dice_values = [2,3,1]print (dice_values)

dice_values = []for x in range(1, 10): dice_values += _[random.randint(1, 6)]

Declare, initialize, & print

Create an empty list and append

for x in range(1, len(dice_values)): print(dice_values[x])

Print one value in a line

Page 16: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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

Page 17: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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])

Page 18: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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' >>> 'lower'.__class__

<type 'str'>>>> [1].__class__<type 'list'>>>> 12.34.__class__<type 'float'>

Invoking the upper() method of the str class

All values are objects, even a number!

An objects belongs to a class, which can be found out using…

Page 19: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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

Keep indentation for body of each method

Call a methodUse a variable

Create an object of a certain type

Page 20: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

20

Object-orientation: the ScaleConverter class

• Executable code in the box below:#05_01_converterclass ScaleConverter:

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

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)

data

operations

Page 21: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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

Override a method in the super class

Method inherited from super class

Page 22: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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)

Page 23: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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

Page 24: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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 ScaleAndOffsetConverterclass 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

Page 25: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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()

Page 26: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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?

Page 27: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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.

Page 28: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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

Page 29: GETTING STARTED WITH PYTHON Part I of Minecraft: Pi Edition October 17, 2015

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.