├── .gitignore ├── Ch 03 Python Program Structure ├── EG3-01 Throw a single die.py ├── EG3-02 Deep Thought.py ├── EG3-03 Egg timer.py ├── EG3-04 hello world.py ├── EG3-05 housemartins.py ├── EG3-06 Ding.py ├── Housemartins.jpg ├── ding.wav ├── egg_timer_background.png └── snaps.py ├── Ch 04 Working with Data in Python ├── EG4-01 Self Timer.py ├── EG4-02 User Configurable Egg Timer.py ├── EG4-03 Ultra-precise Egg Timer.py ├── EG4-04 Pizza Order Calculator.py ├── EG4-05 Seattle Temperature.py ├── EG4-06 Seattle Weather.py └── snaps.py ├── Ch 05 Making Decisions in Programs ├── EG5-01 OneHandedClock.py ├── EG5-02 Simple Alarm Clock.py ├── EG5-03 Siren Alarm Clock.py ├── EG5-04 Alarm clock with time display.py ├── EG5-05 Simple Alarm Clock with else.py ├── EG5-06 Broken Greeter.py ├── EG5-07 Upper case Greeter.py ├── EG5-08 Greeter with password.py ├── EG5-09 Greeter with outer else.py ├── EG5-10 Ride Selector Start.py ├── EG5-11 Complete Ride Selector.py ├── EG5-12 Snaps get_string function.py ├── EG5-13 Theme Park Snaps Display.py ├── EG5-14 Weather helper.py ├── siren.wav ├── snaps.py └── themepark.png ├── Ch 06 Loops ├── EG6-01 Loop with boolean flag.py ├── EG6-02 Loop with counter.py ├── EG6-04 Handing invalid text.py ├── EG6-05 Catching multiple exceptions.py ├── EG6-06 Using break to exit loops.py ├── EG6-07 Loop with condition early ending.py ├── EG6-08 Ignore Ride 3.py ├── EG6-09 Times Table Tutor.py ├── EG6-10 Name printer.py ├── EG6-11 Times Table Loops.py ├── EG6-12 Code Analysis 1.py ├── EG6-13 Code Analysis 2.py ├── EG6-14 Code Analysis 3.py ├── EG6-15 Code Analysis 4.py ├── EG6-18 Digital Clock.py └── snaps.py ├── Ch 07 Methods ├── EG7-01 Pathfinder.py ├── EG7-02 Times Table.py ├── EG7-03 Safer Times Table.py ├── EG7-04 Two Parameter Times Table.py ├── EG7-05 Keyword Arguments.py ├── EG7-06 Default parameters.py ├── EG7-07 Parameters as values.py ├── EG7-08 get_value investigation 1.py ├── EG7-09 get_value investigation 2.py ├── EG7-10 complete get_value.py ├── EG7-11 Local Variables.py ├── EG7-12 Reading Global Variables.py ├── EG7-13 Shadowing Global Variables.py ├── EG7-14 Storing Global Variables.py ├── EG7-15 Using the input module.py ├── EG7-16 Investigating the debugger.py ├── read_text.py ├── snaps.py └── teletypePrinter.py ├── Ch 08 Collections ├── BTCInput.py ├── EG8-01 Finding the largest sales.py ├── EG8-02 Read and Display.py ├── EG8-03 Read and Display loop.py ├── EG8-04 Functions.py ├── EG8-05 Functions and Menu.py ├── EG8-06 Functions and Menu Elif.py ├── EG8-07 Bubble sort first pass.py ├── EG8-08 Bubble sort multiple passes.py ├── EG8-09 Efficient Bubble Sort.py ├── EG8-10 Sort low to high.py ├── EG8-11 High and low.py ├── EG8-12 Total Sales.py ├── EG8-13 Average Sales.py ├── EG8-14 Complete Program.py ├── EG8-15 Load and Save.py ├── EG8-16 File Output.py ├── EG8-17 Sales save.py ├── EG8-18 File Input.py ├── EG8-19 Complete file read.py ├── EG8-20 Sales load.py ├── EG8-21 Sales load using with.py ├── EG8-22 Tables of sales data.py ├── EG8-23 Day Name If.py ├── EG8-24 Day Name List.py ├── EG8-25 Day Name Tuple.py ├── EG8-26 Pirate Treasure Tuple.py ├── EG8-27 Pirate Treasure Tuple Function.py └── snaps.py ├── Ch 09 Using classes to store data ├── BTCInput.py ├── EG9-01 Tiny Contacts Prototype.py ├── EG9-02 Tiny Contacts Three Lists.py ├── EG9-03 Tiny Contacts Quick Search.py ├── EG9-04 Tiny Contacts Class.py ├── EG9-05 Tiny Contacts with Editor.py ├── EG9-06 Tiny Contacts with Load and Save.py ├── EG9-07 Tiny Contacts with constructor.py ├── EG9-08 Pirate Treasure Dictionary.py ├── EG9-09 Alarm access control.py └── snaps.py ├── Ch 10 Using classes to create active objects ├── BTCInput.py ├── BTCInput.pyc ├── EG10-01 Time Tracker.py ├── EG10-02 Time Tracker with method attributes.py ├── EG10-03 Time Tracker with class variables.py ├── EG10-04 Time Tracker with static method.py ├── EG10-05 Time Tracker with status reporting.py ├── EG10-06 Time Tracker with exception.py ├── EG10-07 Time Tracker with exception handler.py ├── EG10-08 Time Tracker with protected attributes.py ├── EG10-09 Time Tracker with properties.py ├── EG10-10 Time Tracker with properties and exception handlers.py ├── EG10-11 Time Tracker with Billing Amount.py ├── EG10-12 Time Tracker with version management.py ├── EG10-13 Time Tracker with version managed billing.py ├── EG10-14 Time Tracker with string method.py ├── EG10-15 Time Tracker with formatted string.py ├── EG10-16 Time Tracker with session history.py ├── EG10-17 Play notes.py ├── EG10-18 Twinkle Twinkle.py ├── EG10-19 Twinkle Twinkle Tuples.py ├── EG10-20 Twinkle Twinkle classes.py ├── EG10-21 Twinkle Twinkle printer.py ├── MusicNotes │ ├── 0.wav │ ├── 1.wav │ ├── 10.wav │ ├── 11.wav │ ├── 12.wav │ ├── 2.wav │ ├── 3.wav │ ├── 4.wav │ ├── 5.wav │ ├── 6.wav │ ├── 7.wav │ ├── 8.wav │ └── 9.wav ├── contacts.pickle ├── pcontacts.pickle ├── snaps.py ├── vsncontacts.pickle └── xcontacts.pickle ├── Ch 11 Object Based Solution Design ├── BTCInput.py ├── EG11-01 Separate classes.py ├── EG11-02 Stock Item class failed.py ├── EG11-03 Stock Item class super init.py ├── EG11-04 Stock Items with str.py ├── EG11-05 Stock Items with version.py ├── EG11-06 Instrumented Stock Items.py ├── EG11-07 Creating Stock Items.py ├── EG11-08 Adding to stock levels.py ├── EG11-09 Selling stock.py ├── EG11-10 FashionShop template.py ├── EG11-11 FashionShop class.py ├── EG11-12 Complete Fashion Shop.py ├── EG11-13 Fashion Shop with Tags.py ├── EG11-14 Tag only fashion shop.py ├── FashionShop.pickle └── snaps.py ├── Ch 12 Python applications ├── BTCInput.py ├── EG12-01 Simple Function References.py ├── EG12-02 Invalid Function References.py ├── EG12-03 Robot Dancer.py ├── EG12-04 Lamdba Example.py ├── EG12-05 Test contact generator.py ├── EG12-06 Aribitrary Arguments.py ├── EG12-07 Using a BTCImport function.py ├── EG12-08 FashionShopApp │ ├── FashionShopShellUI.py │ ├── ShellUI │ │ ├── BTCInput.py │ │ ├── FashionShopShell.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ ├── BTCInput.cpython-36.pyc │ │ │ ├── FashionShopShell.cpython-36.pyc │ │ │ └── __init__.cpython-36.pyc │ ├── Storage │ │ ├── FashionShop.py │ │ ├── StockItem.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ ├── FashionShop.cpython-36.pyc │ │ │ ├── StockItem.cpython-36.pyc │ │ │ └── __init__.cpython-36.pyc │ ├── __pycache__ │ │ └── FashionShopShellUI.cpython-36.pyc │ └── fashionshop.pickle ├── EG12-09 TestFashionShopApp │ ├── FashionShopShellUI.py │ ├── RunTests.py │ ├── ShellUI │ │ ├── BTCInput.py │ │ ├── FashionShopShell.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ ├── BTCInput.cpython-36.pyc │ │ │ ├── FashionShopShell.cpython-36.pyc │ │ │ └── __init__.cpython-36.pyc │ ├── Storage │ │ ├── FashionShop.py │ │ ├── StockItem.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ ├── FashionShop.cpython-36.pyc │ │ │ ├── StockItem.cpython-36.pyc │ │ │ └── __init__.cpython-36.pyc │ ├── Tests │ │ ├── Tests.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ ├── Tests.cpython-36.pyc │ │ │ └── __init__.cpython-36.pyc │ └── fashionshop.pickle ├── EG12-10 TestFashionShopApp Doc │ ├── FashionShopShellUI.py │ ├── RunTests.py │ ├── ShellUI │ │ ├── BTCInput.py │ │ ├── FashionShopShell.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ ├── BTCInput.cpython-36.pyc │ │ │ ├── FashionShopShell.cpython-36.pyc │ │ │ └── __init__.cpython-36.pyc │ ├── Storage │ │ ├── FashionShop.py │ │ ├── StockItem.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ ├── FashionShop.cpython-36.pyc │ │ │ ├── StockItem.cpython-36.pyc │ │ │ └── __init__.cpython-36.pyc │ ├── Tests │ │ ├── Tests.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ ├── Tests.cpython-36.pyc │ │ │ └── __init__.cpython-36.pyc │ ├── __pycache__ │ │ ├── FashionShopShellUI.cpython-36.pyc │ │ └── RunTests.cpython-36.pyc │ └── fashionshop.pickle ├── people.pickle └── test.pickle ├── Ch 13 Python and Graphical User Interfaces ├── EG13-01 First Adding machine.py ├── EG13-02 Exception handler with messages.py ├── EG13-03 Adder with sensible messages.py ├── EG13-04 Adder with messagebox.py ├── EG13-05 TemperatureConverter Starter │ ├── .vscode │ │ └── launch.json │ └── TemperatureConverter.py ├── EG13-06 TemperatureConverter Complete │ ├── .vscode │ │ └── launch.json │ └── TemperatureConverter.py ├── EG13-07 Drawing program │ ├── .vscode │ │ └── launch.json │ └── Drawing.py ├── EG13-08 StockEditDemo │ ├── .vscode │ │ └── launch.json │ ├── StockItem.py │ ├── StockItemEditDemo.py │ ├── StockItemEditor.py │ └── __pycache__ │ │ ├── StockItem.cpython-36.pyc │ │ └── StockItemEditor.cpython-36.pyc ├── EG13-09 StockSelectDemo │ ├── .vscode │ │ └── launch.json │ ├── StockItem.py │ ├── StockItemSelector.py │ ├── StockItemSelectorDemo.py │ └── __pycache__ │ │ ├── StockItem.cpython-36.pyc │ │ └── StockItemSelector.cpython-36.pyc └── EG13-10 FashionShop │ ├── .vscode │ ├── launch (1).json │ ├── launch.json │ ├── settings (1).json │ └── settings.json │ ├── FashionShopGUIApp.py │ ├── FashionShopGUIapp.pyw │ ├── FashionShopShellUIApp.py │ ├── GUI │ ├── FashionShopGUI (1).py │ ├── FashionShopGUI.py │ ├── StockItemEditor (1).py │ ├── StockItemEditor.py │ ├── StockItemSelector (1).py │ ├── StockItemSelector.py │ ├── __init__ (1).py │ ├── __init__.py │ └── __pycache__ │ │ ├── FashionShopGUI.cpython-36 (1).pyc │ │ ├── FashionShopGUI.cpython-36.pyc │ │ ├── StockItemEditor.cpython-36 (1).pyc │ │ ├── StockItemEditor.cpython-36.pyc │ │ ├── StockItemSelector.cpython-36 (1).pyc │ │ ├── StockItemSelector.cpython-36.pyc │ │ ├── __init__.cpython-36 (1).pyc │ │ └── __init__.cpython-36.pyc │ ├── RunTests.py │ ├── ShellUI │ ├── BTCInput (1).py │ ├── BTCInput.py │ ├── FashionShopShell (1).py │ ├── FashionShopShell.py │ ├── FashionShopShellUI (1).py │ ├── FashionShopShellUI.py │ ├── __init__ (1).py │ ├── __init__.py │ └── __pycache__ │ │ ├── BTCInput.cpython-36 (1).pyc │ │ ├── BTCInput.cpython-36.pyc │ │ ├── FashionShopShell.cpython-36 (1).pyc │ │ ├── FashionShopShell.cpython-36.pyc │ │ ├── __init__.cpython-36 (1).pyc │ │ └── __init__.cpython-36.pyc │ ├── Storage │ ├── FashionShop (1).py │ ├── FashionShop.py │ ├── StockItem (1).py │ ├── StockItem.py │ ├── __init__ (1).py │ ├── __init__.py │ └── __pycache__ │ │ ├── FashionShop.cpython-36 (1).pyc │ │ ├── FashionShop.cpython-36.pyc │ │ ├── StockItem.cpython-36 (1).pyc │ │ ├── StockItem.cpython-36.pyc │ │ ├── __init__.cpython-36 (1).pyc │ │ └── __init__.cpython-36.pyc │ ├── __pycache__ │ ├── FashionShopShellUI.cpython-36 (1).pyc │ ├── FashionShopShellUI.cpython-36.pyc │ ├── RunTests.cpython-36 (1).pyc │ └── RunTests.cpython-36.pyc │ ├── fashionshop (1).pickle │ └── fashionshop.pickle ├── Ch 14 Python programs as network clients ├── EG14-01 Receive packets on port 10001 from another machine.py ├── EG14-02 Send packets on port 10001 to another machine.py ├── EG14-03 Web page reader.py ├── EG14-04 Python ElementTree.py ├── EG14-05 RSS Feed reader.py └── EG14-06 Weather Feed Reader │ ├── EG14-06 Weather Feed Reader.py │ └── weather.txt ├── Ch 15 Python programs as network servers ├── EG15-01 Tiny socket web server.py ├── EG15-02 Python web server.py ├── EG15-03 Python web page server │ ├── EG15-03 Python web page server.py │ ├── index.html │ └── page.html ├── EG15-04 Full Python web page server │ ├── EG15-04 Full Python web page server.py │ ├── index.html │ ├── page.html │ └── picture.jpg └── EG15-05 Web message board │ └── EG15-05 Web message board.py ├── Ch 16 Python games with Pygame ├── EG 16-01 pygame drawing functions.py ├── EG16-02 Image Drawing.py ├── EG16-02 Image Drawing │ ├── EG16-02 Image Drawing.py │ └── cheese.png ├── EG16-03 Moving cheese │ ├── EG16-03 Moving cheese.py │ └── cheese.png ├── EG16-04 Steerable cheese │ ├── EG16-04 Steerable cheese.py │ └── cheese.png ├── EG16-05 background sprite │ ├── EG16-05 background sprite.py │ └── background.png ├── EG16-06 Cheese Player │ ├── EG16-06 Cheese Player.py │ ├── background.png │ └── cheese.png ├── EG16-07 Cheese and cracker │ ├── EG16-07 Cheese and cracker.py │ ├── background.png │ ├── cheese.png │ └── cracker.png ├── EG16-08 Cheese and crackers │ ├── EG16-08 Cheese and crackers.py │ ├── background.png │ ├── cheese.png │ └── cracker.png ├── EG16-09 Capturing crackers │ ├── EG16-09 Capturing crackers.py │ ├── background.png │ ├── burp.wav │ ├── cheese.png │ └── cracker.png ├── EG16-09 Scoring cheese and crackers │ ├── EG16-09 Capturing crackers.py │ ├── EG16-09 Scoring cheese and crackers.py │ ├── background.png │ ├── burp.wav │ ├── cheese.png │ └── cracker.png ├── EG16-10 Killer tomato │ ├── EG16-10 Killer tomato.py │ ├── Tomato.png │ ├── background.png │ ├── burp.wav │ ├── cheese.png │ └── cracker.png └── EG16-11 Complete Game │ ├── EG16-11 Complete Game.pyw │ ├── Tomato.png │ ├── background.png │ ├── burp.wav │ ├── cheese.png │ ├── cracker.png │ └── start background.png ├── README.md ├── images └── cover.png ├── notes └── prep.pdf └── snaps.py /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.pyc 3 | -------------------------------------------------------------------------------- /Ch 03 Python Program Structure/EG3-01 Throw a single die.py: -------------------------------------------------------------------------------- 1 | import random #import the random library 2 | print(random.randint(1,6)) 3 | -------------------------------------------------------------------------------- /Ch 03 Python Program Structure/EG3-02 Deep Thought.py: -------------------------------------------------------------------------------- 1 | import time 2 | print('I will need to think about that..') 3 | time.sleep(5) 4 | print('The answer is: 42') 5 | -------------------------------------------------------------------------------- /Ch 03 Python Program Structure/EG3-03 Egg timer.py: -------------------------------------------------------------------------------- 1 | # EG3-03 Egg timer 2 | import time 3 | print('Put the egg in boiling water now') 4 | time.sleep(300) 5 | print('Take the egg out now') 6 | -------------------------------------------------------------------------------- /Ch 03 Python Program Structure/EG3-04 hello world.py: -------------------------------------------------------------------------------- 1 | # EG3-04 hello world 2 | 3 | import snaps 4 | 5 | snaps.display_message('hello world') 6 | -------------------------------------------------------------------------------- /Ch 03 Python Program Structure/EG3-05 housemartins.py: -------------------------------------------------------------------------------- 1 | # EG3-05 housemartins 2 | 3 | import snaps 4 | 5 | snaps.display_image('Housemartins.jpg') 6 | snaps.display_message('Hull Rocks',color=(255,255,255),vert='top') 7 | -------------------------------------------------------------------------------- /Ch 03 Python Program Structure/EG3-06 Ding.py: -------------------------------------------------------------------------------- 1 | # EG3-06 Ding 2 | 3 | import snaps 4 | 5 | snaps.play_sound('ding.wav') 6 | -------------------------------------------------------------------------------- /Ch 03 Python Program Structure/Housemartins.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 03 Python Program Structure/Housemartins.jpg -------------------------------------------------------------------------------- /Ch 03 Python Program Structure/ding.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 03 Python Program Structure/ding.wav -------------------------------------------------------------------------------- /Ch 03 Python Program Structure/egg_timer_background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 03 Python Program Structure/egg_timer_background.png -------------------------------------------------------------------------------- /Ch 04 Working with Data in Python/EG4-01 Self Timer.py: -------------------------------------------------------------------------------- 1 | # EG4-01 Self Timer 2 | 3 | import time 4 | import random 5 | 6 | print('Welcome to Self Timer') 7 | 8 | print('Everybody stand up') 9 | print('Stay standing until you think the time has ended') 10 | print('Then sit down.') 11 | print('Anyone still standing when the time ends loses.') 12 | print('The last person to sit down before the time ended will win.') 13 | 14 | stand_time = random.randint(5, 20) 15 | 16 | print('Stay standing for', stand_time, 'seconds.') 17 | 18 | time.sleep(stand_time) 19 | 20 | print('****TIME UP****') 21 | 22 | -------------------------------------------------------------------------------- /Ch 04 Working with Data in Python/EG4-02 User Configurable Egg Timer.py: -------------------------------------------------------------------------------- 1 | # EG4-02 User Configurable Egg Timer 2 | 3 | import time 4 | 5 | time_text = input('Enter the cooking time in seconds: ') 6 | 7 | time_int = int(time_text) 8 | 9 | print('Put the egg in boiling water now') 10 | 11 | time.sleep(time_int) 12 | 13 | print('Take the egg out now') 14 | -------------------------------------------------------------------------------- /Ch 04 Working with Data in Python/EG4-03 Ultra-precise Egg Timer.py: -------------------------------------------------------------------------------- 1 | # EG4-03 Ultra-precise Egg Timer 2 | 3 | import time 4 | 5 | time_text = input('Enter the cooking time in seconds: ') 6 | 7 | time_float = float(time_text) 8 | 9 | print('Put the egg in boiling water now') 10 | 11 | time.sleep(time_float) 12 | 13 | print('Take the egg out now') 14 | -------------------------------------------------------------------------------- /Ch 04 Working with Data in Python/EG4-04 Pizza Order Calculator.py: -------------------------------------------------------------------------------- 1 | # EG4-04 Pizza Order Calculator 2 | 3 | students_text = input('How many students: ') 4 | 5 | students_int = int(students_text) 6 | 7 | pizza_count = students_int/1.5 8 | 9 | print('You will need', pizza_count, 'pizzas') 10 | 11 | -------------------------------------------------------------------------------- /Ch 04 Working with Data in Python/EG4-05 Seattle Temperature.py: -------------------------------------------------------------------------------- 1 | # EG4-05 Seattle Temperature 2 | 3 | import snaps 4 | 5 | temp = snaps.get_weather_temp(latitude=47.61, longitude=-122.33) 6 | print('The temperature in Seattle is:', temp) 7 | -------------------------------------------------------------------------------- /Ch 04 Working with Data in Python/EG4-06 Seattle Weather.py: -------------------------------------------------------------------------------- 1 | # EG4-06 Seattle Weather 2 | 3 | import snaps 4 | 5 | desc=snaps.get_weather_desciption(latitude=47.61, longitude=-122.33) 6 | print('The conditions are:',desc) 7 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-01 OneHandedClock.py: -------------------------------------------------------------------------------- 1 | # EG5-01 One handed clock Version 1.0 2 | 3 | import time 4 | 5 | current_time = time.localtime() 6 | 7 | hour = current_time.tm_hour 8 | 9 | print('The hour is', hour) 10 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-02 Simple Alarm Clock.py: -------------------------------------------------------------------------------- 1 | # EG5-02 Simple Alarm Clock 2 | 3 | import time 4 | 5 | current_time = time.localtime() 6 | 7 | hour = current_time.tm_hour 8 | minute = current_time.tm_min 9 | 10 | it_is_time_to_get_up = (hour>7) or (hour==7 and minute>29) 11 | 12 | if it_is_time_to_get_up: 13 | print('IT IS TIME TO GET UP') 14 | 15 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-03 Siren Alarm Clock.py: -------------------------------------------------------------------------------- 1 | # EG5-03 Siren Alarm Clock 2 | 3 | import time 4 | import snaps 5 | 6 | current_time = time.localtime() 7 | 8 | hour = current_time.tm_hour 9 | minute = current_time.tm_min 10 | 11 | if (hour>7) or (hour==7 and minute>29): 12 | snaps.display_message('TIME TO GET UP') 13 | snaps.play_sound('siren.wav') 14 | # pause the program to give the sound time to play 15 | time.sleep(10) 16 | 17 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-04 Alarm clock with time display.py: -------------------------------------------------------------------------------- 1 | # EG5-04 Alarm clock with time display 2 | 3 | import time 4 | 5 | current_time = time.localtime() 6 | 7 | hour = current_time.tm_hour 8 | minute = current_time.tm_min 9 | 10 | if (hour>7) or (hour==7 and minute>29): 11 | print('IT IS TIME TO GET UP') 12 | print('RISE AND SHINE') 13 | print('THE EARLY BIRD GETS THE WORM') 14 | print('The time is ', hour,':',minute) 15 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-05 Simple Alarm Clock with else.py: -------------------------------------------------------------------------------- 1 | # EG5-05 Simple Alarm Clock with else 2 | 3 | import time 4 | 5 | current_time = time.localtime() 6 | 7 | hour = current_time.tm_hour 8 | minute = current_time.tm_min 9 | 10 | if (hour>7) or (hour==7 and minute>29): 11 | print('IT IS TIME TO GET UP') 12 | else: 13 | print('Go back to bed') 14 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-06 Broken Greeter.py: -------------------------------------------------------------------------------- 1 | # EG5-06 Broken Greeter 2 | name = input('Enter your name: ') 3 | if name == 'Rob': 4 | print('Hello, Oh great one') 5 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-07 Upper case Greeter.py: -------------------------------------------------------------------------------- 1 | # EG5-07 Uppercase Greeter 2 | 3 | name = input('Enter your name: ') 4 | 5 | if name.upper() == 'ROB': 6 | print('Hello, Oh great one') 7 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-08 Greeter with password.py: -------------------------------------------------------------------------------- 1 | # EG5-08 Greeter with password 2 | 3 | name = input('Enter your name: ') 4 | 5 | if name.upper() == 'ROB': 6 | password = input('Enter the password: ') 7 | if password == 'secret': 8 | print('Hello, Oh great one') 9 | else: 10 | print('Begone. Imposter') 11 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-09 Greeter with outer else.py: -------------------------------------------------------------------------------- 1 | # EG5-11 Greeter with outer else 2 | 3 | name = input('Enter your name: ') 4 | 5 | if name.upper() == 'ROB': 6 | password = input('Enter the password') 7 | if password =='secret': 8 | print('Hello, Oh great one') 9 | else: 10 | print('You are not Rob. Shame.') 11 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-10 Ride Selector Start.py: -------------------------------------------------------------------------------- 1 | # EG5-10 Ride Selector Start 2 | 3 | print('''Welcome to our Theme Park 4 | 5 | These are the available rides: 6 | 7 | 1. Scenic River Cruise 8 | 2. Carnival Carousel 9 | 3. Jungle Adventure Water Splash 10 | 4. Downhill Mountain Run 11 | 5. The Regurgitator 12 | ''') 13 | 14 | ride_number_text = input('Please enter the ride number you want: ') 15 | ride_number = int(ride_number_text) 16 | 17 | if ride_number == 1: 18 | print('You have selected the Scenic River Cruise') 19 | print('There are no age limits for this ride') 20 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-11 Complete Ride Selector.py: -------------------------------------------------------------------------------- 1 | # EG5-11 Complete Ride Selector 2 | 3 | print('''Welcome to our Theme Park 4 | 5 | These are the rides that are available 6 | 7 | 1: Scenic River Cruise 8 | 2: Carnival Carousel 9 | 3: Jungle Adventure Water Splash 10 | 4: Downhill Mountain Run 11 | 5: The Regurgitator 12 | ''') 13 | 14 | ride_number_text = input('Please enter the ride number you want: ') 15 | ride_number = int(ride_number_text) 16 | 17 | if ride_number == 1: 18 | print('You have selected the Scenic River Cruise') 19 | print('There are no age limits on this ride') 20 | else: 21 | # We need to get the age of the user 22 | age_text = input('Please enter your age: ') 23 | age = int(age_text) 24 | if ride_number == 2: 25 | print('You have selected the Carnival Carousel') 26 | if age >= 3: 27 | print('You can go on the ride.') 28 | else: 29 | print('Sorry. You are too young.') 30 | if ride_number == 3: 31 | print('You have selected the Jungle Adventure Water Splash') 32 | if age >= 6: 33 | print('You can go on the ride.') 34 | else: 35 | print('Sorry. You are too young.') 36 | if ride_number == 4: 37 | print('You have selected the Downhill Mountain Run') 38 | if age >= 12: 39 | print('You can go on the ride.') 40 | else: 41 | print('Sorry. You are too young.') 42 | if ride_number == 5: 43 | print('You have selected The Regurgitator ') 44 | if age >= 12: 45 | # Age is not too low 46 | if age > 70: 47 | # Age is too high 48 | print('Sorry. You are too old.') 49 | else: 50 | # Age is in the correct range 51 | print('You can go on the ride.') 52 | else: 53 | # Age is too low 54 | print('Sorry. You are too young.') 55 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-12 Snaps get_string function.py: -------------------------------------------------------------------------------- 1 | # EG5-12 Snaps get_string function 2 | 3 | import snaps 4 | 5 | name = snaps.get_string('Enter your name: ') 6 | snaps.display_message('Hello ' + name) 7 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-13 Theme Park Snaps Display.py: -------------------------------------------------------------------------------- 1 | # EG5-13 Theme Park Snaps Display 2 | 3 | import snaps 4 | 5 | snaps.display_image('themepark.png') 6 | 7 | prompt='''These are the available rides 8 | 9 | 1: Scenic River Cruise 10 | 2: Carnival Carousel 11 | 3: Jungle Adventure Water Splash 12 | 4: Downhill Mountain Run 13 | 5: The Regurgitator 14 | 15 | Select your ride: ''' 16 | 17 | ride_number_text = snaps.get_string(prompt,vert='bottom', 18 | max_line_length=3) 19 | 20 | confirm='Ride ' + ride_number_text 21 | snaps.display_message(confirm) 22 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/EG5-14 Weather helper.py: -------------------------------------------------------------------------------- 1 | # EG5-14 Weather helper 2 | 3 | import snaps 4 | 5 | temp = snaps.get_weather_temp(latitude=47.61, longitude=-122.33) 6 | 7 | print('The temperature is:', temp) 8 | 9 | if temp < 40: 10 | print('Wear a coat - it is cold out there') 11 | elif temp > 70: 12 | print('Remember to wear sunscreen') 13 | -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/siren.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 05 Making Decisions in Programs/siren.wav -------------------------------------------------------------------------------- /Ch 05 Making Decisions in Programs/themepark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 05 Making Decisions in Programs/themepark.png -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-01 Loop with boolean flag.py: -------------------------------------------------------------------------------- 1 | # EG6-01 Loop with boolean flag 2 | flag=True 3 | while flag: 4 | print('Inside loop') 5 | flag=False 6 | print('Outside loop') 7 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-02 Loop with counter.py: -------------------------------------------------------------------------------- 1 | # EG6-02 Loop with counter 2 | count=0 3 | while count<5: 4 | print('Inside loop') 5 | count=count+1 6 | print('Outside loop') 7 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-04 Handing invalid text.py: -------------------------------------------------------------------------------- 1 | #EG6-04 Handing invalid text 2 | ride_number_valid=False # create a flag value and set it to False 3 | while ride_number_valid==False: # repeat while the flag is False 4 | try: # start of code that might throw exceptions 5 | ride_number_text = input('Please enter the ride number you want: ') # read in some text 6 | ride_number = int(ride_number_text) # convert the text into a number (might raise exception) 7 | ride_number_valid=True # if we get here we know the number is OK. Set the flag. 8 | except ValueError: # the handler for an invalid number 9 | print('Invalid number text. Please enter digits.') # display a message 10 | # When we get here we have a valid ride number 11 | print('You have selected ride',ride_number) 12 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-05 Catching multiple exceptions.py: -------------------------------------------------------------------------------- 1 | # EG6-05 Catching multiple exceptions 2 | ride_number_valid=False # create a flag value and set it to False 3 | while ride_number_valid==False: # repeat while the flag is False 4 | try: # start of code that might throw exceptions 5 | ride_number_text = input('Please enter the ride number you want: ') # read in some text 6 | ride_number = int(ride_number_text) # convert the text into a number (might raise exception) 7 | ride_number_valid=True # if we get here we know the number is OK. Set the flag. 8 | except ValueError: # the handler for an invalid number 9 | print('Invalid number text. Please enter digits.') # display a message 10 | except KeyboardInterrupt: # the handler for an interrupt 11 | print('Please do not try to stop the program.') # display a message 12 | # When we get here we have a valid ride number 13 | print('You have selected ride',ride_number) 14 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-06 Using break to exit loops.py: -------------------------------------------------------------------------------- 1 | # EG6-06 Using break to exit loops 2 | while True: # repeat forever 3 | try: # start of code that might throw exceptions 4 | ride_number_text = input('Please enter the ride number you want: ') # read in some text 5 | ride_number = int(ride_number_text) # convert the text into a number (might raise exception) 6 | break # if we get here we know the number is OK. Break out of the loop. 7 | except ValueError: # the handler for an invalid number 8 | print('Invalid number text. Please enter digits.') # display a message 9 | except KeyboardInterrupt: # the handler for an interrupt 10 | print('Please do not try to stop the program.') # display a message 11 | # When we get here we have a valid ride number 12 | print('You have selected ride',ride_number) 13 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-07 Loop with condition early ending.py: -------------------------------------------------------------------------------- 1 | # EG6-07 Loop with condition early ending 2 | count=0 3 | while count<5: 4 | print('Inside loop') 5 | count=count+1 6 | if count==3: 7 | break 8 | print('Outside loop') 9 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-08 Ignore Ride 3.py: -------------------------------------------------------------------------------- 1 | # EG6-08 Ignore Ride 3 2 | while True: 3 | ride_number_text = input('Please enter the ride number you want: ') 4 | ride_number = int(ride_number_text) 5 | if ride_number == 3: 6 | print('Sorry, this ride is not available') 7 | continue 8 | print('You have selected ride number:',ride_number) 9 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-09 Times Table Tutor.py: -------------------------------------------------------------------------------- 1 | # EG6-09 Times Table Tutor 2 | count = 1 3 | timesValue = 2 4 | while count < 13: 5 | result = count * timesValue 6 | print(count,'times',timesValue,'equals',result) 7 | count = count + 1; 8 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-10 Name printer.py: -------------------------------------------------------------------------------- 1 | # EG6-10 Name printer 2 | names=('Rob','Mary','David','Jenny','Chris','Imogen') 3 | for •name in •names : 4 | print(name) 5 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-11 Times Table Loops.py: -------------------------------------------------------------------------------- 1 | # EG6-11 Times Table Loops 2 | times_value = 2 3 | for count in range(1,13): 4 | result = count * times_value 5 | print(count,'times', times_value,'equals',result) 6 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-12 Code Analysis 1.py: -------------------------------------------------------------------------------- 1 | # EG6-12 Code Analysis 1 2 | for count in range(1,13): 3 | if count==5: 4 | break 5 | print(count) 6 | print('Finished') 7 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-13 Code Analysis 2.py: -------------------------------------------------------------------------------- 1 | # EG6-13 Code Analysis 2 2 | for count in range(1,13): 3 | if count==5: 4 | continue 5 | print(count) 6 | print('Finished') 7 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-14 Code Analysis 3.py: -------------------------------------------------------------------------------- 1 | # EG6-14 Code Analysis 3 2 | for count in range(1,13): 3 | count=13 4 | print(count) 5 | print('Finished') 6 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-15 Code Analysis 4.py: -------------------------------------------------------------------------------- 1 | # EG6-14 Code Analysis 3 2 | while True: 3 | break; 4 | print('Finished') 5 | -------------------------------------------------------------------------------- /Ch 06 Loops/EG6-18 Digital Clock.py: -------------------------------------------------------------------------------- 1 | # EG6-18 Digital Clock 2 | 3 | import time 4 | 5 | import snaps 6 | 7 | while True: 8 | 9 | current_time = time.localtime() 10 | 11 | hour_string = str(current_time.tm_hour) 12 | minute_string = str(current_time.tm_min) 13 | second_string = str(current_time.tm_sec) 14 | 15 | time_string = hour_string+':'+minute_string+':'+second_string 16 | snaps.display_message(time_string) 17 | time.sleep(1) 18 | 19 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-01 Pathfinder.py: -------------------------------------------------------------------------------- 1 | # EG7-01 Pathfinder 2 | def m2(): 3 | print('the') 4 | 5 | def m3(): 6 | print('sat on') 7 | m2() 8 | 9 | def m1(): 10 | m2() 11 | print('cat') 12 | m3() 13 | print('mat') 14 | 15 | m1() 16 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-02 Times Table.py: -------------------------------------------------------------------------------- 1 | # EG7-02 Times Table 2 | def print_times_table(times_value): 3 | count = 1 4 | while count < 13: 5 | result = times_value * count 6 | print(count,'times', times_value,'equals',result) 7 | count = count + 1 8 | 9 | print_times_table(6) 10 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-03 Safer Times Table.py: -------------------------------------------------------------------------------- 1 | # EG7-03 Safe Times Table 2 | def print_times_table(times_value): 3 | if isinstance(times_value,int)== False: 4 | raise Exception('print_times_table only works with integers') 5 | count = 1 6 | while count < 13: 7 | result = times_value * count 8 | print(count,'times', times_value,'equals',result) 9 | count = count + 1 10 | #this will work fine 11 | print_times_table(6) 12 | #this will raise an exception 13 | print_times_table('six') 14 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-04 Two Parameter Times Table.py: -------------------------------------------------------------------------------- 1 | # EG7-04 Two Parameter Times Table 2 | def print_times_table(times_value, limit): 3 | count = 1 4 | while count < limit+1: 5 | result = times_value * count 6 | print(count,'times', times_value,'equals',result) 7 | count = count + 1 8 | print_times_table(6,5) 9 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-05 Keyword Arguments.py: -------------------------------------------------------------------------------- 1 | # EG7-05 Keyword Arguments 2 | def print_times_table(times_value, limit): 3 | count = 1 4 | while count < limit+1: 5 | result = times_value * count 6 | print(count,'times', times_value,'equals',result) 7 | count = count + 1 8 | 9 | print_times_table(times_value=12,limit=7) 10 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-06 Default parameters.py: -------------------------------------------------------------------------------- 1 | # EG7-05 Keyword Arguments 2 | def print_times_table(times_value, limit): 3 | count = 1 4 | while count < limit+1: 5 | result = times_value * count 6 | print(count,'times', times_value,'equals',result) 7 | count = count + 1 8 | 9 | print_times_table(times_value=12,limit=7) 10 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-07 Parameters as values.py: -------------------------------------------------------------------------------- 1 | # EG7-07 Parameters as values 2 | def what_would_I_do(input_value): 3 | input_value = 99 4 | 5 | test=0 6 | what_would_I_do(test) 7 | print('The value of test is',test) 8 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-08 get_value investigation 1.py: -------------------------------------------------------------------------------- 1 | # EG7-08 get_value investigation 1 2 | def get_value(prompt, value_min, value_max): 3 | return 1 4 | return 2 5 | 6 | ride_number=get_value(prompt='Please enter the ride number you want:',value_min=1,value_max=5) 7 | print('You have selected ride:',ride_number) 8 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-09 get_value investigation 2.py: -------------------------------------------------------------------------------- 1 | # EG7-09 get_value investigation 2 2 | def get_value(prompt, value_min, value_max): 3 | return 4 | 5 | ride_number=get_value(prompt='Please enter the ride number you want:',value_min=1,value_max=5) 6 | print('You have selected ride:',ride_number) 7 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-10 complete get_value.py: -------------------------------------------------------------------------------- 1 | # EG7-10 complete get_value 2 | def get_value(prompt, value_min, value_max): 3 | while True: 4 | number_text = input(prompt) 5 | try: 6 | number = int(number_text) 7 | except ValueError: 8 | print('Invalid number text. Please enter digits.') 9 | continue # return to the top of the loop 10 | if numbervalue_max: 15 | print('Value too large') 16 | print('The maximum value is',value_max) 17 | continue # return to the top of the loop 18 | # If we get here the number is valid 19 | # return it 20 | return number 21 | 22 | ride_number=get_value(prompt='Please enter the ride number you want:',value_min=1,value_max=5) 23 | print('You have selected ride:',ride_number) 24 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-11 Local Variables.py: -------------------------------------------------------------------------------- 1 | # EG7-11 Local Variables 2 | 3 | def func_2(): 4 | i=99 5 | 6 | def func_1(): 7 | i=0 8 | func_2() 9 | print('The value of i is: ',i) 10 | 11 | func_1() 12 | 13 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-12 Reading Global Variables.py: -------------------------------------------------------------------------------- 1 | # EG7-12 Reading Global Variables 2 | 3 | cheese=99 4 | 5 | def func(): 6 | print('Global cheese is:',cheese) 7 | 8 | func() 9 | 10 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-13 Shadowing Global Variables.py: -------------------------------------------------------------------------------- 1 | # EG7-13 Shadowing Global Variables 2 | 3 | cheese=99 4 | 5 | def func(): 6 | cheese=100 7 | print('Local cheese is:',cheese) 8 | 9 | func() 10 | print('Global cheese is:',cheese) 11 | 12 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-14 Storing Global Variables.py: -------------------------------------------------------------------------------- 1 | # EG7-14 Storing Global Variables 2 | 3 | cheese=99 4 | 5 | def func(): 6 | global cheese 7 | cheese=100 8 | print('Global cheese is:',cheese) 9 | 10 | func() 11 | print('Global cheese is:',cheese) 12 | 13 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-15 Using the input module.py: -------------------------------------------------------------------------------- 1 | # EG7-15 Using the input module 2 | 3 | import BTCInput 4 | 5 | text_value = BTCInput.read_text('Enter some text: ') 6 | print('The text entered is ', text_value) 7 | 8 | int_value = BTCInput.read_int('Enter an integer: ') 9 | print('Int value is ', int_value) 10 | 11 | float_value = BTCInput.read_float('Enter a float value: ') 12 | print('Float value is ', float_value) 13 | 14 | ranged_int = BTCInput.read_int_ranged(prompt= 'Int in range 5 to 90: ', 15 | min_value=5, 16 | max_value=90) 17 | print('Ranged int is', ranged_int) 18 | 19 | ranged_float = BTCInput.read_float_ranged(prompt= 'Float in range 5 to 90: ', 20 | min_value=5, 21 | max_value=90) 22 | print('Ranged float is', ranged_float) 23 | -------------------------------------------------------------------------------- /Ch 07 Methods/EG7-16 Investigating the debugger.py: -------------------------------------------------------------------------------- 1 | # EG7-16 Investigating the debugger 2 | 3 | 4 | def increment_function(input_value): 5 | result = input_value + 1 6 | return result 7 | 8 | 9 | x = 99 10 | y = increment_function(x) 11 | print('The answer is:',y) 12 | 13 | 14 | -------------------------------------------------------------------------------- /Ch 07 Methods/read_text.py: -------------------------------------------------------------------------------- 1 | def read_text(prompt): 2 | ''' 3 | Displays a prompt and reads in a string of text. 4 | Keyboard interrupts (CTRL+C) are ignored 5 | returns a string containing the string input by the user 6 | ''' 7 | while True: # repeat forever 8 | try: 9 | result=input(prompt) # read the input 10 | # if we get here no exception was raised 11 | # break out of the loop 12 | break 13 | except KeyboardInterrupt: 14 | # if we get here the user pressed CTRL+C 15 | print('Please enter text') 16 | 17 | # return the result 18 | return result 19 | 20 | 21 | def read_float(prompt): 22 | ''' 23 | Displays a prompt and reads in a number. 24 | Keyboard interrupts (CTRL+C) are ignored 25 | Invalid numbers are rejected 26 | returns a float containing the value input by the user 27 | ''' 28 | while True: # repeat forever 29 | try: 30 | number_text=read_text(prompt) 31 | result=float(number_text) # read the input 32 | # if we get here no exception was raised 33 | # break out of the loop 34 | break 35 | except ValueError: 36 | # if we get here the user entered an invalid number 37 | print('Please enter a number') 38 | 39 | # return the result 40 | return result 41 | 42 | def read_float_ranged(prompt, min_value, max_value): 43 | ''' 44 | Displays a prompt and reads in a number. 45 | min_value gives the inclusive minimum value 46 | max_value gives the inclusive maximum value 47 | Does not detect if max and min are wrong way round 48 | Keyboard interrupts (CTRL+C) are ignored 49 | Invalid numbers are rejected 50 | returns a float containing the value input by the user 51 | ''' 52 | if min_value>max_value: 53 | # If we get here the min and the max 54 | # are wrong way round 55 | raise Exception('Min value is greater than max value') 56 | while True: # repeat forever 57 | result=read_float(prompt) 58 | if resultmax_value: 65 | # Value entered is too high 66 | print('That number is too high') 67 | print('Maximum value is:',max_value) 68 | # Repeat the number reading loop 69 | continue 70 | # If we get here the number is valid 71 | # break out of the loop 72 | break 73 | # return the result 74 | return result 75 | 76 | 77 | age=read_float('Please enter your age:') 78 | age=read_float_ranged('Enter your age:',min_value=500,max_value=90) 79 | print('Your age is:',age) 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /Ch 07 Methods/teletypePrinter.py: -------------------------------------------------------------------------------- 1 | # Teletype printer 2 | 3 | import time 4 | 5 | def teletype_print(text,delay=0.1): 6 | for ch in text: 7 | print(ch,end='') 8 | time.sleep(delay) 9 | print() 10 | 11 | teletype_print('Hello world') 12 | -------------------------------------------------------------------------------- /Ch 08 Collections/EG8-01 Finding the largest sales.py: -------------------------------------------------------------------------------- 1 | # EG8-01 Finding the largest sales 2 | 3 | from BTCInput import * 4 | 5 | sales1=read_int('Enter the sales for stand 1: ') 6 | sales2=read_int('Enter the sales for stand 2: ') 7 | sales3=read_int('Enter the sales for stand 3: ') 8 | sales4=read_int('Enter the sales for stand 4: ') 9 | sales5=read_int('Enter the sales for stand 5: ') 10 | sales6=read_int('Enter the sales for stand 6: ') 11 | sales7=read_int('Enter the sales for stand 7: ') 12 | sales8=read_int('Enter the sales for stand 8: ') 13 | sales9=read_int('Enter the sales for stand 9: ') 14 | sales10=read_int('Enter the sales for stand 10: ') 15 | 16 | if sales1>sales2 and sales1>sales3 and sales1>sales4 \ 17 | and sales1>sales5 and sales1>sales6 and sales1>sales7 \ 18 | and sales1>sales8 and sales1>sales9 and sales1>sales10: 19 | print('Stand 1 had the best sales') 20 | -------------------------------------------------------------------------------- /Ch 08 Collections/EG8-02 Read and Display.py: -------------------------------------------------------------------------------- 1 | # EG8-02 Read and Display 2 | 3 | from BTCInput import * 4 | 5 | sales=[] 6 | 7 | for count in range(1,11): 8 | prompt='Enter the sales for stand ' + str(count) + ': ' 9 | sales.append(read_int(prompt)) 10 | 11 | print(sales) 12 | -------------------------------------------------------------------------------- /Ch 08 Collections/EG8-03 Read and Display loop.py: -------------------------------------------------------------------------------- 1 | # EG8-03 Read and Display loop 2 | 3 | #fetch the input functions 4 | from BTCInput import * 5 | 6 | #create an empty sales list 7 | sales=[] 8 | 9 | # read in 10 sales figures 10 | for count in range(1,11): 11 | # assemble a prompt string 12 | prompt='Enter the sales for stand ' + str(count) + ': ' 13 | # read a value and append it to sales array 14 | sales.append(read_int(prompt)) 15 | 16 | # print a heading 17 | print('Sales figures') 18 | # initialise the stand counter 19 | count=1 20 | # work through the sales figures and print them 21 | for sales_value in sales: 22 | # print an item 23 | print('Sales for stand', count,'are',sales_value) 24 | # advance the stand counter 25 | count = count + 1 26 | -------------------------------------------------------------------------------- /Ch 08 Collections/EG8-04 Functions.py: -------------------------------------------------------------------------------- 1 | # EG8-03 Functions 2 | 3 | #fetch the input functions 4 | from BTCInput import * 5 | 6 | #sales list used by the program 7 | sales=[] 8 | 9 | def read_sales(no_of_sales): 10 | ''' 11 | Reads in the sales values and stores them in 12 | the sales list. 13 | no_of_sales gives the number of sales values to store 14 | ''' 15 | # remove all the previous sales values 16 | sales.clear() 17 | # read in sales figures 18 | for count in range(1,no_of_sales+1): 19 | # assemble a prompt string 20 | prompt='Enter the sales for stand ' + str(count) + ': ' 21 | # read a value and append it to sales list 22 | sales.append(read_int(prompt)) 23 | 24 | def print_sales(): 25 | ''' 26 | Prints the sales figures on the screen with 27 | a heading. Each figure is numbered in seqeuence 28 | ''' 29 | # print a heading 30 | print('Sales figures') 31 | # initialise the stand counter 32 | count=1 33 | # work through the sales figures 34 | for sales_value in sales: 35 | # print an item 36 | print('Sales for stand', count,'are',sales_value) 37 | # advance the stand counter 38 | count = count + 1 39 | #Program runs here 40 | read_sales(10) 41 | print_sales() 42 | 43 | -------------------------------------------------------------------------------- /Ch 08 Collections/EG8-05 Functions and Menu.py: -------------------------------------------------------------------------------- 1 | # EG8-05 Functions and Menu 2 | 3 | #fetch the input functions 4 | from BTCInput import * 5 | 6 | #create an empty sales list 7 | sales=[] 8 | 9 | def read_sales(no_of_sales): 10 | ''' 11 | Reads in the sales values and stores them in 12 | the sales list. 13 | no_of_sales gives the number of sales values to store 14 | ''' 15 | # remove all the previous sales values 16 | sales.clear() 17 | # read in sales figures 18 | for count in range(1,no_of_sales+1): 19 | # assemble a prompt string 20 | prompt='Enter the sales for stand ' + str(count) + ': ' 21 | # read a value and append it to sales list 22 | sales.append(read_int(prompt)) 23 | 24 | def print_sales(): 25 | ''' 26 | Prints the sales figures on the screen with 27 | a heading. Each figure is numbered in seqeuence 28 | ''' 29 | # print a heading 30 | print('Sales figures') 31 | # initialise the stand counter 32 | count=1 33 | # work through the sales figures 34 | for sales_value in sales: 35 | # print an item 36 | print('Sales for stand', count,'are',sales_value) 37 | # advance the stand counter 38 | count = count + 1 39 | 40 | def sort_high_to_low(): 41 | ''' 42 | Print out a list of the sales figures sorted low to high 43 | ''' 44 | pass 45 | 46 | def sort_low_to_high(): 47 | ''' 48 | Print out a list of the sales figures sorted hight to low 49 | ''' 50 | pass 51 | 52 | def highest_and_lowest(): 53 | ''' 54 | Print out the highest and the lowest sales values 55 | ''' 56 | pass 57 | 58 | def total_sales(): 59 | ''' 60 | Print out the total sales value 61 | ''' 62 | pass 63 | 64 | def average_sales(): 65 | ''' 66 | Print out the average sales value 67 | ''' 68 | pass 69 | 70 | 71 | # Start by reading in the sales 72 | read_sales(10) 73 | 74 | # Now get the command from the user 75 | 76 | menu='''Ice Cream Sales 77 | 78 | 1: Print the sales 79 | 2: Sort High to Low 80 | 3: Sort Low to High 81 | 4: Highest and Lowest 82 | 5: Total Sales 83 | 6: Average sales 84 | 7: Enter Figures 85 | 86 | Enter your command: ''' 87 | 88 | command=read_int_ranged(menu,1,7) 89 | if command==1: 90 | print_sales() 91 | else: 92 | if command==2: 93 | sort_high_to_low() 94 | else: 95 | if command==3: 96 | sort_low_to_high() 97 | else: 98 | if command==4: 99 | highest_and_lowest() 100 | else: 101 | if command==5: 102 | total_sales() 103 | else: 104 | if command==6: 105 | average_sales() 106 | else: 107 | if command==7: 108 | read_sales(10) 109 | 110 | -------------------------------------------------------------------------------- /Ch 08 Collections/EG8-06 Functions and Menu Elif.py: -------------------------------------------------------------------------------- 1 | # EG8-06 Functions and Menu elif 2 | 3 | #fetch the input functions 4 | from BTCInput import * 5 | 6 | #create an empty sales list 7 | sales=[] 8 | 9 | def read_sales(no_of_sales): 10 | ''' 11 | Reads in the sales values and stores them in 12 | the sales list. 13 | no_of_sales gives the number of sales values to store 14 | ''' 15 | # remove all the previous sales values 16 | sales.clear() 17 | # read in sales figures 18 | for count in range(1,no_of_sales+1): 19 | # assemble a prompt string 20 | prompt='Enter the sales for stand ' + str(count) + ': ' 21 | # read a value and append it to sales list 22 | sales.append(read_int(prompt)) 23 | 24 | def print_sales(): 25 | ''' 26 | Prints the sales figures on the screen with 27 | a heading. Each figure is numbered in seqeuence 28 | ''' 29 | # print a heading 30 | print('Sales figures') 31 | # initialise the stand counter 32 | count=1 33 | # work through the sales figures 34 | for sales_value in sales: 35 | # print an item 36 | print('Sales for stand', count,'are',sales_value) 37 | # advance the stand counter 38 | count = count + 1 39 | 40 | def sort_high_to_low(): 41 | ''' 42 | Print out a list of the sales figures sorted hight to low 43 | ''' 44 | pass 45 | 46 | def sort_low_to_high(): 47 | ''' 48 | Print out a list of the sales figures sorted low to high 49 | ''' 50 | pass 51 | 52 | def highest_and_lowest(): 53 | ''' 54 | Print out the highest and the lowest sales values 55 | ''' 56 | pass 57 | 58 | def total_sales(): 59 | ''' 60 | Print out the total sales value 61 | ''' 62 | pass 63 | 64 | def average_sales(): 65 | ''' 66 | Print out the average sales value 67 | ''' 68 | pass 69 | 70 | 71 | # Start by reading in the sales 72 | read_sales(10) 73 | 74 | # Now get the command from the user 75 | 76 | menu='''Ice Cream Sales 77 | 78 | 1: Print the sales 79 | 2: Sort High to Low 80 | 3: Sort Low to High 81 | 4: Highest and Lowest 82 | 5: Total Sales 83 | 6: Average sales 84 | 7: Enter Figures 85 | 86 | Enter your command: ''' 87 | 88 | command=read_int_ranged(menu,1,7) 89 | if command==1: 90 | print_sales() 91 | elif command==2: 92 | sort_high_to_low() 93 | elif command==3: 94 | sort_low_to_high() 95 | elif command==4: 96 | highest_and_lowest() 97 | elif command==5: 98 | total_sales() 99 | elif command==6: 100 | average_sales() 101 | elif command==7: 102 | read_sales(10) 103 | 104 | 105 | -------------------------------------------------------------------------------- /Ch 08 Collections/EG8-07 Bubble sort first pass.py: -------------------------------------------------------------------------------- 1 | # EG8-07 Bubble sort first pass 2 | 3 | # test sales data 4 | sales=[50,54,29,33,22,100,45,54,89,75] 5 | 6 | def print_sales(): 7 | ''' 8 | Prints the sales figures on the screen with 9 | a heading. Each figure is numbered in seqeuence 10 | ''' 11 | # print a heading 12 | print('Sales figures') 13 | # initialise the stand counter 14 | count=1 15 | # work through the sales figures 16 | for sales_value in sales: 17 | # print an item 18 | print('Sales for stand', count,'are',sales_value) 19 | # advance the stand counter 20 | count = count + 1 21 | 22 | def sort_high_to_low(): 23 | ''' 24 | Print out a list of the sales figures sorted hight to low 25 | ''' 26 | for count in range(0,len(sales)-1): 27 | if sales[count]sales[count+1]: 30 | temp=sales[count] 31 | sales[count]=sales[count+1] 32 | sales[count+1]=temp 33 | done_swap=True 34 | if done_swap==False: 35 | break 36 | print_sales() 37 | 38 | sort_low_to_high() 39 | -------------------------------------------------------------------------------- /Ch 08 Collections/EG8-11 High and low.py: -------------------------------------------------------------------------------- 1 | # EG8-11 High and low 2 | 3 | # test sales data 4 | sales=[50,54,29,33,22,100,45,54,89,75] 5 | 6 | def highest_and_lowest(): 7 | ''' 8 | Print out the highest and the lowest sales values 9 | ''' 10 | highest=sales[0] 11 | lowest=sales[0] 12 | for sales_value in sales: 13 | if sales_value>highest: 14 | highest=sales_value 15 | if sales_value StockItem.max_stock_add: 59 | raise Exception('Invalid add amount') 60 | 61 | self.__stock_level = self.__stock_level + count 62 | 63 | 64 | @property 65 | def price(self): 66 | if StockItem.show_instrumentation: 67 | print('** StockItem get price called') 68 | return self.__price 69 | 70 | @property 71 | def stock_level(self): 72 | if StockItem.show_instrumentation: 73 | print('** StockItem get stock level called') 74 | return self.__stock_level 75 | 76 | class Dress(StockItem): 77 | 78 | def __init__(self, stock_ref, price, color, pattern, size, location): 79 | if StockItem.show_instrumentation: 80 | print('** Dress __init__ called') 81 | super().__init__(stock_ref=stock_ref, price=price, 82 | color=color, location=location) 83 | self.pattern = pattern 84 | self.size = size 85 | self.Dress_version = 1 86 | 87 | @property 88 | def item_name(self): 89 | if StockItem.show_instrumentation: 90 | print('** Dress get item_name called') 91 | return 'Dress' 92 | 93 | def check_version(self): 94 | if StockItem.show_instrumentation: 95 | print('** Dress check_version called') 96 | # This is version 1 - no need to update anything 97 | super().check_version() 98 | pass 99 | 100 | def __str__(self): 101 | if StockItem.show_instrumentation: 102 | print('** Dress __str__ called') 103 | stock_details = super().__str__() 104 | template = '''{0} 105 | Pattern: {1} 106 | Size: {2}''' 107 | return template.format(stock_details, self.pattern, 108 | self.size) 109 | 110 | d = Dress(stock_ref='D01', price=100, color='red', pattern='swirly', 111 | size=12, location='Shop Window') 112 | 113 | d.add_stock(5) 114 | 115 | print(d) 116 | 117 | 118 | -------------------------------------------------------------------------------- /Ch 11 Object Based Solution Design/EG11-10 FashionShop template.py: -------------------------------------------------------------------------------- 1 | # EG11-10 FashionShop template 2 | 3 | class FashionShop: 4 | 5 | def __init__(self, name): 6 | pass 7 | 8 | def save(self): 9 | ''' 10 | Saves the fashion shop to the given filename 11 | Data is stored in binary as pickled file 12 | Exceptions will be raised if the save fails 13 | ''' 14 | pass 15 | 16 | @staticmethod 17 | def load(filename): 18 | ''' 19 | Loads the fashion shop from the given filename 20 | Data are stored in binary as pickled file 21 | Exceptions will be raised if the load fails 22 | ''' 23 | return None 24 | 25 | def __str__(self): 26 | return "" 27 | 28 | def get_item(self,key): 29 | ''' 30 | Gets an item from the stock dictionary 31 | Returns None if there is no item for 32 | this key 33 | ''' 34 | return None 35 | 36 | def store_new_item(self,item): 37 | ''' 38 | Store an item in the fashion shop 39 | The item is indexed on the stock_ref value 40 | Raises an exception if the item already 41 | exists 42 | ''' 43 | pass 44 | 45 | -------------------------------------------------------------------------------- /Ch 11 Object Based Solution Design/FashionShop.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 11 Object Based Solution Design/FashionShop.pickle -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-01 Simple Function References.py: -------------------------------------------------------------------------------- 1 | # EG12-01 Simple Function References 2 | 3 | def func_1(): 4 | print('hello from function 1') 5 | 6 | def func_2(): 7 | print('hello from function 2') 8 | 9 | x = func_1 10 | x() 11 | x = func_2 12 | x() 13 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-02 Invalid Function References.py: -------------------------------------------------------------------------------- 1 | # EG12-02 Invalid Function References 2 | 3 | def func_1(): 4 | print('hello from function 1') 5 | 6 | x = func_1 7 | x(99) 8 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-03 Robot Dancer.py: -------------------------------------------------------------------------------- 1 | # EG12-4 Robot Dancer 2 | 3 | import time 4 | 5 | def forward(): 6 | print('robot moving forward') 7 | time.sleep(1) 8 | 9 | def back(): 10 | print('robot moving back') 11 | time.sleep(1) 12 | 13 | def left(): 14 | print('robot moving left') 15 | time.sleep(1) 16 | 17 | def right(): 18 | print('robot moving right') 19 | time.sleep(1) 20 | 21 | dance_moves = [forward, back, left, right] 22 | 23 | print('Dance starting') 24 | for move in dance_moves: 25 | move() 26 | print('Dance over') 27 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-04 Lamdba Example.py: -------------------------------------------------------------------------------- 1 | # EG12-04 Lamdba Example 2 | 3 | # Create a list of numbers 4 | numbers = [1,2,3,4,5,6,7,8] 5 | 6 | # Create an increment function 7 | def increment(x): 8 | return x+1 9 | 10 | # Use the increment function to make an incremented list 11 | new_numbers_increment = map(increment, numbers) 12 | 13 | # print the incremented list 14 | print('Increment list: ', list(new_numbers_increment)) 15 | 16 | # Use a lambda function to make an incremented list 17 | new_numbers_lambda = map(lambda x : x+1, numbers) 18 | 19 | # print the lambada incremented list 20 | print('Increment list: ', list(new_numbers_lambda)) 21 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-05 Test contact generator.py: -------------------------------------------------------------------------------- 1 | # EG12-05 Test contact generator 2 | 3 | class Contact: 4 | 5 | def __init__(self, name, address, telephone): 6 | self.name = name 7 | self.address = address 8 | self.telephone = telephone 9 | self._hours_worked=0 10 | 11 | @staticmethod 12 | def create_test_contacts(): 13 | phone_number = 1000000 14 | hours_worked = 1 15 | for first_name in ('Rob', 'Mary', 'Jenny', 'David', 'Chris', 'Imogen'): 16 | for second_name in ('Miles', 'Brown'): 17 | full_name = first_name + ' ' + second_name 18 | address = full_name + "'s house" 19 | telephone = str(phone_number) 20 | phone_number = phone_number + 1 21 | contact = Contact(full_name, address, telephone) 22 | contact._hours_worked = hours_worked 23 | hours_worked = hours_worked + 1 24 | yield contact 25 | 26 | for contact in Contact.create_test_contacts(): 27 | print(contact.name) 28 | print(contact.address) 29 | print(contact.telephone) 30 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-06 Aribitrary Arguments.py: -------------------------------------------------------------------------------- 1 | # EG12-06 Aribitrary Arguments 2 | 3 | def add_function(*values): 4 | total = 0 5 | for value in values: 6 | total = total + value 7 | return total 8 | 9 | print(add_function()) 10 | print(add_function(1)) 11 | print(add_function(1, 2)) 12 | print(add_function(1, 2, 3)) 13 | print(add_function(1, 2, 3, 4)) 14 | print(add_function(1, 2, 3, 4, 5)) 15 | 16 | num_list = [1, 2, 3, 4, 5, 6, 7, 8] 17 | print(add_function(*num_list)) 18 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-07 Using a BTCImport function.py: -------------------------------------------------------------------------------- 1 | # EG12-07 Using a BTCImport function 2 | 3 | import BTCInput 4 | 5 | age = BTCInput.read_int_ranged(prompt='Enter age: ', min_value=5, max_value=95) 6 | print('Your age is: ',age) 7 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-08 FashionShopApp/FashionShopShellUI.py: -------------------------------------------------------------------------------- 1 | # Loads a user interface class and a storage manager class 2 | # and then uses these to create an application 3 | 4 | # Get the module containing the user interface class 5 | # from the ShellUI package 6 | from ShellUI import FashionShopShell 7 | # Get the user interface manager class from this module 8 | ui = FashionShopShell.FashionShopShell 9 | 10 | # Get the module containing the data storage class 11 | # from the Storage package 12 | from Storage import FashionShop 13 | # Get the data manager class from the storage module 14 | shop = FashionShop.FashionShop 15 | 16 | # Now create an app from the user interface object 17 | # Give it the filename and the data manager class as 18 | # parameters 19 | app = ui(filename='fashionshop.pickle', storage_class=shop) 20 | 21 | # Now call the main_menu function on the app 22 | app.main_menu() 23 | 24 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-08 FashionShopApp/ShellUI/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-08 FashionShopApp/ShellUI/__init__.py -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-08 FashionShopApp/ShellUI/__pycache__/BTCInput.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-08 FashionShopApp/ShellUI/__pycache__/BTCInput.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-08 FashionShopApp/ShellUI/__pycache__/FashionShopShell.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-08 FashionShopApp/ShellUI/__pycache__/FashionShopShell.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-08 FashionShopApp/ShellUI/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-08 FashionShopApp/ShellUI/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-08 FashionShopApp/Storage/FashionShop.py: -------------------------------------------------------------------------------- 1 | 2 | import pickle 3 | 4 | from Storage.StockItem import StockItem 5 | 6 | class FashionShop: 7 | 8 | show_instrumentation = False 9 | 10 | min_price = 0.5 11 | max_price = 500.0 12 | 13 | max_stock_add = 50 14 | 15 | def __init__(self): 16 | if FashionShop.show_instrumentation: 17 | print('** FashionShop __init__ called') 18 | self.__stock_dictionary = {} 19 | 20 | def save(self, filename): 21 | ''' 22 | Saves the fashion shop to the given filename 23 | Data is stored in binary as pickled file 24 | Exceptions will be raised if the save fails 25 | ''' 26 | if FashionShop.show_instrumentation: 27 | print('** FashionShop save called') 28 | with open(filename,'wb') as out_file: 29 | pickle.dump(self,out_file) 30 | 31 | @staticmethod 32 | def load(filename): 33 | ''' 34 | Loads the fashion shop from the given filename 35 | Data are stored in binary as pickled file 36 | Exceptions will be raised if the load fails 37 | ''' 38 | if FashionShop.show_instrumentation: 39 | print('** FashionShop load called') 40 | with open(filename,'rb') as input_file: 41 | result = pickle.load(input_file) 42 | 43 | # Now update the versions of the loaded stock items 44 | for stock_item in result.__stock_dictionary.values(): 45 | stock_item.check_version() 46 | return result 47 | 48 | 49 | def store_new_stock_item(self, stock_item): 50 | ''' 51 | Create a new item in the fashion shop 52 | The item is indexed on the stock_ref value 53 | Raises an exception if the item already 54 | exists 55 | ''' 56 | if FashionShop.show_instrumentation: 57 | print('** FashionShop store_new_stock_item called') 58 | if stock_item.stock_ref in self.__stock_dictionary: 59 | raise Exception('Item already present') 60 | self.__stock_dictionary[stock_item.stock_ref] = stock_item 61 | 62 | 63 | def find_stock_item(self, stock_ref): 64 | ''' 65 | Gets an item from the stock dictionary 66 | Returns None if there is no item for 67 | this key 68 | ''' 69 | if FashionShop.show_instrumentation: 70 | print('** FashionShop find_stock_item called') 71 | if stock_ref in self.__stock_dictionary: 72 | return self.__stock_dictionary[stock_ref] 73 | else: 74 | return None 75 | 76 | def __str__(self): 77 | if FashionShop.show_instrumentation: 78 | print('** FashionShop __str__ called') 79 | stock = map(str,self.__stock_dictionary.values()) 80 | stock_list = '\n'.join(stock) 81 | template = '''Items in Stock 82 | 83 | {0} 84 | ''' 85 | return template.format(stock_list) 86 | 87 | def find_matching_with_tags(self, search_tags): 88 | ''' 89 | Returns the stock items that contain 90 | the search_tags as a subset of their tags 91 | ''' 92 | if FashionShop.show_instrumentation: 93 | print('** FashionShop find_matching_tags called', search_tags) 94 | 95 | def match_tags(item): 96 | ''' 97 | Returns True if the tags in the item 98 | contain the search tags 99 | ''' 100 | return search_tags.issubset(item.tags) 101 | 102 | return filter(lambda item:search_tags.issubset(item.tags), self.__stock_dictionary.values()) 103 | # return filter(match_tags, self.__stock_dictionary.values()) 104 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-08 FashionShopApp/Storage/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-08 FashionShopApp/Storage/__pycache__/FashionShop.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-08 FashionShopApp/Storage/__pycache__/FashionShop.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-08 FashionShopApp/Storage/__pycache__/StockItem.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-08 FashionShopApp/Storage/__pycache__/StockItem.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-08 FashionShopApp/Storage/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-08 FashionShopApp/Storage/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-08 FashionShopApp/__pycache__/FashionShopShellUI.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-08 FashionShopApp/__pycache__/FashionShopShellUI.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-08 FashionShopApp/fashionshop.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-08 FashionShopApp/fashionshop.pickle -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/FashionShopShellUI.py: -------------------------------------------------------------------------------- 1 | # Loads a user interface class and a storage manager class 2 | # and then uses these to create an application 3 | 4 | # Get the module containing the user interface class 5 | # from the ShellUI package 6 | from ShellUI import FashionShopShell 7 | # Get the user interface manager class from this module 8 | ui = FashionShopShell.FashionShopShell 9 | 10 | # Get the module containing the data storage class 11 | # from the Storage package 12 | from Storage import FashionShop 13 | # Get the data manager class from the storage module 14 | shop = FashionShop.FashionShop 15 | 16 | # Now create an app from the user interface object 17 | # Give it the filename and the data manager class as 18 | # parameters 19 | app = ui(filename='fashionshop.pickle', storage_class=shop) 20 | 21 | # Now call the main_menu function on the app 22 | app.main_menu() 23 | 24 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/RunTests.py: -------------------------------------------------------------------------------- 1 | 2 | import unittest 3 | 4 | from Storage.StockItem import StockItem 5 | 6 | class TestShop(unittest.TestCase): 7 | 8 | def test_StockItem_init(self): 9 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 10 | self.assertEqual(item.stock_ref, 'Test') 11 | self.assertEqual(item.price, 10) 12 | self.assertEqual(item.stock_level, 0) 13 | self.assertEqual(item.tags, 'test:tag') 14 | 15 | def test_StockItem_add_stock(self): 16 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 17 | self.assertEqual(item.stock_level, 0) 18 | item.add_stock(10) 19 | self.assertEqual(item.stock_level, 10) 20 | with self.assertRaises(Exception): 21 | item.add_stock(-1) 22 | 23 | def test_StockItem_sell_stock(self): 24 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 25 | self.assertEqual(item.stock_level, 0) 26 | item.add_stock(10) 27 | self.assertEqual(item.stock_level, 10) 28 | item.sell_stock(2) 29 | self.assertEqual(item.stock_level, 8) 30 | 31 | 32 | unittest.main() 33 | 34 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/ShellUI/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-09 TestFashionShopApp/ShellUI/__init__.py -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/ShellUI/__pycache__/BTCInput.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-09 TestFashionShopApp/ShellUI/__pycache__/BTCInput.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/ShellUI/__pycache__/FashionShopShell.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-09 TestFashionShopApp/ShellUI/__pycache__/FashionShopShell.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/ShellUI/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-09 TestFashionShopApp/ShellUI/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/Storage/FashionShop.py: -------------------------------------------------------------------------------- 1 | 2 | import pickle 3 | 4 | from Storage.StockItem import StockItem 5 | 6 | class FashionShop: 7 | 8 | show_instrumentation = False 9 | 10 | min_price = 0.5 11 | max_price = 500.0 12 | 13 | max_stock_add = 50 14 | 15 | def __init__(self): 16 | if FashionShop.show_instrumentation: 17 | print('** FashionShop __init__ called') 18 | self.__stock_dictionary = {} 19 | 20 | def save(self, filename): 21 | ''' 22 | Saves the fashion shop to the given filename 23 | Data is stored in binary as pickled file 24 | Exceptions will be raised if the save fails 25 | ''' 26 | if FashionShop.show_instrumentation: 27 | print('** FashionShop save called') 28 | with open(filename,'wb') as out_file: 29 | pickle.dump(self,out_file) 30 | 31 | @staticmethod 32 | def load(filename): 33 | ''' 34 | Loads the fashion shop from the given filename 35 | Data are stored in binary as pickled file 36 | Exceptions will be raised if the load fails 37 | ''' 38 | if FashionShop.show_instrumentation: 39 | print('** FashionShop load called') 40 | with open(filename,'rb') as input_file: 41 | result = pickle.load(input_file) 42 | 43 | # Now update the versions of the loaded stock items 44 | for stock_item in result.__stock_dictionary.values(): 45 | stock_item.check_version() 46 | return result 47 | 48 | 49 | def store_new_stock_item(self, stock_item): 50 | ''' 51 | Create a new item in the fashion shop 52 | The item is indexed on the stock_ref value 53 | Raises an exception if the item already 54 | exists 55 | ''' 56 | if FashionShop.show_instrumentation: 57 | print('** FashionShop store_new_stock_item called') 58 | if stock_item.stock_ref in self.__stock_dictionary: 59 | raise Exception('Item already present') 60 | self.__stock_dictionary[stock_item.stock_ref] = stock_item 61 | 62 | 63 | def find_stock_item(self, stock_ref): 64 | ''' 65 | Gets an item from the stock dictionary 66 | Returns None if there is no item for 67 | this key 68 | ''' 69 | if FashionShop.show_instrumentation: 70 | print('** FashionShop find_stock_item called') 71 | if stock_ref in self.__stock_dictionary: 72 | return self.__stock_dictionary[stock_ref] 73 | else: 74 | return None 75 | 76 | def __str__(self): 77 | if FashionShop.show_instrumentation: 78 | print('** FashionShop __str__ called') 79 | stock = map(str,self.__stock_dictionary.values()) 80 | stock_list = '\n'.join(stock) 81 | template = '''Items in Stock 82 | 83 | {0} 84 | ''' 85 | return template.format(stock_list) 86 | 87 | def find_matching_with_tags(self, search_tags): 88 | ''' 89 | Returns the stock items that contain 90 | the search_tags as a subset of their tags 91 | ''' 92 | if FashionShop.show_instrumentation: 93 | print('** FashionShop find_matching_tags called', search_tags) 94 | 95 | def match_tags(item): 96 | ''' 97 | Returns True if the tags in the item 98 | contain the search tags 99 | ''' 100 | return search_tags.issubset(item.tags) 101 | 102 | return filter(lambda item:search_tags.issubset(item.tags), self.__stock_dictionary.values()) 103 | # return filter(match_tags, self.__stock_dictionary.values()) 104 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/Storage/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/Storage/__pycache__/FashionShop.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-09 TestFashionShopApp/Storage/__pycache__/FashionShop.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/Storage/__pycache__/StockItem.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-09 TestFashionShopApp/Storage/__pycache__/StockItem.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/Storage/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-09 TestFashionShopApp/Storage/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/Tests/Tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class TestShop(unittest.TestCase): 4 | 5 | def test_StockItem_init(self): 6 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 7 | self.assertEqual(item.stock_ref, 'Test') 8 | self.assertEqual(item.price, 10) 9 | self.assertEqual(item.stock_level, 0) 10 | 11 | def failing_test(self): 12 | self.assertEqual(1, 0) 13 | 14 | 15 | 16 | def ztest_StockItem_add_stock(self): 17 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 18 | self.assertEqual(item.stock_level, 0) 19 | item.add_stock(10) 20 | self.assertEqual(item.stock_level, 10) 21 | 22 | def ztest_StockItem_sell_stock(self): 23 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 24 | self.assertEqual(item.stock_level, 0) 25 | item.add_stock(10) 26 | self.assertEqual(item.stock_level, 10) 27 | item.sell_stock(2) 28 | self.assertEqual(item.stock_level, 8) 29 | 30 | 31 | 32 | print('bazinga') 33 | unittest.main() 34 | 35 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/Tests/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/Tests/__pycache__/Tests.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-09 TestFashionShopApp/Tests/__pycache__/Tests.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/Tests/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-09 TestFashionShopApp/Tests/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-09 TestFashionShopApp/fashionshop.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-09 TestFashionShopApp/fashionshop.pickle -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/FashionShopShellUI.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Starts a fashion Shop running with a Python Command Shell user interface 3 | 4 | Only runs if it is started as the main program 5 | ''' 6 | 7 | if __name__ == '__main__': 8 | # Loads a user interface class and a storage manager class 9 | # and then uses these to create an application 10 | 11 | # Get the module containing the user interface class 12 | # from the ShellUI package 13 | from ShellUI import FashionShopShell 14 | # Get the user interface manager class from this module 15 | ui = FashionShopShell.FashionShopShell 16 | 17 | # Get the module containing the data storage class 18 | # from the Storage package 19 | from Storage import FashionShop 20 | # Get the data manager class from the storage module 21 | shop = FashionShop.FashionShop 22 | 23 | # Now create an app from the user interface object 24 | # Give it the filename and the data manager class as 25 | # parameters 26 | app = ui(filename='fashionshop.pickle', storage_class=shop) 27 | 28 | # Now call the main_menu function on the app 29 | app.main_menu() 30 | 31 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/RunTests.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Runs unit tests on the Fashion Shop clases 3 | ''' 4 | 5 | 6 | import unittest 7 | 8 | from Storage.StockItem import StockItem 9 | 10 | class TestShop(unittest.TestCase): 11 | 12 | def test_StockItem_init(self): 13 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 14 | self.assertEqual(item.stock_ref, 'Test') 15 | self.assertEqual(item.price, 10) 16 | self.assertEqual(item.stock_level, 0) 17 | self.assertEqual(item.tags, 'test:tag') 18 | 19 | def test_StockItem_add_stock(self): 20 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 21 | self.assertEqual(item.stock_level, 0) 22 | item.add_stock(10) 23 | self.assertEqual(item.stock_level, 10) 24 | with self.assertRaises(Exception): 25 | item.add_stock(-1) 26 | 27 | def test_StockItem_sell_stock(self): 28 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 29 | self.assertEqual(item.stock_level, 0) 30 | item.add_stock(10) 31 | self.assertEqual(item.stock_level, 10) 32 | item.sell_stock(2) 33 | self.assertEqual(item.stock_level, 8) 34 | 35 | if __name__ == '__main__': 36 | unittest.main() 37 | 38 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/ShellUI/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Classes to implement a Python Command Shell vesrion 3 | of the Fashion Shop application 4 | ''' 5 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/ShellUI/__pycache__/BTCInput.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/ShellUI/__pycache__/BTCInput.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/ShellUI/__pycache__/FashionShopShell.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/ShellUI/__pycache__/FashionShopShell.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/ShellUI/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/ShellUI/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Storage/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Data storage classes for the Fshion Shop application 3 | ''' 4 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Storage/__pycache__/FashionShop.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Storage/__pycache__/FashionShop.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Storage/__pycache__/StockItem.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Storage/__pycache__/StockItem.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Storage/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Storage/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Tests/Tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class TestShop(unittest.TestCase): 4 | 5 | def test_StockItem_init(self): 6 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 7 | self.assertEqual(item.stock_ref, 'Test') 8 | self.assertEqual(item.price, 10) 9 | self.assertEqual(item.stock_level, 0) 10 | 11 | def failing_test(self): 12 | self.assertEqual(1, 0) 13 | 14 | 15 | 16 | def ztest_StockItem_add_stock(self): 17 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 18 | self.assertEqual(item.stock_level, 0) 19 | item.add_stock(10) 20 | self.assertEqual(item.stock_level, 10) 21 | 22 | def ztest_StockItem_sell_stock(self): 23 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 24 | self.assertEqual(item.stock_level, 0) 25 | item.add_stock(10) 26 | self.assertEqual(item.stock_level, 10) 27 | item.sell_stock(2) 28 | self.assertEqual(item.stock_level, 8) 29 | 30 | 31 | 32 | print('bazinga') 33 | unittest.main() 34 | 35 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Tests/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Tests/__pycache__/Tests.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Tests/__pycache__/Tests.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Tests/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/Tests/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/__pycache__/FashionShopShellUI.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/__pycache__/FashionShopShellUI.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/__pycache__/RunTests.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/__pycache__/RunTests.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/fashionshop.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/EG12-10 TestFashionShopApp Doc/fashionshop.pickle -------------------------------------------------------------------------------- /Ch 12 Python applications/people.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/people.pickle -------------------------------------------------------------------------------- /Ch 12 Python applications/test.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 12 Python applications/test.pickle -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-01 First Adding machine.py: -------------------------------------------------------------------------------- 1 | # EG13-01 First Adding machine 2 | 3 | from tkinter import * 4 | 5 | class Adder(object): 6 | ''' 7 | Implements an adding machine using the Tkinter GUI 8 | Call the method display to initiate the display 9 | ''' 10 | def display(self): 11 | ''' 12 | Display the user interface 13 | Returns when the interface is closed by the user 14 | ''' 15 | root = Tk() 16 | 17 | first_number_label = Label(root, text='First Number') 18 | first_number_label.grid(sticky=E, padx=5, pady=5, row=0, column=0) 19 | 20 | first_number_entry = Entry(root, width=10) 21 | first_number_entry.grid(padx=5, pady=5, row=0, column=1) 22 | 23 | second_number_label = Label(root, text='Second Number') 24 | second_number_label.grid(sticky=E, padx=5, pady=5, row=1, column=0) 25 | 26 | second_number_entry = Entry(root, width=10) 27 | second_number_entry.grid(padx=5, pady=5, row=1, column=1) 28 | 29 | def do_add(): 30 | first_number_text = first_number_entry.get() 31 | first_number = float(first_number_text) 32 | 33 | second_number_text = second_number_entry.get() 34 | second_number = float(second_number_text) 35 | 36 | result = first_number + second_number 37 | result_label.config(text = str(result)) 38 | 39 | add_button = Button(root,text='Add numbers', command=do_add) 40 | add_button.grid(sticky=E+W,row=2, padx=5, pady=5, column=0, columnspan=2) 41 | 42 | result_label = Label(root, text='Result') 43 | result_label.grid(sticky=E+W, padx=5, pady=5, row=3, column=0, columnspan=2) 44 | 45 | root.mainloop() 46 | 47 | if __name__ == '__main__': 48 | app = Adder() 49 | app.display() 50 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-02 Exception handler with messages.py: -------------------------------------------------------------------------------- 1 | # EG13-02 Exception handler with messages 2 | 3 | from tkinter import * 4 | 5 | class Adder(object): 6 | ''' 7 | Implements an adding machine using the Tkinter GUI 8 | Call the method display to initiate the display 9 | ''' 10 | def display(self): 11 | ''' 12 | Display the user interface 13 | Returns when the interface is closed by the user 14 | ''' 15 | root = Tk() 16 | 17 | first_number_label = Label(root, text='First Number') 18 | first_number_label.grid(sticky=E, padx=5, pady=5, row=0, column=0) 19 | 20 | first_number_entry = Entry(root, width=10) 21 | first_number_entry.grid(padx=5, pady=5, row=0, column=1) 22 | 23 | second_number_label = Label(root, text='Second Number') 24 | second_number_label.grid(sticky=E, padx=5, pady=5, row=1, column=0) 25 | 26 | second_number_entry = Entry(root, width=10) 27 | second_number_entry.grid(padx=5, pady=5, row=1, column=1) 28 | 29 | def do_add(): 30 | first_number_text = first_number_entry.get() 31 | try: 32 | first_number = float(first_number_text) 33 | except ValueError: 34 | result_label.config(text='Invalid first number') 35 | return 36 | 37 | second_number_text = second_number_entry.get() 38 | try: 39 | second_number = float(second_number_text) 40 | except ValueError: 41 | result_label.config(text='Invalid second number') 42 | return 43 | 44 | 45 | result = first_number + second_number 46 | result_label.config(text = str(result)) 47 | 48 | add_button = Button(root,text='Add numbers', command=do_add) 49 | add_button.grid(sticky=E+W,row=2, padx=5, pady=5, column=0, columnspan=2) 50 | 51 | result_label = Label(root, text='Result') 52 | result_label.grid(sticky=E+W, padx=5, pady=5, row=3, column=0, columnspan=2) 53 | 54 | root.mainloop() 55 | 56 | if __name__ == '__main__': 57 | app = Adder() 58 | app.display() 59 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-03 Adder with sensible messages.py: -------------------------------------------------------------------------------- 1 | # EG13-03 Adder with sensible messages 2 | 3 | from tkinter import * 4 | 5 | class Adder(object): 6 | ''' 7 | Implementes an adding machine using a the Tkinter GUI 8 | Call the method display to initiate the display 9 | ''' 10 | def display(self): 11 | ''' 12 | Display the user interface 13 | Returns when the interface is closed by the user 14 | ''' 15 | root = Tk() 16 | 17 | first_number_label = Label(root, text='First Number') 18 | first_number_label.grid(sticky=E, padx=5, pady=5, row=0, column=0) 19 | 20 | first_number_entry = Entry(root, width=10) 21 | first_number_entry.grid(padx=5, pady=5, row=0, column=1) 22 | 23 | second_number_label = Label(root, text='Second Number') 24 | second_number_label.grid(sticky=E, padx=5, pady=5, row=1, column=0) 25 | 26 | second_number_entry = Entry(root, width=10) 27 | second_number_entry.grid(padx=5, pady=5, row=1, column=1) 28 | 29 | def do_add(): 30 | error_message = '' 31 | first_number_text = first_number_entry.get() 32 | try: 33 | first_number = float(first_number_text) 34 | except ValueError: 35 | error_message = 'Invalid first number\n' 36 | 37 | second_number_text = second_number_entry.get() 38 | try: 39 | second_number = float(second_number_text) 40 | except ValueError: 41 | error_message = error_message + 'Invalid second number' 42 | 43 | if error_message != '': 44 | result_label.config(text=error_message) 45 | else: 46 | result = first_number + second_number 47 | result_label.config(text = str(result)) 48 | 49 | add_button = Button(root,text='Add numbers', command=do_add) 50 | add_button.grid(sticky=E+W,row=2, padx=5, pady=5, column=0, columnspan=2) 51 | 52 | result_label = Label(root, text='Result') 53 | result_label.grid(sticky=E+W, padx=5, pady=5, row=3, column=0, columnspan=2) 54 | 55 | root.mainloop() 56 | 57 | if __name__ == '__main__': 58 | app = Adder() 59 | app.display() 60 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-04 Adder with messagebox.py: -------------------------------------------------------------------------------- 1 | # EG13-04 Adder with messagebox 2 | 3 | from tkinter import * 4 | from tkinter import messagebox 5 | 6 | class Adder(object): 7 | ''' 8 | Implements an adding machine using the Tkinter GUI 9 | Call the method display to initiate the display 10 | ''' 11 | def display(self): 12 | ''' 13 | Display the user interface 14 | Returns when the interface is closed by the user 15 | ''' 16 | root = Tk() 17 | 18 | first_number_label = Label(root, text='First Number') 19 | first_number_label.grid(sticky=E, padx=5, pady=5, row=0, column=0) 20 | 21 | first_number_entry = Entry(root, width=10) 22 | first_number_entry.grid(padx=5, pady=5, row=0, column=1) 23 | 24 | second_number_label = Label(root, text='Second Number') 25 | second_number_label.grid(sticky=E, padx=5, pady=5, row=1, column=0) 26 | 27 | second_number_entry = Entry(root, width=10) 28 | second_number_entry.grid(padx=5, pady=5, row=1, column=1) 29 | 30 | def do_add(): 31 | error_message = '' 32 | first_number_text = first_number_entry.get() 33 | try: 34 | first_number = float(first_number_text) 35 | except ValueError: 36 | error_message = 'Invalid first number\n' 37 | 38 | second_number_text = second_number_entry.get() 39 | try: 40 | second_number = float(second_number_text) 41 | except ValueError: 42 | error_message = error_message + 'Invalid second number' 43 | 44 | if error_message != '': 45 | messagebox.showerror(title='Adder',message=error_message) 46 | else: 47 | result = first_number + second_number 48 | result_label.config(text = str(result)) 49 | 50 | add_button = Button(root,text='Add numbers', command=do_add) 51 | add_button.grid(sticky=E+W,row=2, padx=5, pady=5, column=0, columnspan=2) 52 | 53 | result_label = Label(root, text='Result') 54 | result_label.grid(sticky=E+W, padx=5, pady=5, row=3, column=0, columnspan=2) 55 | 56 | root.mainloop() 57 | 58 | if __name__ == '__main__': 59 | app = Adder() 60 | app.display() 61 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-05 TemperatureConverter Starter/TemperatureConverter.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Display a graphical user interface that lets users convert from temperature scales 3 | ''' 4 | 5 | from tkinter import * 6 | from tkinter import messagebox 7 | 8 | class Converter(object): 9 | ''' 10 | Displays a Tkinter user interface to convert between Fahrenheit and Centigrade 11 | Call the display function to display the converter on the screen 12 | ''' 13 | 14 | def display(self): 15 | ''' 16 | Displays the converter window 17 | When the window is closed this method completes 18 | ''' 19 | 20 | root = Tk() 21 | 22 | cent_label = Label(root, text='Centigrade:') 23 | cent_label.grid(row=0, column=0, padx=5, pady=5, stick=E) 24 | 25 | cent_entry = Entry(root, width=5) 26 | cent_entry.grid(row=0, column=1, padx=5, pady=5) 27 | 28 | fah_entry = Entry(root, width=5) 29 | fah_entry.grid(row=2, column=1, padx=5, pady=5) 30 | 31 | def fah_to_cent(): 32 | ''' 33 | Convert from Fahrenheit to centigrade and display the result 34 | ''' 35 | fah_string = fah_entry.get() 36 | fah_float = float(fah_string) 37 | result = (fah_float - 32) / 1.89 38 | cent_entry.delete(0) # remove the old text 39 | cent_entry.insert(0, str(result)) # insert the new text 40 | 41 | def cent_to_fah(): 42 | ''' 43 | Convert from centigrade to Fahrenheit and display the result 44 | ''' 45 | cent_string = cent_entry.get() 46 | cent_float = float(cent_string) 47 | result = cent_float * 1.8 + 32 48 | 49 | fah_to_cent_button = Button(root, text="Fah to cent", command=fah_to_cent) 50 | fah_to_cent_button.grid(row=1, column=0, padx=5, pady=5) 51 | 52 | root.mainloop() 53 | 54 | 55 | 56 | if __name__ == '__main__': 57 | app = Converter() 58 | app.display() 59 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-06 TemperatureConverter Complete/TemperatureConverter.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Display a graphical user interface that lets users convert from temperature scales 3 | ''' 4 | 5 | from tkinter import * 6 | from tkinter import messagebox 7 | 8 | class Converter(object): 9 | ''' 10 | Displays a Tkinter user interface to convert between Fahrenheit and Centigrade 11 | Call the display function to display the converter on the screen 12 | ''' 13 | 14 | def display(self): 15 | ''' 16 | Displays the converter window 17 | When the window is closed this method completes 18 | ''' 19 | 20 | root = Tk() 21 | 22 | cent_label = Label(root, text='Centigrade:') 23 | cent_label.grid(row=0, column=0, padx=5, pady=5, stick=E) 24 | 25 | cent_entry = Entry(root, width=5) 26 | cent_entry.grid(row=0, column=1, padx=5, pady=5) 27 | 28 | fah_label = Label(root, text='Fahrenheit:') 29 | fah_label.grid(row=2, column=0, padx=5, pady=5, stick=E) 30 | 31 | fah_entry = Entry(root, width=5) 32 | fah_entry.grid(row=2, column=1, padx=5, pady=5) 33 | 34 | def fah_to_cent(): 35 | ''' 36 | Convert from Fahrenheit to centigrade and display the result 37 | ''' 38 | fah_string = fah_entry.get() 39 | fah_float = float(fah_string) 40 | result = (fah_float - 32) / 1.89 41 | cent_entry.delete(0) # remove the old text 42 | cent_entry.insert(0, str(result)) # insert the new text 43 | 44 | def cent_to_fah(): 45 | ''' 46 | Convert from centigrade to Fahrenheit and display the result 47 | ''' 48 | cent_string = cent_entry.get() 49 | cent_float = float(cent_string) 50 | result = cent_float * 1.8 + 32 51 | 52 | 53 | fah_entry.delete(0) # remove the old text 54 | fah_entry.insert(0, str(result)) 55 | 56 | fah_to_cent_button = Button(root, text="Fah to cent", command=fah_to_cent) 57 | fah_to_cent_button.grid(row=1, column=0, padx=5, pady=5) 58 | 59 | cent_to_fah_button = Button(root, text="Cent to fah", command=cent_to_fah) 60 | cent_to_fah_button.grid(row=1, column=1, padx=5, pady=5) 61 | 62 | root.mainloop() 63 | 64 | 65 | 66 | if __name__ == '__main__': 67 | app = Converter() 68 | app.display() 69 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-07 Drawing program/Drawing.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Provides a simple drawing app 3 | Hold down the left button to draw 4 | Provides some single key commands: 5 | R-red G-green B-blue 6 | C-clear 7 | ''' 8 | 9 | from tkinter import * 10 | 11 | class Drawing(object): 12 | 13 | def display(self): 14 | root = Tk() 15 | 16 | canvas = Canvas(root, width=500, height=500) 17 | canvas.grid(row=0, column=0) 18 | 19 | draw_color = 'red' 20 | 21 | def mouse_move(event): 22 | ''' 23 | Draws a 10 pixel rectangle centered about the mouse 24 | position 25 | ''' 26 | canvas.create_rectangle(event.x-5, event.y-5, 27 | event.x+5, event.y+5, fill=draw_color, outline=draw_color) 28 | 29 | canvas.bind('', mouse_move) 30 | 31 | def key_press(event): 32 | nonlocal draw_color 33 | ch = event.char.upper() 34 | if ch == 'C': 35 | canvas.delete("all") 36 | elif ch == 'R': 37 | draw_color = 'red' 38 | elif ch == 'G': 39 | draw_color = 'green' 40 | elif ch == 'B': 41 | draw_color = 'blue' 42 | 43 | 44 | canvas.bind('', key_press) 45 | canvas.focus_set() 46 | 47 | root.mainloop() 48 | 49 | 50 | 51 | 52 | 53 | if __name__ == '__main__': 54 | app = Drawing() 55 | app.display() -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-08 StockEditDemo/StockItemEditDemo.py: -------------------------------------------------------------------------------- 1 | # EG13-08 StockItemEditDemo 2 | 3 | from tkinter import * 4 | from StockItem import StockItem 5 | from StockItemEditor import StockItemEditor 6 | 7 | item = StockItem('D001', 120, 8 | 'dress,color:red,loc:shop window,pattern:swirly,size:12,evening,long') 9 | 10 | root = Tk() 11 | 12 | stock_frame = StockItemEditor(root) 13 | stock_frame.frame.grid(row=0, column=0) 14 | 15 | def save_edit(): 16 | 17 | if not stock_frame.item_edited(item): 18 | print('not changed - no need to save') 19 | return 20 | 21 | stock_frame.get_from_editor(item) 22 | stock_frame.clear_editor() 23 | print(item) 24 | 25 | save_button = Button(root,text='Save', command=save_edit) 26 | save_button.grid(row=1, column=0) 27 | stock_frame.load_into_editor(item) 28 | root.mainloop() 29 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-08 StockEditDemo/StockItemEditor.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | from StockItem import StockItem 4 | 5 | class StockItemEditor(object): 6 | ''' 7 | Provides an editor for a StockItem 8 | The frame property gives the Tkinter frame 9 | that is used to display the editor 10 | ''' 11 | 12 | def __init__(self,root): 13 | ''' 14 | Create an instance of the editor. root provides 15 | the Tkinter root frame for the editor 16 | ''' 17 | self.frame = Frame(root,borderwidth=5) 18 | 19 | stock_ref_label = Label(self.frame,text='Stock ref:') 20 | stock_ref_label.grid(sticky=E, row=0, column=0, padx=5, pady=5) 21 | self._stock_ref_entry = Entry(self.frame, width=30) 22 | self._stock_ref_entry.grid(sticky=W, row=0, column=1, padx=5, pady=5) 23 | 24 | price_label = Label(self.frame,text='Price:') 25 | price_label.grid(sticky=E, row=1, column=0, padx=5, pady=5) 26 | self._price_entry = Entry(self.frame, width=30) 27 | self._price_entry.grid(sticky=W, row=1, column=1, padx=5, pady=5) 28 | 29 | self._stock_level_label = Label(self.frame,text='Stock level: 0') 30 | self._stock_level_label.grid( row=2, column=0, columnspan=2, padx=5, pady=5) 31 | 32 | tags_label = Label(self.frame,text='Tags:') 33 | tags_label.grid(sticky=E+N, row=3, column=0, padx=5, pady=5) 34 | 35 | self._tags_text = Text(self.frame, width=50, height=5) 36 | self._tags_text.grid(row=3, column=1, padx=5, pady=5) 37 | 38 | def load_into_editor(self, item): 39 | ''' 40 | Loads a StockItem into the editor display 41 | item is a reference to the StockItem 42 | being loaded into the display 43 | ''' 44 | self.clear_editor() 45 | self._stock_ref_entry.insert(0, item.stock_ref) 46 | self._price_entry.insert(0, str(item.price)) 47 | self._stock_level_label.config(text = 'Stock level : ' + str(item.stock_level)) 48 | self._tags_text.insert('0.0',item.text_tags) 49 | 50 | def get_from_editor(self,item): 51 | ''' 52 | Gets updated values from the screen 53 | item is a reference to the StockItem 54 | that will get the updated values 55 | Will raise an exception if the price entry 56 | cannot be converted into a number 57 | ''' 58 | item.set_price(int(self._price_entry.get())) 59 | item.stock_ref = self._stock_ref_entry.get() 60 | item.text_tags = self._tags_text.get('1.0',END) 61 | 62 | def item_edited(self, item): 63 | ''' 64 | Checks if there are any difference between the 65 | item supplied as a parameter and the 66 | item displayed on the screen 67 | Returns True if the item has been changed 68 | ''' 69 | if item.stock_ref != self._stock_ref_entry.get(): 70 | return True 71 | if item.price != float(self._price_entry.get()): 72 | return True 73 | if item.text_tags.strip() != self._tags_text.get('1.0',END).strip(): 74 | return True 75 | return False 76 | 77 | def clear_editor(self): 78 | ''' 79 | Clears the editor window 80 | ''' 81 | self._stock_ref_entry.delete(0, END) 82 | self._price_entry.delete(0, END) 83 | self._tags_text.delete('0.0', END) 84 | self._stock_level_label.config(text = 'Empty') 85 | 86 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-08 StockEditDemo/__pycache__/StockItem.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-08 StockEditDemo/__pycache__/StockItem.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-08 StockEditDemo/__pycache__/StockItemEditor.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-08 StockEditDemo/__pycache__/StockItemEditor.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-09 StockSelectDemo/StockItemSelector.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | from StockItem import StockItem 4 | 5 | class StockItemSelector(object): 6 | 7 | ''' 8 | Provides a frame that can be used to select 9 | a given stock item reference from a list 10 | of stock items 11 | The stock item list is delivered to the 12 | class via the populate_listbox method 13 | Selection events will trigger a call 14 | of got_selection in the object provided 15 | as the receiver of selection messages 16 | ''' 17 | 18 | def __init__(self, root, receiver): 19 | ''' 20 | Create an instance of the editor. root provides 21 | the Tkinter root frame for the editor 22 | receiver is a reference to the object that 23 | will receive messages when an item is selected 24 | The event will take the form of a call 25 | to the got_selection method in the 26 | receiver 27 | ''' 28 | 29 | assert hasattr(receiver, 'got_selection') 30 | 31 | self.receiver = receiver 32 | 33 | self.frame = Frame(root,borderwidth=5) 34 | 35 | self.listbox = Listbox(self.frame) 36 | self.listbox.grid(row=0, column=0) 37 | 38 | def on_select(event): 39 | ''' 40 | Bound to the selection event in the Listbox 41 | Finds the selected text and calls 42 | the message receiver to deliver the name 43 | that has been selected 44 | ''' 45 | lb = event.widget 46 | index = int(lb.curselection()[0]) 47 | receiver.got_selection(lb.get(index)) 48 | 49 | self.listbox.bind('<>', on_select) 50 | 51 | def populate_listbox(self, items): 52 | ''' 53 | Clears the selection Listbox and then 54 | populates it with the stock_ref values 55 | in the collection of items that have 56 | been supplied 57 | ''' 58 | self.listbox.delete(0, END) 59 | for item in items: 60 | self.listbox.insert(END,item.stock_ref) 61 | 62 | 63 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-09 StockSelectDemo/StockItemSelectorDemo.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | from StockItem import StockItem 4 | from StockItemSelector import StockItemSelector 5 | 6 | class MessageReceiver(object): 7 | 8 | def got_selection(self, stock_ref): 9 | print('Stock item selected :', stock_ref) 10 | 11 | 12 | stock_list = [] 13 | item_number = 1 14 | 15 | for i in range(1,100): 16 | stock_ref = 'D' + str(i) 17 | item = StockItem(stock_ref, 120, 18 | 'dress,color:red,loc:shop window,pattern:swirly,size:12,evening,long') 19 | stock_list.append(item) 20 | 21 | receiver = MessageReceiver() 22 | 23 | root = Tk() 24 | 25 | stock_selector = StockItemSelector(root, receiver) 26 | stock_selector.populate_listbox(stock_list) 27 | 28 | stock_selector.frame.grid(row=0, column=0) 29 | 30 | root.mainloop() -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-09 StockSelectDemo/__pycache__/StockItem.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-09 StockSelectDemo/__pycache__/StockItem.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-09 StockSelectDemo/__pycache__/StockItemSelector.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-09 StockSelectDemo/__pycache__/StockItemSelector.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/.vscode/settings (1).json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "C:/Users/Rob/AppData/Local/Programs/Python/Python36-32/python.exe" 3 | } -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "C:/Users/Rob/AppData/Local/Programs/Python/Python36-32/python.exe" 3 | } -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/FashionShopGUIApp.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Starts a fashion Shop running with a Python Command Shell user interface 3 | 4 | Only runs if it is started as the main program 5 | ''' 6 | 7 | if __name__ == '__main__': 8 | # Loads a user interface class and a storage manager class 9 | # and then uses these to create an application 10 | 11 | # Get the module containing the user interface class 12 | # from the ShellUI package 13 | from GUI import FashionShopGUI 14 | # Get the user interface manager class from this module 15 | ui = FashionShopGUI.FashionShopGUI 16 | 17 | # Get the module containing the data storage class 18 | # from the Storage package 19 | from Storage import FashionShop 20 | # Get the data manager class from the storage module 21 | shop = FashionShop.FashionShop 22 | 23 | # Now create an app from the user interface object 24 | # Give it the filename and the data manager class as 25 | # parameters 26 | app = ui(filename='fashionshop.pickle', storage_class=shop) 27 | 28 | # Now call the main_menu function on the app 29 | app.main_menu() 30 | 31 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/FashionShopGUIapp.pyw: -------------------------------------------------------------------------------- 1 | ''' 2 | Starts a fashion Shop running with a Python Command Shell user interface 3 | 4 | Only runs if it is started as the main program 5 | ''' 6 | 7 | if __name__ == '__main__': 8 | # Loads a user interface class and a storage manager class 9 | # and then uses these to create an application 10 | 11 | # Get the module containing the user interface class 12 | # from the ShellUI package 13 | from GUI import FashionShopGUI 14 | # Get the user interface manager class from this module 15 | ui = FashionShopGUI.FashionShopGUI 16 | 17 | # Get the module containing the data storage class 18 | # from the Storage package 19 | from Storage import FashionShop 20 | # Get the data manager class from the storage module 21 | shop = FashionShop.FashionShop 22 | 23 | # Now create an app from the user interface object 24 | # Give it the filename and the data manager class as 25 | # parameters 26 | app = ui(filename='fashionshop.pickle', storage_class=shop) 27 | 28 | # Now call the main_menu function on the app 29 | app.main_menu() 30 | 31 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/FashionShopShellUIApp.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Starts a fashion Shop running with a Python Command Shell user interface 3 | 4 | Only runs if it is started as the main program 5 | ''' 6 | 7 | if __name__ == '__main__': 8 | # Loads a user interface class and a storage manager class 9 | # and then uses these to create an application 10 | 11 | # Get the module containing the user interface class 12 | # from the ShellUI package 13 | from ShellUI import FashionShopShell 14 | # Get the user interface manager class from this module 15 | ui = FashionShopShell.FashionShopShell 16 | 17 | # Get the module containing the data storage class 18 | # from the Storage package 19 | from Storage import FashionShop 20 | # Get the data manager class from the storage module 21 | shop = FashionShop.FashionShop 22 | 23 | # Now create an app from the user interface object 24 | # Give it the filename and the data manager class as 25 | # parameters 26 | app = ui(filename='fashionshop.pickle', storage_class=shop) 27 | 28 | # Now call the main_menu function on the app 29 | app.main_menu() 30 | 31 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/StockItemEditor (1).py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | from Storage.StockItem import StockItem 4 | 5 | class StockItemEditor(object): 6 | ''' 7 | Provides an editor for a StockItem 8 | The frame property gives the Tkinter frame 9 | that is used to display the editor 10 | ''' 11 | 12 | def __init__(self,root): 13 | ''' 14 | Create an instance of the editor. root provides 15 | the Tkinter root frame for the editor 16 | ''' 17 | self.frame = Frame(root,borderwidth=5) 18 | 19 | stock_ref_label = Label(self.frame,text='Stock ref:') 20 | stock_ref_label.grid(sticky=E, row=0, column=0, padx=5, pady=5) 21 | self._stock_ref_entry = Entry(self.frame, width=30) 22 | self._stock_ref_entry.grid(sticky=W, row=0, column=1, padx=5, pady=5) 23 | 24 | price_label = Label(self.frame,text='Price:') 25 | price_label.grid(sticky=E, row=1, column=0, padx=5, pady=5) 26 | self._price_entry = Entry(self.frame, width=30) 27 | self._price_entry.grid(sticky=W, row=1, column=1, padx=5, pady=5) 28 | 29 | self._stock_level_label = Label(self.frame,text='Stock level: 0') 30 | self._stock_level_label.grid( row=2, column=0, columnspan=2, padx=5, pady=5) 31 | 32 | tags_label = Label(self.frame,text='Tags:') 33 | tags_label.grid(sticky=E+N, row=3, column=0, padx=5, pady=5) 34 | 35 | self._tags_text = Text(self.frame, width=70, height=5) 36 | self._tags_text.grid(row=3, column=1, padx=5, pady=5) 37 | 38 | def load_into_editor(self, item): 39 | ''' 40 | Loads a StockItem into the editor display 41 | item is a reference to the StockItem 42 | being loaded into the display 43 | ''' 44 | self.clear_editor() 45 | self._stock_ref_entry.insert(0, item.stock_ref) 46 | self._price_entry.insert(0, str(item.price)) 47 | self._stock_level_label.config(text = 'Stock level : ' + str(item.stock_level)) 48 | self._tags_text.insert('0.0',item.text_tags) 49 | 50 | def get_from_editor(self,item): 51 | ''' 52 | Gets updated values from the screen 53 | item is a reference to the StockItem 54 | that will get the updated values 55 | Will raise an exception if the price entry 56 | cannot be converted into a number 57 | ''' 58 | item.set_price(int(self._price_entry.get())) 59 | item.stock_ref = self._stock_ref_entry.get() 60 | item.text_tags = self._tags_text.get('1.0',END) 61 | 62 | def item_edited(self, item): 63 | ''' 64 | Checks if there are any difference between the 65 | item supplied as a parameter and the 66 | item displayed on the screen 67 | Returns True if the item has been changed 68 | ''' 69 | if item.stock_ref != self._stock_ref_entry.get(): 70 | return True 71 | if item.price != float(self._price_entry.get()): 72 | return True 73 | if item.text_tags.strip() != self._tags_text.get('1.0',END).strip(): 74 | return True 75 | return False 76 | 77 | def clear_editor(self): 78 | ''' 79 | Clears the editor window 80 | ''' 81 | self._stock_ref_entry.delete(0, END) 82 | self._price_entry.delete(0, END) 83 | self._tags_text.delete('0.0', END) 84 | self._stock_level_label.config(text = 'Empty') 85 | 86 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/StockItemEditor.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | from Storage.StockItem import StockItem 4 | 5 | class StockItemEditor(object): 6 | ''' 7 | Provides an editor for a StockItem 8 | The frame property gives the Tkinter frame 9 | that is used to display the editor 10 | ''' 11 | 12 | def __init__(self,root): 13 | ''' 14 | Create an instance of the editor. root provides 15 | the Tkinter root frame for the editor 16 | ''' 17 | self.frame = Frame(root,borderwidth=5) 18 | 19 | stock_ref_label = Label(self.frame,text='Stock ref:') 20 | stock_ref_label.grid(sticky=E, row=0, column=0, padx=5, pady=5) 21 | self._stock_ref_entry = Entry(self.frame, width=30) 22 | self._stock_ref_entry.grid(sticky=W, row=0, column=1, padx=5, pady=5) 23 | 24 | price_label = Label(self.frame,text='Price:') 25 | price_label.grid(sticky=E, row=1, column=0, padx=5, pady=5) 26 | self._price_entry = Entry(self.frame, width=30) 27 | self._price_entry.grid(sticky=W, row=1, column=1, padx=5, pady=5) 28 | 29 | self._stock_level_label = Label(self.frame,text='Stock level: 0') 30 | self._stock_level_label.grid( row=2, column=0, columnspan=2, padx=5, pady=5) 31 | 32 | tags_label = Label(self.frame,text='Tags:') 33 | tags_label.grid(sticky=E+N, row=3, column=0, padx=5, pady=5) 34 | 35 | self._tags_text = Text(self.frame, width=70, height=5) 36 | self._tags_text.grid(row=3, column=1, padx=5, pady=5) 37 | 38 | def load_into_editor(self, item): 39 | ''' 40 | Loads a StockItem into the editor display 41 | item is a reference to the StockItem 42 | being loaded into the display 43 | ''' 44 | self.clear_editor() 45 | self._stock_ref_entry.insert(0, item.stock_ref) 46 | self._price_entry.insert(0, str(item.price)) 47 | self._stock_level_label.config(text = 'Stock level : ' + str(item.stock_level)) 48 | self._tags_text.insert('0.0',item.text_tags) 49 | 50 | def get_from_editor(self,item): 51 | ''' 52 | Gets updated values from the screen 53 | item is a reference to the StockItem 54 | that will get the updated values 55 | Will raise an exception if the price entry 56 | cannot be converted into a number 57 | ''' 58 | item.set_price(int(self._price_entry.get())) 59 | item.stock_ref = self._stock_ref_entry.get() 60 | item.text_tags = self._tags_text.get('1.0',END) 61 | 62 | def item_edited(self, item): 63 | ''' 64 | Checks if there are any difference between the 65 | item supplied as a parameter and the 66 | item displayed on the screen 67 | Returns True if the item has been changed 68 | ''' 69 | if item.stock_ref != self._stock_ref_entry.get(): 70 | return True 71 | if item.price != float(self._price_entry.get()): 72 | return True 73 | if item.text_tags.strip() != self._tags_text.get('1.0',END).strip(): 74 | return True 75 | return False 76 | 77 | def clear_editor(self): 78 | ''' 79 | Clears the editor window 80 | ''' 81 | self._stock_ref_entry.delete(0, END) 82 | self._price_entry.delete(0, END) 83 | self._tags_text.delete('0.0', END) 84 | self._stock_level_label.config(text = 'Empty') 85 | 86 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/StockItemSelector (1).py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | from Storage.StockItem import StockItem 4 | 5 | class StockItemSelector(object): 6 | 7 | ''' 8 | Provides a frame that can be used to select 9 | a given stock item reference from a list 10 | of stock items 11 | The stock item list is delivered to the 12 | class via the populate_listbox method 13 | Selection events will trigger a call 14 | of got_selection in the object provided 15 | as the receiver of selection messages 16 | ''' 17 | 18 | def __init__(self, root, receiver): 19 | ''' 20 | Create an instance of the editor. root provides 21 | the Tkinter root frame for the editor 22 | receiver is a reference to the object that 23 | will receive messages when an item is selected 24 | The event will take the form of a call 25 | to the got_selection method in the 26 | receiver 27 | ''' 28 | 29 | assert hasattr(receiver, 'got_selection') 30 | 31 | self.receiver = receiver 32 | 33 | self.frame = Frame(root,borderwidth=5) 34 | 35 | self.listbox = Listbox(self.frame, height=20) 36 | self.listbox.grid(row=0, column=0) 37 | 38 | def on_select(event): 39 | ''' 40 | Bound to the selection event in the Listbox 41 | Finds the selected text and calls 42 | the message receiver to deliver the name 43 | that has been selected 44 | ''' 45 | lb = event.widget 46 | index = int(lb.curselection()[0]) 47 | receiver.got_selection(lb.get(index)) 48 | 49 | self.listbox.bind('<>', on_select) 50 | 51 | def populate_listbox(self, items): 52 | ''' 53 | Clears the selection Listbox and then 54 | populates it with the stock_ref values 55 | in the collection of items that have 56 | been supplied 57 | ''' 58 | self.listbox.delete(0, END) 59 | for item in items: 60 | self.listbox.insert(END,item.stock_ref) 61 | 62 | 63 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/StockItemSelector.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | from Storage.StockItem import StockItem 4 | 5 | class StockItemSelector(object): 6 | 7 | ''' 8 | Provides a frame that can be used to select 9 | a given stock item reference from a list 10 | of stock items 11 | The stock item list is delivered to the 12 | class via the populate_listbox method 13 | Selection events will trigger a call 14 | of got_selection in the object provided 15 | as the receiver of selection messages 16 | ''' 17 | 18 | def __init__(self, root, receiver): 19 | ''' 20 | Create an instance of the editor. root provides 21 | the Tkinter root frame for the editor 22 | receiver is a reference to the object that 23 | will receive messages when an item is selected 24 | The event will take the form of a call 25 | to the got_selection method in the 26 | receiver 27 | ''' 28 | 29 | assert hasattr(receiver, 'got_selection') 30 | 31 | self.receiver = receiver 32 | 33 | self.frame = Frame(root,borderwidth=5) 34 | 35 | self.listbox = Listbox(self.frame, height=20) 36 | self.listbox.grid(row=0, column=0) 37 | 38 | def on_select(event): 39 | ''' 40 | Bound to the selection event in the Listbox 41 | Finds the selected text and calls 42 | the message receiver to deliver the name 43 | that has been selected 44 | ''' 45 | lb = event.widget 46 | index = int(lb.curselection()[0]) 47 | receiver.got_selection(lb.get(index)) 48 | 49 | self.listbox.bind('<>', on_select) 50 | 51 | def populate_listbox(self, items): 52 | ''' 53 | Clears the selection Listbox and then 54 | populates it with the stock_ref values 55 | in the collection of items that have 56 | been supplied 57 | ''' 58 | self.listbox.delete(0, END) 59 | for item in items: 60 | self.listbox.insert(END,item.stock_ref) 61 | 62 | 63 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__init__ (1).py: -------------------------------------------------------------------------------- 1 | ''' 2 | Classes to implement a Graphical User Interface vesrion 3 | of the Fashion Shop application 4 | ''' 5 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Classes to implement a Graphical User Interface vesrion 3 | of the Fashion Shop application 4 | ''' 5 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/FashionShopGUI.cpython-36 (1).pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/FashionShopGUI.cpython-36 (1).pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/FashionShopGUI.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/FashionShopGUI.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/StockItemEditor.cpython-36 (1).pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/StockItemEditor.cpython-36 (1).pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/StockItemEditor.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/StockItemEditor.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/StockItemSelector.cpython-36 (1).pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/StockItemSelector.cpython-36 (1).pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/StockItemSelector.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/StockItemSelector.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/__init__.cpython-36 (1).pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/__init__.cpython-36 (1).pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/GUI/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/RunTests.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Runs unit tests on the Fashion Shop clases 3 | ''' 4 | 5 | 6 | import unittest 7 | 8 | from Storage.StockItem import StockItem 9 | 10 | class TestShop(unittest.TestCase): 11 | 12 | def test_StockItem_init(self): 13 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 14 | self.assertEqual(item.stock_ref, 'Test') 15 | self.assertEqual(item.price, 10) 16 | self.assertEqual(item.stock_level, 0) 17 | self.assertEqual(item.tags, 'test:tag') 18 | 19 | def test_StockItem_add_stock(self): 20 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 21 | self.assertEqual(item.stock_level, 0) 22 | item.add_stock(10) 23 | self.assertEqual(item.stock_level, 10) 24 | with self.assertRaises(Exception): 25 | item.add_stock(-1) 26 | 27 | def test_StockItem_sell_stock(self): 28 | item = StockItem(stock_ref='Test', price=10, tags='test:tag') 29 | self.assertEqual(item.stock_level, 0) 30 | item.add_stock(10) 31 | self.assertEqual(item.stock_level, 10) 32 | item.sell_stock(2) 33 | self.assertEqual(item.stock_level, 8) 34 | 35 | if __name__ == '__main__': 36 | unittest.main() 37 | 38 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/FashionShopShellUI (1).py: -------------------------------------------------------------------------------- 1 | ''' 2 | Starts a fashion Shop running with a Python Command Shell user interface 3 | 4 | Only runs if it is started as the main program 5 | ''' 6 | 7 | if __name__ == '__main__': 8 | # Loads a user interface class and a storage manager class 9 | # and then uses these to create an application 10 | 11 | # Get the module containing the user interface class 12 | # from the ShellUI package 13 | from ShellUI import FashionShopShell 14 | # Get the user interface manager class from this module 15 | ui = FashionShopShell.FashionShopShell 16 | 17 | # Get the module containing the data storage class 18 | # from the Storage package 19 | from Storage import FashionShop 20 | # Get the data manager class from the storage module 21 | shop = FashionShop.FashionShop 22 | 23 | # Now create an app from the user interface object 24 | # Give it the filename and the data manager class as 25 | # parameters 26 | app = ui(filename='fashionshop.pickle', storage_class=shop) 27 | 28 | # Now call the main_menu function on the app 29 | app.main_menu() 30 | 31 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/FashionShopShellUI.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Starts a fashion Shop running with a Python Command Shell user interface 3 | 4 | Only runs if it is started as the main program 5 | ''' 6 | 7 | if __name__ == '__main__': 8 | # Loads a user interface class and a storage manager class 9 | # and then uses these to create an application 10 | 11 | # Get the module containing the user interface class 12 | # from the ShellUI package 13 | from ShellUI import FashionShopShell 14 | # Get the user interface manager class from this module 15 | ui = FashionShopShell.FashionShopShell 16 | 17 | # Get the module containing the data storage class 18 | # from the Storage package 19 | from Storage import FashionShop 20 | # Get the data manager class from the storage module 21 | shop = FashionShop.FashionShop 22 | 23 | # Now create an app from the user interface object 24 | # Give it the filename and the data manager class as 25 | # parameters 26 | app = ui(filename='fashionshop.pickle', storage_class=shop) 27 | 28 | # Now call the main_menu function on the app 29 | app.main_menu() 30 | 31 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__init__ (1).py: -------------------------------------------------------------------------------- 1 | ''' 2 | Classes to implement a Python Command Shell vesrion 3 | of the Fashion Shop application 4 | ''' 5 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Classes to implement a Python Command Shell vesrion 3 | of the Fashion Shop application 4 | ''' 5 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__pycache__/BTCInput.cpython-36 (1).pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__pycache__/BTCInput.cpython-36 (1).pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__pycache__/BTCInput.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__pycache__/BTCInput.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__pycache__/FashionShopShell.cpython-36 (1).pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__pycache__/FashionShopShell.cpython-36 (1).pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__pycache__/FashionShopShell.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__pycache__/FashionShopShell.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__pycache__/__init__.cpython-36 (1).pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__pycache__/__init__.cpython-36 (1).pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/ShellUI/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__init__ (1).py: -------------------------------------------------------------------------------- 1 | ''' 2 | Data storage classes for the Fshion Shop application 3 | ''' 4 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Data storage classes for the Fshion Shop application 3 | ''' 4 | -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__pycache__/FashionShop.cpython-36 (1).pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__pycache__/FashionShop.cpython-36 (1).pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__pycache__/FashionShop.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__pycache__/FashionShop.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__pycache__/StockItem.cpython-36 (1).pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__pycache__/StockItem.cpython-36 (1).pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__pycache__/StockItem.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__pycache__/StockItem.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__pycache__/__init__.cpython-36 (1).pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__pycache__/__init__.cpython-36 (1).pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/Storage/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/__pycache__/FashionShopShellUI.cpython-36 (1).pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/__pycache__/FashionShopShellUI.cpython-36 (1).pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/__pycache__/FashionShopShellUI.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/__pycache__/FashionShopShellUI.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/__pycache__/RunTests.cpython-36 (1).pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/__pycache__/RunTests.cpython-36 (1).pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/__pycache__/RunTests.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/__pycache__/RunTests.cpython-36.pyc -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/fashionshop (1).pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/fashionshop (1).pickle -------------------------------------------------------------------------------- /Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/fashionshop.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 13 Python and Graphical User Interfaces/EG13-10 FashionShop/fashionshop.pickle -------------------------------------------------------------------------------- /Ch 14 Python programs as network clients/EG14-01 Receive packets on port 10001 from another machine.py: -------------------------------------------------------------------------------- 1 | # EG14-01 Receive packets on port 10001 from another machine 2 | 3 | import socket 4 | 5 | host_name = socket.gethostname() 6 | host_ip = socket.gethostbyname(host_name) 7 | print('The ip address of this computer is:', host_ip) 8 | 9 | listen_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 10 | listen_address = (host_ip, 10006) 11 | 12 | listen_socket.bind(listen_address) 13 | 14 | print('Listening:') 15 | 16 | while(True): 17 | reply = listen_socket.recvfrom(4096) 18 | print(reply) 19 | -------------------------------------------------------------------------------- /Ch 14 Python programs as network clients/EG14-02 Send packets on port 10001 to another machine.py: -------------------------------------------------------------------------------- 1 | # EG14-02 Send packets on port 10001 to another machine 2 | 3 | import socket 4 | import time 5 | 6 | # You will need to chnge this to the address 7 | # of the machine you are sending to 8 | target_ip = '192.168.1.55' 9 | 10 | socket_number = 10006 11 | 12 | send_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 13 | destination_address = (target_ip, socket_number) 14 | 15 | while(True): 16 | print('sending') 17 | send_socket.sendto(b'hello from me', destination_address) 18 | time.sleep(2) 19 | -------------------------------------------------------------------------------- /Ch 14 Python programs as network clients/EG14-03 Web page reader.py: -------------------------------------------------------------------------------- 1 | # EG14-03 Web page reader 2 | 3 | import urllib.request 4 | 5 | url = 'https://www.robmiles.com' 6 | 7 | req = urllib.request.urlopen(url) 8 | for line in req: 9 | print(line) 10 | -------------------------------------------------------------------------------- /Ch 14 Python programs as network clients/EG14-04 Python ElementTree.py: -------------------------------------------------------------------------------- 1 | # EG14-04 Python ElementTree 2 | 3 | import xml.etree.ElementTree as ElementTree 4 | 5 | rss_text = ''' 6 | 7 | 8 | 9 | robmiles.com 10 | 11 | 12 | 13 | Water Meter Day 14 | 15 | Life 16 | 17 | 18 | 19 | 20 | 21 | 22 | Python now in Visual Studio 2017 23 | 24 | Python 25 | Visual Studio 26 | 27 | 28 | 29 | 30 | 31 | 32 | ''' 33 | 34 | doc = ElementTree.fromstring(rss_text) 35 | for item in doc.iter('item'): 36 | title = item.find('title').text 37 | print(title.strip()) 38 | description = item.find('description').text 39 | print(' ',description.strip()) 40 | -------------------------------------------------------------------------------- /Ch 14 Python programs as network clients/EG14-05 RSS Feed reader.py: -------------------------------------------------------------------------------- 1 | # EG14-05 RSS Feed reader 2 | 3 | import urllib.request 4 | import xml.etree.ElementTree as ElementTree 5 | 6 | url = 'https://www.robmiles.com/journal/rss.xml' 7 | url = "http://feeds.bbci.co.uk/news/rss.xml" 8 | url = "http://www.huffingtonpost.co.uk/feeds/index.xml" 9 | url = "http://feeds.reuters.com/reuters/UKTopNews" 10 | 11 | req = urllib.request.urlopen(url) 12 | page=req.read() 13 | 14 | doc = ElementTree.fromstring(page) 15 | 16 | for item in doc.iter('item'): 17 | title = item.find('title').text 18 | print(title.strip()) 19 | description = item.find('description').text 20 | print(' ',description.strip()) 21 | -------------------------------------------------------------------------------- /Ch 14 Python programs as network clients/EG14-06 Weather Feed Reader/EG14-06 Weather Feed Reader.py: -------------------------------------------------------------------------------- 1 | import urllib.request 2 | import xml.etree.ElementTree 3 | 4 | # EG14-06 Weather Feed Reader 5 | 6 | def get_weather_temp(latitude,longitude): 7 | address = 'http://forecast.weather.gov/MapClick.php' 8 | query = '?lat={0}&lon={1}&unit=0&lg=english&FcstType=dwml'.\ 9 | format(latitude,longitude) 10 | req=urllib.request.urlopen(address+query) 11 | page=req.read() 12 | doc=xml.etree.ElementTree.fromstring(page) 13 | for d in doc.iter('temperature'): 14 | if d.get('type') == 'apparent': 15 | text_temp_value = d.find('value').text 16 | return int(text_temp_value) 17 | 18 | 19 | def get_weather_desciption(latitude,longitude): 20 | ''' 21 | Uses forecast.weather.gov to get the weather 22 | for the specified latitude and longitude 23 | ''' 24 | address = 'http://forecast.weather.gov/MapClick.php' 25 | query = '?lat={0}&lon={1}&unit=0&lg=english&FcstType=dwml'.\ 26 | format(latitude,longitude) 27 | req=urllib.request.urlopen(address+query) 28 | page=req.read() 29 | doc=xml.etree.ElementTree.fromstring(page) 30 | for d in doc.iter('data'): 31 | if d.get('type') == 'current observations': 32 | param = d.find('parameters') 33 | weather = param.find('weather') 34 | conditions = weather.find('weather-conditions') 35 | return conditions.get('weather-summary') 36 | 37 | if __name__ == '__main__': 38 | temp = get_weather_temp(latitude=47.61, longitude=-122.33) 39 | print('The temperature is:', temp) 40 | temp = get_weather_desciption(latitude=47.61, longitude=-122.33) 41 | print('The weather is:', temp) 42 | 43 | -------------------------------------------------------------------------------- /Ch 15 Python programs as network servers/EG15-01 Tiny socket web server.py: -------------------------------------------------------------------------------- 1 | # EG15-01 Tiny socket web server 2 | 3 | import socket 4 | 5 | host_ip = 'localhost' 6 | host_socket = 8080 7 | 8 | full_address = 'http://' + host_ip + ':' + str(host_socket) 9 | 10 | print('Open your browser and connect to: ', full_address) 11 | 12 | listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 13 | listen_address = (host_ip, host_socket) 14 | 15 | listen_socket.bind(listen_address) 16 | listen_socket.listen() 17 | 18 | connection, address = listen_socket.accept() 19 | print('Got connection from: ', address) 20 | 21 | network_message_bytes = connection.recv(1024) 22 | html_request_string = network_message_bytes.decode() 23 | print(html_request_string) 24 | 25 | status_string = 'HTTP/1.1 200 OK' 26 | 27 | header_string = '''Content-Type: text/html; charset=UTF-8 28 | Connection: close 29 | 30 | ''' 31 | 32 | content_string = ''' 33 | 34 |

hello from our tiny server

35 | 36 | 37 | ''' 38 | 39 | response_string = status_string + header_string + content_string 40 | 41 | response_bytes = response_string.encode() 42 | 43 | connection.send(response_bytes) 44 | 45 | connection.close() 46 | -------------------------------------------------------------------------------- /Ch 15 Python programs as network servers/EG15-02 Python web server.py: -------------------------------------------------------------------------------- 1 | # EG15-02 Python web server 2 | 3 | import http.server 4 | 5 | class webServerHandler(http.server.BaseHTTPRequestHandler): 6 | 7 | def do_GET(self): 8 | ''' 9 | This method is called when the server receives 10 | a GET requests from the client 11 | It sends a fixed message back to the client 12 | ''' 13 | self.send_response(200) 14 | self.send_header('Content-type','text/html') 15 | self.end_headers() 16 | 17 | message_text = ''' 18 | 19 |

hello from the Python server

20 | 21 | 22 | ''' 23 | message_bytes = message_text.encode() 24 | 25 | self.wfile.write(message_bytes) 26 | return 27 | 28 | host_socket = 8080 29 | host_ip = 'localhost' 30 | 31 | host_address = (host_ip, host_socket) 32 | 33 | my_server = http.server.HTTPServer(host_address, webServerHandler) 34 | my_server.serve_forever() 35 | 36 | -------------------------------------------------------------------------------- /Ch 15 Python programs as network servers/EG15-03 Python web page server/EG15-03 Python web page server.py: -------------------------------------------------------------------------------- 1 | # EG15-03 Python web page server 2 | 3 | import http.server 4 | 5 | class WebServerHandler(http.server.BaseHTTPRequestHandler): 6 | 7 | def do_GET(self): 8 | ''' 9 | This method is called when the server receives 10 | a GET requests from the client 11 | It opens a file with the requested path 12 | and sends back the contents 13 | ''' 14 | self.send_response(200) 15 | self.send_header('Content-type','text/html') 16 | self.end_headers() 17 | 18 | # trim off the leading / character in the path 19 | file_path = self.path[1:] 20 | 21 | with open(file_path,'r') as input_file: 22 | message_text = input_file.read() 23 | 24 | message_bytes = message_text.encode() 25 | 26 | self.wfile.write(message_bytes) 27 | 28 | return 29 | 30 | host_socket = 8080 31 | host_ip = 'localhost' 32 | 33 | host_address = (host_ip, host_socket) 34 | 35 | my_server = http.server.HTTPServer(host_address, WebServerHandler) 36 | my_server.serve_forever() 37 | 38 | -------------------------------------------------------------------------------- /Ch 15 Python programs as network servers/EG15-03 Python web page server/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |

This is the index page for our tiny site.

4 | This is another page 5 | 6 | -------------------------------------------------------------------------------- /Ch 15 Python programs as network servers/EG15-03 Python web page server/page.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |

This is another page in our tiny web site.

4 | This takes us back to the index 5 | -------------------------------------------------------------------------------- /Ch 15 Python programs as network servers/EG15-04 Full Python web page server/EG15-04 Full Python web page server.py: -------------------------------------------------------------------------------- 1 | # EG15-04 Full Python web page server 2 | 3 | import http.server 4 | 5 | host_socket = 8080 6 | host_ip = 'localhost' 7 | 8 | host_address = (host_ip, host_socket) 9 | 10 | my_server = http.server.HTTPServer(host_address, 11 | http.server.SimpleHTTPRequestHandler) 12 | my_server.serve_forever() 13 | -------------------------------------------------------------------------------- /Ch 15 Python programs as network servers/EG15-04 Full Python web page server/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |

This is the index page for our tiny site.

4 | This is another page 5 | 6 | -------------------------------------------------------------------------------- /Ch 15 Python programs as network servers/EG15-04 Full Python web page server/page.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |

This is another page in our tiny web site.

5 | This takes us back to the index 6 | 7 | -------------------------------------------------------------------------------- /Ch 15 Python programs as network servers/EG15-04 Full Python web page server/picture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 15 Python programs as network servers/EG15-04 Full Python web page server/picture.jpg -------------------------------------------------------------------------------- /Ch 15 Python programs as network servers/EG15-05 Web message board/EG15-05 Web message board.py: -------------------------------------------------------------------------------- 1 | # EG15-05 Web message board 2 | 3 | import http.server 4 | import socketserver 5 | import urllib 6 | 7 | messages = [] 8 | 9 | class webServerHandler(http.server.BaseHTTPRequestHandler): 10 | 11 | def make_page(self): 12 | all_messages = '
\n'.join(messages) 13 | page = ''' 14 | 15 |

Tiny Message Board

16 |

Messages

17 |

{0}

18 |

New Message

19 |
20 | 21 | 22 |
23 |
24 | 25 |
26 | 27 | ''' 28 | return page.format(all_messages) 29 | 30 | def do_GET(self): 31 | self.send_response(200) 32 | self.send_header('Content-type','text/html') 33 | self.end_headers() 34 | 35 | message_text = self.make_page() 36 | 37 | print(message_text) 38 | 39 | message_bytes = message_text.encode() 40 | 41 | self.wfile.write(message_bytes) 42 | return 43 | 44 | def do_POST(self): 45 | 46 | length = int(self.headers['Content-Length']) 47 | 48 | post_body_bytes = self.rfile.read(length) 49 | 50 | post_body_text = post_body_bytes.decode() 51 | 52 | query_strings = urllib.parse.parse_qs(post_body_text, 53 | keep_blank_values=True) 54 | 55 | if 'clear' in query_strings: 56 | messages.clear() 57 | elif 'message' in query_strings: 58 | message = query_strings['message'][0] 59 | messages.append(message) 60 | 61 | self.send_response(200) 62 | self.send_header('Content-type','text/html') 63 | self.end_headers() 64 | 65 | message_text = self.make_page() 66 | 67 | message_bytes = message_text.encode() 68 | 69 | self.wfile.write(message_bytes) 70 | 71 | host_socket = 8080 72 | host_ip = 'localhost' 73 | 74 | host_address = (host_ip, host_socket) 75 | 76 | my_server = http.server.HTTPServer(host_address, webServerHandler) 77 | my_server.serve_forever() 78 | 79 | -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG 16-01 pygame drawing functions.py: -------------------------------------------------------------------------------- 1 | #EG 16-01 pygame drawing functions 2 | 3 | import random 4 | import pygame 5 | 6 | class DrawDemo: 7 | 8 | @staticmethod 9 | def do_draw_demo(): 10 | init_result = pygame.init() 11 | if init_result[1] != 0: 12 | print('pygame not installed properly') 13 | return 14 | 15 | width = 800 16 | height = 600 17 | size = (width, height) 18 | 19 | def get_random_coordinate(): 20 | X = random.randint(0,width-1) 21 | Y = random.randint(0,height-1) 22 | return (X, Y) 23 | 24 | def get_random_color(): 25 | red = random.randint(0,255) 26 | green = random.randint(0,255) 27 | blue = random.randint(0,255) 28 | return (red, green, blue) 29 | 30 | surface = pygame.display.set_mode(size) 31 | pygame.display.set_caption('Drawing example') 32 | 33 | red = (255, 0, 0) 34 | green = (0, 255, 0) 35 | blue = (0, 0, 255) 36 | black = (0, 0, 0) 37 | yellow = (255, 255, 0) 38 | magenta = (255, 0, 255) 39 | cyan = (0, 255, 255) 40 | white = (255, 255, 255) 41 | gray = (128, 128, 128) 42 | 43 | # Fill the screen with white 44 | surface.fill(white) 45 | 46 | 47 | # Draw 100 random lines 48 | for count in range(100): 49 | start = get_random_coordinate() 50 | end = get_random_coordinate() 51 | color = get_random_color() 52 | pygame.draw.line(surface, color, start, end) 53 | 54 | # Draw 100 dots 55 | dot_radius = 10 56 | for count in range(100): 57 | pos = get_random_coordinate() 58 | color = get_random_color() 59 | radius = random.randint(5, 50) 60 | pygame.draw.circle(surface, color, pos, radius) 61 | 62 | pygame.display.flip() 63 | 64 | DrawDemo.do_draw_demo() 65 | 66 | 67 | -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-02 Image Drawing.py: -------------------------------------------------------------------------------- 1 | # EG16-02 Image Drawing 2 | 3 | import pygame 4 | 5 | class ImageDemo: 6 | 7 | @staticmethod 8 | def do_image_demo(): 9 | init_result = pygame.init() 10 | if init_result[1] != 0: 11 | print('pygame not installed properly') 12 | return 13 | 14 | width = 800 15 | height = 600 16 | size = (width, height) 17 | 18 | surface = pygame.display.set_mode(size) 19 | pygame.display.set_caption('Image example') 20 | 21 | white = (255, 255, 255) 22 | surface.fill(white) 23 | 24 | cheeseImage = pygame.image.load('Cheese.png') 25 | 26 | cheesePos = (0,0) 27 | surface.blit(cheeseImage, cheesePos) 28 | pygame.display.flip() 29 | 30 | ImageDemo.do_image_demo() 31 | 32 | -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-02 Image Drawing/EG16-02 Image Drawing.py: -------------------------------------------------------------------------------- 1 | # EG16-02 Image Drawing 2 | 3 | import pygame 4 | 5 | class ImageDemo: 6 | 7 | @staticmethod 8 | def do_image_demo(): 9 | init_result = pygame.init() 10 | if init_result[1] != 0: 11 | print('pygame not installed properly') 12 | return 13 | 14 | width = 800 15 | height = 600 16 | size = (width, height) 17 | 18 | surface = pygame.display.set_mode(size) 19 | pygame.display.set_caption('Image example') 20 | 21 | white = (255, 255, 255) 22 | surface.fill(white) 23 | 24 | cheeseImage = pygame.image.load("cheese.png") 25 | 26 | cheesePos = (0,0) 27 | surface.blit(cheeseImage, cheesePos) 28 | pygame.display.flip() 29 | 30 | ImageDemo.do_image_demo() 31 | 32 | -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-02 Image Drawing/cheese.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-02 Image Drawing/cheese.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-03 Moving cheese/EG16-03 Moving cheese.py: -------------------------------------------------------------------------------- 1 | # EG16-03 Moving cheese 2 | 3 | import pygame 4 | 5 | class ImageDemo: 6 | 7 | @staticmethod 8 | def do_image_demo(): 9 | init_result = pygame.init() 10 | if init_result[1] != 0: 11 | print('pygame not installed properly') 12 | return 13 | 14 | width = 800 15 | height = 600 16 | size = (width, height) 17 | 18 | surface = pygame.display.set_mode(size) 19 | pygame.display.set_caption('Moving cheese') 20 | 21 | cheeseImage = pygame.image.load("cheese.png") 22 | 23 | cheeseX = 40 24 | cheeseY = 60 25 | cheeseYSpeed = 2 26 | cheeseMovingUp = False 27 | cheeseMovingDown = False 28 | 29 | clock = pygame.time.Clock() 30 | 31 | while True: 32 | clock.tick(60) 33 | for e in pygame.event.get(): 34 | if e.type == pygame.KEYDOWN: 35 | if e.key == pygame.K_ESCAPE: 36 | pygame.quit() 37 | return 38 | elif e.key == pygame.K_UP: 39 | cheeseMovingUp = True 40 | elif e.key == pygame.K_DOWN: 41 | cheeseMovingDown = True 42 | elif e.type == pygame.KEYUP: 43 | if e.key == pygame.K_UP: 44 | cheeseMovingUp = False 45 | elif e.key == pygame.K_DOWN: 46 | cheeseMovingDown = False 47 | if cheeseMovingDown: 48 | cheeseY = cheeseY+cheeseYSpeed 49 | if cheeseMovingUp: 50 | cheeseY = cheeseY-cheeseYSpeed 51 | surface.fill((255,255,255)) 52 | cheesePos = (int(cheeseX),int(cheeseY)) 53 | surface.blit(cheeseImage, cheesePos) 54 | pygame.display.flip() 55 | 56 | ImageDemo.do_image_demo() 57 | 58 | -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-03 Moving cheese/cheese.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-03 Moving cheese/cheese.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-04 Steerable cheese/EG16-04 Steerable cheese.py: -------------------------------------------------------------------------------- 1 | # EG16-04 Steerable cheese 2 | 3 | import pygame 4 | 5 | class ImageDemo: 6 | 7 | @staticmethod 8 | def do_image_demo(): 9 | init_result = pygame.init() 10 | if init_result[1] != 0: 11 | print('pygame not installed properly') 12 | return 13 | 14 | width = 800 15 | height = 600 16 | size = (width, height) 17 | 18 | surface = pygame.display.set_mode(size) 19 | pygame.display.set_caption('Moving cheese') 20 | 21 | cheeseImage = pygame.image.load("cheese.png") 22 | 23 | cheeseX = 40 24 | cheeseY = 60 25 | cheeseYSpeed = 3 26 | cheeseMovingUp = False 27 | cheeseMovingDown = False 28 | clock = pygame.time.Clock() 29 | 30 | while True: 31 | clock.tick(30) 32 | for e in pygame.event.get(): 33 | if e.type == pygame.KEYDOWN: 34 | if e.key == pygame.K_ESCAPE: 35 | pygame.quit() 36 | return 37 | elif e.key == pygame.K_UP: 38 | cheeseMovingUp = True 39 | elif e.key == pygame.K_DOWN: 40 | cheeseMovingDown = True 41 | elif e.type == pygame.KEYUP: 42 | if e.key == pygame.K_UP: 43 | cheeseMovingUp = False 44 | elif e.key == pygame.K_DOWN: 45 | cheeseMovingDown = False 46 | if cheeseMovingDown: 47 | cheeseY = cheeseY+cheeseYSpeed 48 | if cheeseMovingUp: 49 | cheeseY = cheeseY-cheeseYSpeed 50 | surface.fill((255,255,255)) 51 | cheesePos = (int(cheeseX),int(cheeseY)) 52 | surface.blit(cheeseImage, cheesePos) 53 | pygame.display.flip() 54 | 55 | ImageDemo.do_image_demo() 56 | 57 | -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-04 Steerable cheese/cheese.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-04 Steerable cheese/cheese.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-05 background sprite/EG16-05 background sprite.py: -------------------------------------------------------------------------------- 1 | # EG16-05 background sprite 2 | 3 | import pygame 4 | 5 | class Sprite: 6 | ''' 7 | A sprite in the game. Can be sub-classed 8 | to create sprites with particular behaviours 9 | ''' 10 | def __init__(self, image, game): 11 | ''' 12 | Initialize a sprite 13 | image is the image to use to draw the sprite 14 | default position is origin (0,0) 15 | game is the game that contains this sprite 16 | ''' 17 | self.image = image 18 | self.position = [0, 0] 19 | self.game = game 20 | self.reset() 21 | 22 | def update(self): 23 | ''' 24 | Called in the game loop to update 25 | the status of the sprite. 26 | Does nothing in the super class 27 | ''' 28 | pass 29 | 30 | def draw(self): 31 | ''' 32 | Draws the sprite on the screen at its 33 | current position 34 | ''' 35 | self.game.surface.blit(self.image, self.position) 36 | 37 | def reset(self): 38 | ''' 39 | Called at the start of a new game to 40 | reset the sprite 41 | ''' 42 | pass 43 | 44 | class CrackerChase: 45 | ''' 46 | Plays the amazing cracker chase game 47 | ''' 48 | 49 | def play_game(self): 50 | ''' 51 | Starts the game playing 52 | Will return when the player exits 53 | the game. 54 | ''' 55 | init_result = pygame.init() 56 | if init_result[1] != 0: 57 | print('pygame not installed properly') 58 | return 59 | 60 | self.width = 800 61 | self.height = 600 62 | self.size = (self.width, self.height) 63 | 64 | self.surface = pygame.display.set_mode(self.size) 65 | pygame.display.set_caption('Cracker Chase') 66 | background_image = pygame.image.load('background.png') 67 | self.background_sprite = Sprite(image=background_image, 68 | game=self) 69 | 70 | clock = pygame.time.Clock() 71 | 72 | while True: 73 | clock.tick(60) 74 | for e in pygame.event.get(): 75 | if e.type == pygame.KEYDOWN: 76 | if e.key == pygame.K_ESCAPE: 77 | pygame.quit() 78 | return 79 | self.background_sprite.draw() 80 | pygame.display.flip() 81 | 82 | 83 | game = CrackerChase() 84 | game.play_game() 85 | -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-05 background sprite/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-05 background sprite/background.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-06 Cheese Player/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-06 Cheese Player/background.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-06 Cheese Player/cheese.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-06 Cheese Player/cheese.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-07 Cheese and cracker/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-07 Cheese and cracker/background.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-07 Cheese and cracker/cheese.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-07 Cheese and cracker/cheese.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-07 Cheese and cracker/cracker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-07 Cheese and cracker/cracker.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-08 Cheese and crackers/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-08 Cheese and crackers/background.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-08 Cheese and crackers/cheese.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-08 Cheese and crackers/cheese.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-08 Cheese and crackers/cracker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-08 Cheese and crackers/cracker.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-09 Capturing crackers/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-09 Capturing crackers/background.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-09 Capturing crackers/burp.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-09 Capturing crackers/burp.wav -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-09 Capturing crackers/cheese.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-09 Capturing crackers/cheese.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-09 Capturing crackers/cracker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-09 Capturing crackers/cracker.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-09 Scoring cheese and crackers/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-09 Scoring cheese and crackers/background.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-09 Scoring cheese and crackers/burp.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-09 Scoring cheese and crackers/burp.wav -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-09 Scoring cheese and crackers/cheese.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-09 Scoring cheese and crackers/cheese.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-09 Scoring cheese and crackers/cracker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-09 Scoring cheese and crackers/cracker.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-10 Killer tomato/Tomato.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-10 Killer tomato/Tomato.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-10 Killer tomato/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-10 Killer tomato/background.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-10 Killer tomato/burp.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-10 Killer tomato/burp.wav -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-10 Killer tomato/cheese.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-10 Killer tomato/cheese.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-10 Killer tomato/cracker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-10 Killer tomato/cracker.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-11 Complete Game/Tomato.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-11 Complete Game/Tomato.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-11 Complete Game/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-11 Complete Game/background.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-11 Complete Game/burp.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-11 Complete Game/burp.wav -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-11 Complete Game/cheese.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-11 Complete Game/cheese.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-11 Complete Game/cracker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-11 Complete Game/cracker.png -------------------------------------------------------------------------------- /Ch 16 Python games with Pygame/EG16-11 Complete Game/start background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/Ch 16 Python games with Pygame/EG16-11 Complete Game/start background.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Begin to Code with Python 2 | ![Begin to Code with Python book cover](images/cover.png) 3 | 4 | 5 | This is the sample code for the book "Begin to Code with Python" by Rob Miles. You can find the official Microsoft Press Store page for this book [here](https://www.microsoftpressstore.com/store/begin-to-code-with-python-9781509304523) 6 | # Languages and tools 7 | ## Python 8 | You should use the latest version of Python 3 which you can find [here](https://www.python.org/downloads/). There are versions of Python for many platforms. The book uses the Idle code editor which is included with the Python distribution. It doesn't matter which version of Python 3.n that you use, but you must *not* use any form of Python 2.n 9 | ## Visual Studio Code 10 | The book also uses Visual Studio Code which you can find [here](https://code.visualstudio.com/). 11 | # Snaps 12 | The Snaps framework is used for some of the graphical exercises in the text. You don't need it for most of the exercises. The Snaps framework uses PyGame for graphics and user input. You can find out how to install PyGame in the book. Take a look at page 65. The site for PyGame is [here](https://www.pygame.org). 13 | 14 | ## Important Notes: 15 | ### Typo 16 | There is an error on page 66. Rather than it saying 17 | 18 | ``` 19 | from snaps import * 20 | ``` 21 | 22 | It should just say 23 | 24 | ``` 25 | import snaps 26 | ``` 27 | 28 | To make snaps work you just have to have the snaps program in the same folder as your program. 29 | ### Using the keyboard with Snaps 30 | There have been some reports of the keyboard reading function in Snaps not working correctly when you run your Python program from within an IDE such as pyCharm or IDLE. If you find the keyboard to be unresponsive, try running the Python program directly in Python, rather than inside an IDE. Check on page 63 for details of how to run a program from the desktop. 31 | ## Videos 32 | There are some videos which take you through installing Python and Snaps. You can find them [here](https://www.youtube.com/playlist?list=PL7zNOp_WVLyUZ5XoCP2w0Uhy02PnX5W9m). 33 | # Microsoft Certified Professional 34 | 35 | You can find a set of notes that will help you use this book to revise for the Microsoft Certified Professional Exam 98-381, 'Introduction to Programming Using Python' [here](notes/prep.pdf) 36 | # Buying the book 37 | You can buy the book [here](http://a.co/abCAG81) 38 | # Getting in touch 39 | You can find my blog at [www.robmiles.com](https://www.robmiles.com/) 40 |

If you have any questions about the links, the sample programs, or the book, you can get in touch with me via email on questions at begintocodewithpython.com. You can also tweet any questions to @begintocode or @robmiles 41 | -------------------------------------------------------------------------------- /images/cover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/images/cover.png -------------------------------------------------------------------------------- /notes/prep.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Begintocodewithpython/samples/1bb6d6f8c8b60d649e53fa69373a14fa47947b8b/notes/prep.pdf --------------------------------------------------------------------------------