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

Slides:



Advertisements
Similar presentations
PHP I.
Advertisements

Noadswood Science,  To know how to use Python to produce windows and colours along with specified co-ordinates Sunday, April 12, 2015.
MINECRAFT MOD PROGRAMMING Part III of Minecraft: Pi Edition October 31, 2015.
Intro to Python Welcome to the Wonderful world of GIS programing!
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
Chapter 2 Writing Simple Programs
1 An Introduction to Visual Basic Objectives Explain the history of programming languages Define the terminology used in object-oriented programming.
PYTHON: LESSON 1 Catherine and Annie. WHAT IS PYTHON ANYWAY?  Python is a programming language.  But what’s a programming language?  It’s a language.
Fundamentals of Python: From First Programs Through Data Structures
Game Programming © Wiley Publishing All Rights Reserved. The L Line The Express Line to Learning L Line L.
Computer Science 111 Fundamentals of Programming I User Interfaces Introduction to GUI programming.
Startup – Chapter 1.
Python Programming Fundamentals
Fundamentals of Python: First Programs
CS346 - Javascript 1, 21 Module 1 Introduction to JavaScript CS346.
Microsoft Visual Basic 2005: Reloaded Second Edition
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 1 Computers and Programs.
Python 0 Some material adapted from Upenn cmpe391 slides and other sources.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Python From the book “Think Python”
If statements while loop for loop
Guide to Programming with Python Chapter One Getting Started: The Game Over Program.
PYTHON GUI PROGRAMMING
Python – May 11 Briefing Course overview Introduction to the language Lab.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Session 20 Graphical User Interface (GUI)
Intro to Python Adriane Huber Debbie Bartlett Python Lab #1Python Lab #1 1.
Lesson 4 Using Variables in Python – Creating a Simple ChatBot Program.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
You Need an Interpreter!. Closing the GAP Thus far, we’ve been struggling to speak to computers in “their” language, maybe its time we spoke to them in.
ECET – Dynamic Programming with Python Spring 2013 Lecture L1 – Introduction to Python Page 1 Welcome! This is Professor Jai P. Agrawal. I will walk.
9-Nov-97Tri-Ada '971 TASH An Alternative to the Windows API TRI-Ada ‘97 Terry J. Westley
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
A Python Tour: Just a Brief Introduction "The only way to learn a new programming language is by writing programs in it." -- B. Kernighan and D. Ritchie.
8 th Semester, Batch 2009 Department Of Computer Science SSUET.
Introduction to Programming Python Lab 5: Strings and Output 05 February PythonLab5 lecture slides.ppt Ping Brennan
1. COMPUTERS AND PROGRAMS Rocky K. C. Chang September 6, 2015 (Adapted from John Zelle’s slides)
See Winter 2016CISC101 - Prof. McLeod1.
Introduction to Programming Python Lab 8: Loops 26 February PythonLab8 lecture slides.ppt Ping Brennan
PROGRAMMING USING PYTHON LANGUAGE ASSIGNMENT 1. INSTALLATION OF RASPBERRY NOOB First prepare the SD card provided in the kit by loading an Operating System.
IST 210: PHP Basics IST 210: Organization of Data IST2101.
Getting Started With Python Brendan Routledge
Introducing Python 3 Introduction to Python. Introduction to Python L1 Introducing Python 3 Learning Objectives Know what Python is and some of the applications.
Computer Science 112 Fundamentals of Programming II Data Fields for I/O and Message Boxes for Error Recovery.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Part 1 Learning Objectives To understand that variables are a temporary named location to store data and that programmers work with different data types.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
PROBLEM SOLVING WARM-UP Fill in the spaces using any operation to solve the following (!, (), -/+,÷,×): = 6.
© 2010 Robert K. Moniot1 Chapter 6 Introduction to JavaScript.
CST 1101 Problem Solving Using Computers
A Python Tour: Just a Brief Introduction
Introduction to Programming
Python: Experiencing IDLE, writing simple programs
Topics Introduction to Repetition Structures
Introduction to Programming
Chapter 2 First Java Programs
Engineering Innovation Center
Do you know this browser?...
Introduction to Python
Introduction to Programming
Introduction to Programming
12th Computer Science – Unit 5
Introduction to Programming
General Computer Science for Engineers CISC 106 Lecture 03
Introduction to Programming
L L Line CSE 420 Computer Games Lecture #3 Introduction to Python.
CMPT 120 Lecture 10 – Unit 2 – Cryptography and Encryption –
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

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

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 2

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 3

A brief history of Python First created by Guido von Rossum in late 1989Guido von Rossum 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, andgarbage collector support for unicodeunicode 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 4

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 Google the video sharing web site YouTubeYouTube NASA, and NASA the New York Stock ExchangeNew York Stock Exchange 5

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 6

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

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('Gone!') Write a comment line (starting with a #) to be read by the programmers not to be interpreted by machine 8

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

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 4 th time: print('Gone!') 10

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' 11

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 len(book_name)  28 Other methods: try them out on your own upper() lower() capitalize() 12

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

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") # 14

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

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 16

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

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__ >>> [1].__class__ >>> __class__ 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… 18

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 method Use a variable Create an object of a certain type 19

Object-orientation: the ScaleConverter class Executable code in the box below: #05_01_converter class 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 20

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 21

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

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 23

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 o C A label with a caption (label) to display output value: temp. in o F 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 24

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

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? 26

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. 27

Setting up the Raspberry Pi Open a web browser on Raspberry Pi Visit 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-.tar.gz Change directory with cd mcpi./minecraft-pi a new window should pop up with Minecraft: Pi Edition running inside 28

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 29 To be continued next Friday, October 24.