Главная » Просмотр файлов » Josh Cogliati - Non-Programmers Tutorial For Python

Josh Cogliati - Non-Programmers Tutorial For Python (779876), страница 5

Файл №779876 Josh Cogliati - Non-Programmers Tutorial For Python (Josh Cogliati - Non-Programmers Tutorial For Python) 5 страницаJosh Cogliati - Non-Programmers Tutorial For Python (779876) страница 52018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 5)

Later this function can be run.Question: What happens next?Answer: The next line after the function, print "3*2 = ",mult(3,2) is run.Question: And what does this do?Answer: It prints 3*2 = and the return value of mult(3,2)Question: And what does mult(3,2) return?Answer: We need to do a walkthrough of the mult function to find out.Question: What happens next?Answer: The variable a gets the value 3 assigned to it and the variable b gets the value 2 assigned to it.Question: And then?Answer: The line if b == 0: is run. Since b has the value 2 this is false so the line return 0 is skipped.Question: And what then?Answer: The line rest = mult(a,b - 1) is run.

This line sets the local variable rest to the value ofmult(a,b - 1). The value of a is 3 and the value of b is 2 so the function call is mult(3,1)Question: So what is the value of mult(3,1) ?32Chapter 7. Defining FunctionsAnswer: We will need to run the function mult with the parameters 3 and 1.Question: So what happens next?Answer: The local variables in the new run of the function are set so that a has the value 3 and b has the value 1.Since these are local values these do not affect the previous values of a and b.Question: And then?Answer: Since b has the value 1 the if statement is false, so the next line becomes rest = mult(a,b - 1).Question: What does this line do?Answer: This line will assign the value of mult(3,0) to rest.Question: So what is that value?Answer: We will have to run the function one more time to find that out. This time a has the value 3 and b has thevalue 0.Question: So what happens next?Answer: The first line in the function to run is if b == 0: .

b has the value 0 so the next line to run is return 0Question: And what does the line return 0 do?Answer: This line returns the value 0 out of the function.Question: So?Answer: So now we know that mult(3,0) has the value 0.Now we know what the linerest = mult(a,b - 1) did since we have run the function mult with the parameters 3 and 0. We have finishedrunning mult(3,0) and are now back to running mult(3,1). The variable rest gets assigned the value 0.Question: What line is run next?Answer: The line value = a + rest is run next.

In this run of the function, a=3 and rest=0 so now value=3.Question: What happens next?Answer: The line return value is run. This returns 3 from the function. This also exits from the run of thefunction mult(3,1). After return is called, we go back to running mult(3,2).Question: Where were we in mult(3,2)?Answer: We had the variables a=3 and b=2 and were examining the line rest = mult(a,b - 1) .Question: So what happens now?Answer: The variable rest get 3 assigned to it. The next line value = a + rest sets value to 3+3 or 6.Question: So now what happens?Answer: The next line runs, this returns 6 from the function.print "3*2 = ",mult(3,2) which can now print out the 6.We are now back to running the lineQuestion: What is happening overall?Answer: Basically we used two facts to calulate the multipule of the two numbers. The first is that any number times0 is 0 (x * 0 = 0).

The second is that a number times another number is equal to the first number plus the firstnumber times one less than the second number (x * y = x + x * (y - 1)). So what happens is 3*2 is firstconverted into 3 + 3*1. Then 3*1 is converted into 3 + 3*0. Then we know that any number times 0 is 0 so 3*0is 0. Then we can calculate that 3 + 3*0 is 3 + 0 which is 3. Now we know what 3*1 is so we can calculate that3 + 3*1 is 3 + 3 which is 6.This is how the whole thing works:7.3. Function walkthrough333*23 +3 +3 +3 +63*13 + 3*03 + 03These last two sections were recently written.

If you have any comments, found any errors or think I need more/clearerexplanations please email. I have been known in the past to make simple things incomprehensible. If the rest of thetutorial has made sense, but this section didn’t, it is probably my fault and I would like to know. Thanks.7.4Examplesfactorial.py#defines a function that calculates the factorialdef factorial(n):if n <= 1:return 1return n*factorial(n-1)printprintprintprint"2!"3!"4!"5!====",factorial(2)",factorial(3)",factorial(4)",factorial(5)Output:2!3!4!5!====2624120temperature2.py34Chapter 7.

Defining Functions#converts temperature to fahrenheit or celsiusdef print_options():print "Options:"print " ’p’ print options"print " ’c’ convert from celsius"print " ’f’ convert from fahrenheit"print " ’q’ quit the program"def celsius_to_fahrenheit(c_temp):return 9.0/5.0*c_temp+32def fahrenheit_to_celsius(f_temp):return (f_temp - 32.0)*5.0/9.0choice = "p"while choice != "q":if choice == "c":temp = input("Celsius temperature:")print "Fahrenheit:",celsius_to_fahrenheit(temp)elif choice == "f":temp = input("Fahrenheit temperature:")print "Celsius:",fahrenheit_to_celsius(temp)elif choice != "q":print_options()choice = raw_input("option:")Sample Run:> python temperature2.pyOptions:’p’ print options’c’ convert from celsius’f’ convert from fahrenheit’q’ quit the programoption:cCelsius temperature:30Fahrenheit: 86.0option:fFahrenheit temperature:60Celsius: 15.5555555556option:qarea2.py7.4.

Examples35#By Amos Satterleeprintdef hello():print ’Hello!’def area(width,height):return width*heightdef print_welcome(name):print ’Welcome,’,namename = raw_input(’Your Name: ’)hello(),print_welcome(name)printprint ’To find the area of a rectangle,’print ’Enter the width and height below.’printw = input(’Width: ’)while w <= 0:print ’Must be a positive number’w = input(’Width: ’)h = input(’Height: ’)while h <= 0:print ’Must be a positive number’h = input(’Height: ’)print ’Width =’,w,’ Height =’,h,’ so Area =’,area(w,h)Sample Run:Your Name: JoshHello!Welcome, JoshTo find the area of a rectangle,Enter the width and height below.Width:Must beWidth:Height:Width =7.5-4a positive number434 Height = 3 so Area = 12ExercisesRewrite the area.py program done in 3.2 to have a separate function for the area of a square, the area of a rectangle,and the area of a circle.

(3.14 * radius**2). This program should include a menu interface.36Chapter 7. Defining FunctionsCHAPTEREIGHTLists8.1Variables with more than one valueYou have already seen ordinary variables that store a single value. However other variable types can hold more thanone value. The simplest type is called a list. Here is a example of a list being used:which_one = input("What month (1-12)? ")months = [’January’, ’February’, ’March’, ’April’, ’May’, ’June’, ’July’,\’August’, ’September’, ’October’, ’November’, ’December’]if 1 <= which_one <= 12:print "The month is",months[which_one - 1]and a output example:What month (1-12)? 3The month is MarchIn this example the months is a list.

months is defined with the lines months = [’January’,’February’, ’March’, ’April’, ’May’, ’June’, ’July’,\ ’August’, ’September’,’October’, ’November’, ’December’] (Note that a \ can be used to split a long line). The [ and ] startand end the list with comma’s (“,”) separating the list items. The list is used in months[which_one - 1]. A listconsists of items that are numbered starting at 0. In other words if you wanted January you would use months[0].Give a list a number and it will return the value that is stored at that location.The statement if 1 <= which one <= 12: will only be true if which one is between one and twelve inclusive (in other words it is what you would expect if you have seen that in algebra).Lists can be thought of as a series of boxes.

For example, the boxes created by demolist = [’life’,42,’the universe’, 6,’and’,7] would look like this:box numberdemolist0‘life’1422‘the universe’364‘and’57Each box is referenced by its number so the statement demolist[0] would get ’life’, demolist[1] wouldget 42 and so on up to demolist[5] getting 7.8.2More features of listsThe next example is just to show a lot of other stuff lists can do (for once I don’t expect you to type it in, but youshould probably play around with lists until you are comfortable with them.). Here goes:37demolist = [’life’,42, ’the universe’, 6,’and’,7]print ’demolist = ’,demolistdemolist.append(’everything’)print "after ’everything’ was appended demolist is now:"print demolistprint ’len(demolist) =’, len(demolist)print ’demolist.index(42) =’,demolist.index(42)print ’demolist[1] =’, demolist[1]#Next we will loop through the listc = 0while c < len(demolist):print ’demolist[’,c,’]=’,demolist[c]c = c + 1del demolist[2]print "After ’the universe’ was removed demolist is now:"print demolistif ’life’ in demolist:print "’life’ was found in demolist"else:print "’life’ was not found in demolist"if ’amoeba’ in demolist:print "’amoeba’ was found in demolist"if ’amoeba’ not in demolist:print "’amoeba’ was not found in demolist"demolist.sort()print ’The sorted demolist is ’,demolistThe output is:demolist = [’life’, 42, ’the universe’, 6, ’and’, 7]after ’everything’ was appended demolist is now:[’life’, 42, ’the universe’, 6, ’and’, 7, ’everything’]len(demolist) = 7demolist.index(42) = 1demolist[1] = 42demolist[ 0 ]= lifedemolist[ 1 ]= 42demolist[ 2 ]= the universedemolist[ 3 ]= 6demolist[ 4 ]= anddemolist[ 5 ]= 7demolist[ 6 ]= everythingAfter ’the universe’ was removed demolist is now:[’life’, 42, 6, ’and’, 7, ’everything’]’life’ was found in demolist’amoeba’ was not found in demolistThe sorted demolist is [6, 7, 42, ’and’, ’everything’, ’life’]This example uses a whole bunch of new functions.

Notice that you can just print a whole list. Next the appendfunction is used to add a new item to the end of the list. len returns how many items are in a list. The valid indexes (asin numbers that can be used inside of the []) of a list range from 0 to len - 1. The index function tell where the firstlocation of an item is located in a list. Notice how demolist.index(42) returns 1 and when demolist[1] isrun it returns 42. The line #Next we will loop through the list is a just a reminder to the programmer(also called a comment). Python will ignore any lines that start with a #.

Next the lines:38Chapter 8. Listsc = 0while c < len(demolist):print ’demolist[’,c,’]=’,demolist[c]c = c + 1Create a variable c which starts at 0 and is incremented until it reaches the last index of the list. Meanwhile the printstatement prints out each element of the list.The del command can be used to remove a given element in a list. The next few lines use the in operator to test if aelement is in or is not in a list.The sort function sorts the list. This is useful if you need a list in order from smallest number to largest or alphabetical. Note that this rearranges the list.In summary for a list the following operations occur:examplelist[2]list[2] = 3del list[2]len(list)"value" in list"value" not in listlist.sort()list.index("value")list.append("value")explanationaccesses the element at index 2sets the element at index 2 to be 3removes the element at index 2returns the length of listis true if "value" is an element in listis true if "value" is not an element in listsorts listreturns the index of the first place that "value" occursadds an element "value" at the end of the listThis next example uses these features in a more useful way:8.2.

More features of lists39menu_item = 0list = []while menu_item != 9:print "--------------------"print "1. Print the list"print "2. Add a name to the list"print "3. Remove a name from the list"print "4. Change an item in the list"print "9. Quit"menu_item = input("Pick an item from the menu: ")if menu_item == 1:current = 0if len(list) > 0:while current < len(list):print current,". ",list[current]current = current + 1else:print "List is empty"elif menu_item == 2:name = raw_input("Type in a name to add: ")list.append(name)elif menu_item == 3:del_name = raw_input("What name would you like to remove: ")if del_name in list:item_number = list.index(del_name)del list[item_number]#The code above only removes the first occurance of# the name. The code below from Gerald removes all.#while del_name in list:#item_number = list.index(del_name)#del list[item_number]else:print del_name," was not found"elif menu_item == 4:old_name = raw_input("What name would you like to change: ")if old_name in list:item_number = list.index(old_name)new_name = raw_input("What is the new name: ")list[item_number] = new_nameelse:print old_name," was not found"print "Goodbye"And here is part of the output:40Chapter 8.

Характеристики

Тип файла
PDF-файл
Размер
201,87 Kb
Тип материала
Высшее учебное заведение

Список файлов книги

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