Главная » Все файлы » Просмотр файлов из архивов » PDF-файлы » Josh Cogliati - Non-Programmers Tutorial For Python

Josh Cogliati - Non-Programmers Tutorial For Python

PDF-файл Josh Cogliati - Non-Programmers Tutorial For Python Основы автоматизированного проектирования (ОАП) (17687): Книга - 3 семестрJosh Cogliati - Non-Programmers Tutorial For Python: Основы автоматизированного проектирования (ОАП) - PDF (17687) - СтудИзба2018-01-10СтудИзба

Описание файла

PDF-файл из архива "Josh Cogliati - Non-Programmers Tutorial For Python", который расположен в категории "". Всё это находится в предмете "основы автоматизированного проектирования (оап)" из 3 семестр, которые можно найти в файловом архиве МГТУ им. Н.Э.Баумана. Не смотря на прямую связь этого архива с МГТУ им. Н.Э.Баумана, его также можно найти и в других разделах. Архив можно найти в разделе "книги и методические указания", в предмете "основы автоматизированного производства (оап)" в общих файлах.

Просмотр PDF-файла онлайн

Текст из PDF

Non-Programmers Tutorial For PythonJosh CogliatiAugust 4, 2005Copyright(c) 1999-2002 Josh Cogliati.Permission is granted to anyone to make or distribute verbatim copies of this document as received, in any medium,provided that the copyright notice and permission notice are preserved, and that the distributor grants the recipientpermission for further redistribution as permitted by this notice.Permission is granted to distribute modified versions of this document, or of portions of it, under the above conditions,provided also that they carry prominent notices stating who last altered them.All example python source code in this tutorial is granted to the public domain.

Therefore you may modify it andrelicense it under any license you please.AbstractNon-Programmers Tutorial For Python is a tutorial designed to be a introduction to the Python programming language.This guide is for someone with no programming experience.If you have programmed in other languages I recommend using The Python Tutorial written by Guido van Rossum.This document is available as LATEX, HTML, PDF, and Postscript. Go to http://www.honors.montana.edu/˜jjc/easytut/to see all these forms.If you have any questions or comments please contact me at jjc@iname.com I welcome questions and commentsabout this tutorial.

I will try to answer any questions you have as best as I can.Thanks go to James A. Brown for writing most of the Windows install info. Thanks also to Elizabeth Cogliati forcomplaining enough :) about the original tutorial,(that is almost unusable for a non-programmer) for proofreading andfor many ideas and comments on it. Thanks to Joe Oppegaard for writing all the exercises. Thanks to everyone I havemissed.Dedicated to Elizabeth CogliatiCONTENTS1 Intro1.11.21.31.41.5.................................................................................................................................................1111222 Hello, World2.1 What you should know .

. . . . . . . . . . . . .2.2 Printing . . . . . . . . . . . . . . . . . . . . . .2.3 Expressions . . . . . . . . . . . . . . . . . . . .2.4 Talking to humans (and other intelligent beings)2.5 Examples . . . . . . . . . . . . . . . . . . . . .2.6 Exercises . . . . . . .

. . . . . . . . . . . . . .........................................................................................................................................................................33345673 Who Goes There?3.1 Input and Variables . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9911124 Count to 104.1 While loops . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1313145 Decisions5.1 If statement . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .171718216 Debugging6.1 What is debugging? . . . . .6.2 What should the program do?6.3 What does the program do? .6.4 How do I fix the program? . .........................................................................................................................................................23232324277 Defining Functions7.1 Creating Functions . .7.2 Variables in functions7.3 Function walkthrough7.4 Examples .

. . . . . .........................................................................................................................................................2929303234First things first . . . . . . . . . . . .Installing Python . . . . . . . . . . .Interactive Mode . . . . . .

. . . . .Creating and Running Programs . . .Using Python from the command line.........................................i7.58 Lists8.18.28.38.4Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

.36Variables with more than one valueMore features of lists . . . . . . . .Examples . . . . . . . . . . . . . .Exercises . . . . . . . . . . . . . .3737374243............................................................................................................................................9 For Loops4510 Boolean Expressions10.1 Examples .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49515111 Dictionaries5312 Using Modules12.1 Exercises . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .596013 More on Lists6114 Revenge of the Strings14.1 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .677115 File IO15.1 Exercises . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .737716 Dealing with the imperfect (or how to handle errors)16.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .798017 The End8118 FAQ83Index85iiCHAPTERONEIntro1.1First things firstSo, you’ve never programmed before.

As we go through this tutorial I will attempt to teach you how to program.There really is only one way to learn to program. You must read code and write code. I’m going to show you lots ofcode. You should type in code that I show you to see what happens. Play around with it and make changes. The worstthat can happen is that it won’t work. When I type in code it will be formatted like this:##Python is easy to learnprint "Hello, World!"That’s so it is easy to distinguish from the other text. To make it confusing I will also print what the computer outputsin that same font.Now, on to more important things. In order to program in Python you need the Python software. If you don’talready have the Python software go to http://www.python.org/download/ and get the proper version for your platform.Download it, read the instructions and get it installed.1.2Installing PythonFirst you need to download the appropriate file for your computer from http://www.python.org/download.

Go to the 2.0link (or newer) and then get the windows installer if you use Windows or the rpm or source if you use Unix.The Windows installer will download to file. The file can then be run by double clicking on the icon that is downloaded.The installation will then proceed.If you get the Unix source make sure you compile in the tk extension if you want to use IDLE.1.3Interactive ModeGo into IDLE (also called the Python GUI). You should see a window that has some text like this:1Python 2.0 (#4, Dec 12 2000, 19:19:57)[GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2Type "copyright", "credits" or "license" for more information.IDLE 0.6 -- press F1 for help>>>The >>> is Python way of telling you that you are in interactive mode. In interactive mode what you type is immediately run. Try typing 1+1 in. Python will respond with 2.

Interactive mode allows you to test out and see what Pythonwill do. If you ever feel you need to play with new Python statements go into interactive mode and try them out.1.4Creating and Running ProgramsGo into IDLE if you are not already. Go to File then New Window. In this window type the following:print "Hello, World!"First save the program.

Go to File then Save. Save it as ‘hello.py’. (If you want you can save it to some otherdirectory than the default.) Now that it is saved it can be run.Next run the program by going to Run then Run Module (or if you have a older version of IDLE use Edit thenRun script). This will output Hello, World! on the *Python Shell* window.Confused still? Try this tutorial for IDLE at http://hkn.eecs.berkeley.edu/ dyoo/python/idle intro/index.html1.5Using Python from the command lineIf you don’t want to use Python from the command line, you don’t have too, just use IDLE.

To get into interactivemode just type python with out any arguments. To run a program create it with a text editor (Emacs has a goodpython mode) and then run it with python program name.2Chapter 1. IntroCHAPTERTWOHello, World2.1What you should knowYou should know how to edit programs in a text editor or IDLE, save them to disk (floppy or hard) and run them oncethey have been saved.2.2PrintingProgramming tutorials since the beginning of time have started with a little program called Hello, World! So here it is:print "Hello, World!"If you are using the command line to run programs then type it in with a text editor, save it as ‘hello.py’ and run it with“python hello.py”Otherwise go into IDLE, create a new window, and create the program as in section 1.4.When this program is run here’s what it prints:Hello, World!Now I’m not going to tell you this every time, but when I show you a program I recommend that you type it in and runit.

I learn better when I type it in and you probably do too.Now here is a more complicated program:printprintprintprint"Jack and Jill went up a hill""to fetch a pail of water;""Jack fell down, and broke his crown,""and Jill came tumbling after."When you run this program it prints out:Jack and Jill went up a hillto fetch a pail of water;Jack fell down, and broke his crown,and Jill came tumbling after.3When the computer runs this program it first sees the line:print "Jack and Jill went up a hill"so the computer prints:Jack and Jill went up a hillThen the computer goes down to the next line and sees:print "to fetch a pail of water;"So the computer prints to the screen:to fetch a pail of water;The computer keeps looking at each line, follows the command and then goes on to the next line. The computer keepsrunning commands until it reaches the end of the program.2.3ExpressionsHere is another program:printprintprintprint"2 + 2 is", 2+2"3 * 4 is", 3 * 4100 - 1, " = 100 - 1""(33 + 2) / 5 + 11.5 = ",(33 + 2) / 5 + 11.5And here is the output when the program is run:2 +3 *99(3324=+is 4is 12100 - 12) / 5 + 11.5 =18.5As you can see Python can turn your thousand dollar computer into a 5 dollar calculator.Python has six basic operations for numbers:OperationExponentiationMultiplicationDivisionRemainderAdditionSubtractionSymbol***/%+-Example5 ** 2 == 252 * 3 == 614 / 3 == 414 % 3 == 21 + 2 == 34 - 3 == 1Notice that division follows the rule, if there are no decimals to start with, there will be no decimals to end with.

(Note:This will be changing in Python 2.3) The following program shows this:4Chapter 2. Hello, Worldprintprintprintprintprintprintprintprintprintprintprintprint"14 / 3 = ",14 / 3"14 % 3 = ",14 % 3"14.0 / 3.0 =",14.0 / 3.0"14.0 % 3.0 =",14 % 3.0"14.0 / 3 =",14.0 / 3"14.0 % 3 =",14.0 % 3"14 / 3.0 =",14 / 3.0"14 % 3.0 =",14 % 3.0With the output:14 / 3 =14 % 3 =4214.0 / 3.0 = 4.6666666666714.0 % 3.0 = 2.014.0 / 3 = 4.6666666666714.0 % 3 = 2.014 / 3.0 = 4.6666666666714 % 3.0 = 2.0Notice how Python gives different answers for some problems depending on whether or not there decimal values areused.The order of operations is the same as in math:1. parentheses ()2.

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
5173
Авторов
на СтудИзбе
436
Средний доход
с одного платного файла
Обучение Подробнее