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

Josh Cogliati - Non-Programmers Tutorial For Python, страница 3

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

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

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

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

Текст 3 страницы из PDF

An easy way to do this is to write aprogram like this:while 1 == 1:print "Help, I’m stuck in a loop."This program will output Help, I’m stuck in a loop. until the heat death of the universe or you stop it.The way to stop it is to hit the Control (or Ctrl) button and ‘c’ (the letter) at the same time. This will kill the program.(Note: sometimes you will have to hit enter after the Control C.)4.2ExamplesFibonnacci.py14Chapter 4.

Count to 10#This program calulates the fibonnacci sequencea = 0b = 1count = 0max_count = 20while count < max_count:count = count + 1#we need to keep track of a since we change itold_a = aold_b = ba = old_bb = old_a + old_b#Notice that the , at the end of a print statement keeps it# from switching to a new lineprint old_a,printOutput:0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181Password.py# Waits until a password has been entered.# the passwordUse control-C to break out with out#Note that this must not be the password so that the# while loop runs at least once.password = "foobar"#note that != means not equalwhile password != "unicorn":password = raw_input("Password:")print "Welcome in"Sample run:Password:auoPassword:y22Password:passwordPassword:open sesamePassword:unicornWelcome in4.2.

Examples1516CHAPTERFIVEDecisions5.1If statementAs always I believe I should start each chapter with a warm up typing exercise so here is a short program to computethe absolute value of a number:n = input("Number? ")if n < 0:print "The absolute value of",n,"is",-nelse:print "The absolute value of",n,"is",nHere is the output from the two times that I ran this program:Number? -34The absolute value of -34 is 34Number? 1The absolute value of 1 is 1So what does the computer do when when it sees this piece of code? First it prompts the user for a number with thestatement n = input("Number? "). Next it reads the line if n < 0: If n is less than zero Python runsthe line print "The absolute value of",n,"is",-n.

Otherwise python runs the line print "Theabsolute value of",n,"is",n.More formally Python looks at whether the expression n < 0 is true or false. A if statement is followed by a blockof statements that are run when the expression is true. Optionally after the if statement is a else statement. Theelse statement is run if the expression is false.There are several different tests that a expression can have.

Here is a table of all of them:operator<<=>>===!=<>functionless thanless than or equal togreater thangreater than or equal toequalnot equalanother way to say not equalAnother feature of the if command is the elif statement. It stands for else if and means if the original if statement17is false and then the elif part is true do that part. Here’s a example:a = 0while a < 10:a = a + 1if a > 5:print a," > ",5elif a <= 7:print a," <= ",7else:print "Neither test was true"and the output:12345678910<=<=<=<=<=>>>>>7777755555Notice how the elif a <= 7 is only tested when the if statement fail to be true.

elif allows multiple tests to bedone in a single if statement.5.2ExamplesHigh low.py#Plays the guessing game higher or lower# (originally written by Josh Cogliati, improved by Quique)#This should actually be something that is semi random like the# last digits of the time or something else, but that will have to# wait till a later chapter. (Extra Credit, modify it to be random# after the Modules chapter)number = 78guess = 0while guess != number :guess = input ("Guess a number: ")if guess > number :print "Too high"elif guess < number :print "Too low"print "Just right"18Chapter 5. DecisionsSample run:Guess a number:100Too highGuess a number:50Too lowGuess a number:75Too lowGuess a number:87Too highGuess a number:81Too highGuess a number:78Just righteven.py#Asks for a number.#Prints if it is even or oddnumber = input("Tell me a number: ")if number % 2 == 0:print number,"is even."elif number % 2 == 1:print number,"is odd."else:print number,"is very strange."Sample runs.Tell me a number: 33 is odd.Tell me a number: 22 is even.Tell me a number: 3.141593.14159 is very strange.average1.py5.2.

Examples19#keeps asking for numbers until 0 is entered.#Prints the average value.count = 0sum = 0.0number = 1 #set this to something that will not exit#the while loop immediatly.print "Enter 0 to exit the loop"while number != 0:number = input("Enter a number:")count = count + 1sum = sum + numbercount = count - 1 #take off one for the last numberprint "The average was:",sum/countSample runsEnter 0 to exit the loopEnter a number:3Enter a number:5Enter a number:0The average was: 4.0Enter 0 to exit the loopEnter a number:1Enter a number:4Enter a number:3Enter a number:0The average was: 2.66666666667average2.py#keeps asking for numbers until count have been entered.#Prints the average value.sum = 0.0print "This program will take several numbers than average them"count = input("How many numbers would you like to sum:")current_count = 0while current_count < count:current_count = current_count + 1print "Number ",current_countnumber = input("Enter a number:")sum = sum + numberprint "The average was:",sum/countSample runs20Chapter 5.

DecisionsThis program will take several numbers than average themHow many numbers would you like to sum:2Number 1Enter a number:3Number 2Enter a number:5The average was: 4.0This program will take several numbers than average themHow many numbers would you like to sum:3Number 1Enter a number:1Number 2Enter a number:4Number 3Enter a number:3The average was: 2.666666666675.3ExercisesModify the password guessing program to keep track of how many times the user has entered the password wrong. Ifit is more than 3 times, print “That must have been complicated.”Write a program that asks for two numbers. If the sum of the numbers is greater than 100, print “That is big number”.Write a program that asks the user their name, if they enter your name say ”That is a nice name”, if they enter ”JohnCleese” or ”Michael Palin”, tell them how you feel about them ;), otherwise tell them ”You have a nice name”.5.3.

Exercises2122CHAPTERSIXDebugging6.1What is debugging?As soon as we started programming, we found to our surprise that it wasn’t as easy to get programsright as we had thought. Debugging had to be discovered. I can remember the exact instant when Irealized that a large part of my life from then on was going to be spent in finding mistakes in my ownprograms.– Maurice Wilkes discovers debugging, 1949By now if you have been messing around with the programs you have probably found that sometimes the programdoes something you didn’t want it to do. This is fairly common.

Debugging is the process of figuring out what thecomputer is doing and then getting it to do what you want it to do. This can be tricky. I once spent nearly a weektracking down and fixing a bug that was caused by someone putting an x where a y should have been.This chapter will be more abstract than previous chapters. Please tell me if it is useful.6.2What should the program do?The first thing to do (this sounds obvious) is to figure out what the program should be doing if it is running correctly.Come up with some test cases and see what happens. For example, let’s say I have a program to compute the perimeterof a rectangle (the sum of the length of all the edges).

I have the following test cases:width32425height43421perimeter141016812I now run my program on all of the test cases and see if the program does what I expect it to do. If it doesn’t then Ineed to find out what the computer is doing.More commonly some of the test cases will work and some will not. If that is the case you should try and figure outwhat the working ones have in common. For example here is the output for a perimeter program (you get to see thecode in a minute):Height: 3Width: 4perimeter =1523Height: 2Width: 3perimeter =11Height: 4Width: 4perimeter =16Height: 2Width: 2perimeter =8Height: 5Width: 1perimeter =8Notice that it didn’t work for the first two inputs, it worked for the next two and it didn’t work on the last one.

Try andfigure out what is in common with the working ones. Once you have some idea what the problem is finding the causeis easier. With your own programs you should try more test cases if you need them.6.3What does the program do?The next thing to do is to look at the source code. One of the most important things to do while programming isreading source code. The primary way to do this is code walkthroughs.A code walkthrough starts at the first line, and works its way down until the program is done.

While loops and ifstatements mean that some lines may never be run and some lines are run many times. At each line you figure outwhat Python has done.Lets start with the simple perimeter program. Don’t type it in, you are going to read it, not run it. The source code is:height = input("Height: ")width = input("Width: ")print "perimeter = ",width+height+width+widthQuestion: What is the first line Python runs?Answer: The first line is alway run first. In this case it is: height = input("Height: ")Question: What does that line do?Answer: Prints Height:, waits for the user to type a number in, and puts that in the variable height.Question: What is the next line that runs?Answer: In general, it is the next line down which is: width = input("Width: ")Question: What does that line do?Answer: Prints Width:, waits for the user to type a number in, and puts what the user types in the variable width.Question: What is the next line that runs?24Chapter 6.

DebuggingAnswer: When the next line is not indented more or less than the current line, it is the line right afterwards, so it is:print "perimeter = ",width+height+width+width (It may also run a function in the current line, butthats a future chapter.)Question: What does that line do?Answer: First it prints perimeter =, then it prints width+height+width+width.Question: Does width+height+width+width calculate the perimeter properly?Answer: Let’s see, perimeter of a rectangle is the bottom (width) plus the left side (height) plus the top (width) plusthe right side (huh?). The last item should be the right side’s length, or the height.Question: Do you understand why some of the times the perimeter was calculated ‘correctly’?Answer: It was calculated correctly when the width and the height were equal.The next program we will do a code walkthrough for is a program that is supposed to print out 5 dots on the screen.However, this is what the program is outputting:.

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