An introduction to interactive programming in python

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

An Introduction to Interactive Programming in Python (Part 1) — Part 1 of Fundamentals of Computing from Rice University

ihendrik/An-Introduction-to-Interactive-Programming-in-Python-Part-1

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

An Introduction to Interactive Programming in Python (Part 1) — Part 1 of Fundamentals of Computing from Rice University

Mini-project # 0 — «We want. a shrubbery!»

Your task is simple: modify this program template to print We want. a shrubbery!

Mini-project # 1 — Rock-paper-scissors-lizard-Spock

Rock-paper-scissors-lizard-Spock (RPSLS) is a variant of Rock-paper-scissors that allows five choices. Each choice wins against two other choices, loses against two other choices and ties against itself. Much of RPSLS’s popularity is that it has been featured in 3 episodes of the TV series «The Big Bang Theory».

While Rock-paper-scissor-lizard-Spock has a set of ten rules that logically determine who wins a round of RPSLS, coding up these rules would require a large number (5×5=25) of if/elif/else clauses in your mini-project code. A simpler method for determining the winner is to assign each of the five choices a number:

0 — rock 1 — Spock 2 — paper 3 — lizard 4 — scissors

Mini-project # 2 — «Guess the number» game»

One of the simplest two-player games is “Guess the number”. The first player thinks of a secret number in some known range while the second player attempts to guess the number. After each guess, the first player answers either “Higher”, “Lower” or “Correct!” depending on whether the secret number is higher, lower or equal to the guess. In this project, you will build a simple interactive program in Python where the computer will take the role of the first player while you play as the second player.

Читайте также:  Python uwsgi nginx flask

You will interact with your program using an input field and several buttons. For this project, we will ignore the canvas and print the computer’s responses in the console. Building an initial version of your project that prints information in the console is a development strategy that you should use in later projects as well. Focusing on getting the logic of the program correct before trying to make it display the information in some “nice” way on the canvas usually saves lots of time since debugging logic errors in graphical output can be tricky.

Mini-project # 3 — «Stopwatch: The Game»

Our mini-project for this week will focus on combining text drawing in the canvas with timers to build a simple digital stopwatch that keeps track of the time in tenths of a second. The stopwatch should contain «Start», «Stop» and «Reset» buttons.

In this project, we will build a version of Pong, one of the first arcade video games (1972). While Pong is not particularly exciting compared to today’s video games, Pong is relatively simple to build and provides a nice opportunity to work on the skills that you will need to build a game like Asteroids.

About

An Introduction to Interactive Programming in Python (Part 1) — Part 1 of Fundamentals of Computing from Rice University

Источник

Введение в интерактивное программирование на языке Python (Часть 2)

Изображение преподавателя Joe Warren

Joe Warren и еще 3 преподавателя

Доступна финансовая помощь

Специализация Основы компьютерных вычислений Университет Райса

Об этом курсе

This two-part course is designed to help students with very little or no computing background learn the basics of building simple interactive applications. Our language of choice, Python, is an easy-to learn, high-level computer language that is used in many of the computational courses offered on Coursera. To make learning Python easy, we have developed a new browser-based programming environment that makes developing interactive applications in Python simple. These applications will involve windows whose contents are graphical and respond to buttons, the keyboard and the mouse.

In part 2 of this course, we will introduce more elements of programming (such as list, dictionaries, and loops) and then use these elements to create games such as Blackjack. Part 1 of this class will culminate in building a version of the classic arcade game «Asteroids». Upon completing this course, you will be able to write small, but interesting Python programs. The next course in the specialization will begin to introduce a more principled approach to writing programs and solving computational problems that will allow you to write larger and more complex programs.

Читайте также:  Function in java syntax

Источник

Применяем на практике знания, полученные на курсе An Introduction to Interactive Programming in Python (coursera.org)

По мотивам этого поста.
В прошедшем 2012 году я, как и миллионы других пользователей открыл для себя бесплатное онлайн обучение. Всё началось с прекрасного стартапа Codecademy. Замечательные курсы про JavaScript, jQuery, Python, Ruby и другие занимали всё свободное время. Побочным эффектом стала практика чтения на английском. К середине года доступные уроки закончились и я стал интересоваться другими площадками, где можно продолжить самообучение. Как раз в то время на Хабре участились статьи про Coursera и я решил попробовать.
Первым курсом который привлек внимание был An Introduction to Interactive Programming in Python от Rice University. Недолго думая, я вступил в стройные ряды онлайн студентов.

Часть 1. Снова в школу

С первой же видео-лекции преподаватели курса (Joe Warren, Scott Rixner, Stephen Wong, John Greiner) располагают слушателей к дружеской обстановке и весёлому настроению. Достаточно сказать, что первым проектом для изучения стало написание консольной версии широко известной в кругах любителей The Big Bang Theory игры «Камень. Ножницы. Бумага. Ящерица. Спок.». Для тех кто не в курсе вот ее правила.
Все программирование в этом курсе происходит в специальной онлайн песочнице, что очень удобно, так как не надо таскать с собой повсюду исходники и дистрибутивы, а все свои эксперименты можно сохранять «в облаках». Как устроен процесс обучения в Coursera наверняка местной публике уже известно. Темы лекций и проекты по неделям были следующие:

  1. Expressions, variables, functions, conditionals. (Проект «Rock-Paper-Scissors-Lizard-Spock» game)
  2. Event-driven programming, local and global variables, buttons and input fields. (Проект «Guess the Number» game)
  3. The canvas, static drawing, timers, interactive drawing. (Проект Stopwatch: The Game)
  4. Lists, keyboard input, motion, positional/velocity control. (Проект «Pong» game)
  5. Mouse input, more lists, dictionaries, images. (Проект «Memory» game)
  6. Classes, tiled images. (Проект «Blackjack» game)
  7. Acceleration and friction, spaceship class, sprite class, sound Spaceship from. (Проект «RiceRocks» game)
  8. Sets, groups of sprites, collisions, sprite animation. (Проект Full «RiceRocks» game)
Часть 2. Быдлокод

Закончив курс со средним баллом 99.46 / 100, я конечно же почувствовал себя всемогущим программистом. И как раз вовремя подвернулась небольшая задача, которую я и не преминул решить, используя вновь приобретенные знания.
Задачка была следующая: для имеющегося каталога с кучей документации в формате .pdf cгенерировать HTML страничку со списком ссылок на файлы, отсортированных по вложенным каталогам. Ссылки должны быть удобочитаемые, а значит имя файла не годится и нужно лезть в каждый PDF и читать заголовок документа.
Немного курения мануалов по модулям pyPdf и markup и совсем немножко копипаста, и получилось нечто:

import os import sys from datetime import date from pyPdf import PdfFileReader import markup import shutil def getPdfTitle(filename): if not filename.endswith('.pdf'): return "" input1 = PdfFileReader(file(filename, "rb")) if not input1 or input1.getIsEncrypted(): print ".file " + filename + " is encrypted. " return filename.split(os.sep)[-1] if input1.getDocumentInfo() == None or input1.getDocumentInfo().title == None: print ".file " + filename + " has no title. " return filename.split(os.sep)[-1] return "%s - %s" % (input1.getDocumentInfo().author, input1.getDocumentInfo().title) def create_html_list(rootpath): rootpath = rootpath.rstrip(os.sep) start_level = rootpath.count(os.sep) page = markup.page( ) page.init( title="Pdf File List", css=( 'bootstrap.css', 'style.css' ), script= < 'script.js':'javascript' >) page.div(class_='wrapper') for root, dirs, files in os.walk(rootpath): present_level = root.count(os.sep) actual_level = present_level - start_level caption = os.path.realpath(root).split(os.sep)[-1] if actual_level == 0: page.h1( caption, class_='caption' ) elif actual_level == 1: page.h2( caption, class_='caption' ) elif actual_level == 2: page.h3( caption, class_='caption' ) elif actual_level == 3: page.h4( caption, class_='caption' ) else: page.h5( os.path.relpath(root), class_='caption' ) if len(files) < 1: continue file_list = [file for file in files] # begin list page.ol( class_='list' ) for filename in file_list: title = getPdfTitle(os.path.relpath(root) + '\\' + filename).encode('ascii', 'ignore') if title == "": continue # to escape special characters title.encode('ascii', 'ignore') # list item page.li( class_='item' ) page.a(title, href=os.path.realpath(root) + '\\' + filename, class_='link') page.li.close() # end list page.ol.close( ) today = date.today() today.strftime("%d-%m-%Y") page.div("Last list refresh: " + str(today), class_='time') page.div.close() # print page # writing page to index.html file index_html = open('index.html', 'wt') index_html.write(str(page)) index_html.close() def copy_files(files, dst): for file in files: shutil.copy2(file, dst + "\\" + file) def usage(): print "Usage: pdfdir2html @path_to_pdf_files" if __name__ == '__main__': print "Generate HTML list from folder with pdf files" if len(sys.argv) == 1: print "No arguments given!" usage() elif len(sys.argv) == 2: destination = str(sys.argv[-1]) print ".converting folder: " + destination + ". " create_html_list(destination) print ".copying files. " copy_files(['index.html', 'bootstrap.css', 'style.css'], destination) print ".done" else: print "Too much arguments!" usage() 

Скрипт сканирует вложенные директории, считывает заголовок каждого PDF и создает в целевой папке файл index.html. Для пущей красоты я еще добавил к нему немножко CSS, но это уже детали…
Как оказалось, среди документации встречаются зашифрованные файлы, которые хоть и открываются нормально любым PDF ридером, но почему-то не позволяют прочитать свой заголовок с помощью getDocumentInfo().title . В таком случае ссылкой у нас будет всё-таки имя файла.
Для генерации HTML кода прекрасно подошел markup, с ним все просто и красиво, например:

 page = markup.page( ) page.init( title="Pdf File List", css=( 'bootstrap.css', 'style.css' ), script= < 'script.js':'javascript' >) page.div(class_='wrapper') . page.div.close() print page 
Часть 3. Куда податься

Пусть приведенный код и не использует концепций ООП, изученных в курсе Interactive Programming in Python, но именно этот курс подстегнул во мне интерес к использованию новых языков и изучению современных паттернов программирования. В данный момент на очереди у меня вот такие курсы:

Читайте также:  Свойства компонентов си шарп

Источник

Оцените статью