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

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

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

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

. . .And here is the program:number = 5while number > 1:print ".",number = number - 1printThis program will be more complex to walkthrough since it now has indented portions (or control structures). Let usbegin.Question: What is the first line to be run?Answer: The first line of the file: number = 5Question: What does it do?Answer: Puts the number 5 in the variable number.Question: What is the next line?Answer: The next line is: while number > 1:Question: What does it do?Answer: Well, while statements in general look at their expression, and if it is true they do the next indented blockof code, otherwise they skip the next indented block of code.Question: So what does it do right now?Answer: If number > 1 is true then the next two lines will be run.Question: So is number > 1?Answer: The last value put into number was 5 and 5 > 1 so yes.Question: So what is the next line?Answer: Since the while was true the next line is: print ".",Question: What does that line do?Answer: Prints one dot and since the statement ends with a , the next print statement will not be on a different screen6.3.

What does the program do?25line.Question: What is the next line?Answer: number = number - 1 since that is following line and there are no indent changes.Question: What does it do?Answer: It calculates number - 1, which is the current value of number (or 5) subtracts 1 from it, and makes thatthe new value of number.

So basically it changes number’s value from 5 to 4.Question: What is the next line?Answer: Well, the indent level decreases so we have to look at what type of control structure it is. It is a while loop,so we have to go back to the while clause which is while number > 1:Question: What does it do?Answer: It looks at the value of number, which is 4, and compares it to 1 and since 4 > 1 the while loop continues.Question: What is the next line?Answer: Since the while loop was true, the next line is: print ".",Question: What does it do?Answer: It prints a second dot on the line.Question: What is the next line?Answer: No indent change so it is: number = number - 1Question: And what does it do?Answer: It talks the current value of number (4), subtracts 1 from it, which gives it 3 and then finally makes 3 the newvalue of number.Question: What is the next line?Answer: Since there is an indent change caused by the end of the while loop, the next line is: while number > 1:Question: What does it do?Answer: It compares the current value of number (3) to 1.

3 > 1 so the while loop continues.Question: What is the next line?Answer: Since the while loop condition was true the next line is: print ".",Question: And it does what?Answer: A third dot is printed on the line.Question: What is the next line?Answer: It is: number = number - 1Question: What does it do?Answer: It takes the current value of number (3) subtracts from it 1 and makes the 2 the new value of number.Question: What is the next line?Answer: Back up to the start of the while loop: while number > 1:Question: What does it do?Answer: It compares the current value of number (2) to 1. Since 2 > 1 the while loop continues.Question: What is the next line?Answer: Since the while loop is continuing: print ".",26Chapter 6.

DebuggingQuestion: What does it do?Answer: It discovers the meaning of life, the universe and everything. I’m joking. (I had to make sure you wereawake.) The line prints a fourth dot on the screen.Question: What is the next line?Answer: It’s: number = number - 1Question: What does it do?Answer: Takes the current value of number (2) subtracts 1 and makes 1 the new value of number.Question: What is the next line?Answer: Back up to the while loop: while number > 1:Question: What does the line do?Answer: It compares the current value of number (1) to 1. Since 1 > 1 is false (one is not greater than one), thewhile loop exits.Question: What is the next line?Answer: Since the while loop condition was false the next line is the line after the while loop exits, or: printQuestion: What does that line do?Answer: Makes the screen go to the next line.Question: Why doesn’t the program print 5 dots?Answer: The loop exits 1 dot too soon.Question: How can we fix that?Answer: Make the loop exit 1 dot later.Question: And how do we do that?Answer: There are several ways.

One way would be to change the while loop to: while number > 0: Anotherway would be to change the conditional to: number >= 1 There are a couple others.6.4How do I fix the program?You need to figure out what the program is doing. You need to figure out what the program should do. Figure out whatthe difference between the two is. Debugging is a skill that has to be done to be learned. If you can’t figure it out afteran hour or so take a break, talk to someone about the problem or contemplate the lint in your navel.

Come back in awhile and you will probably have new ideas about the problem. Good luck.6.4. How do I fix the program?2728CHAPTERSEVENDefining Functions7.1Creating FunctionsTo start off this chapter I am going to give you a example of what you could do but shouldn’t (so don’t type it in):a = 23b = -23if a < 0:a = -aif b < 0:b = -bif a == b:print "The absolute values of", a,"and",b,"are equal"else:print "The absolute values of a and b are different"with the output being:The absolute values of 23 and 23 are equalThe program seems a little repetitive. (Programmers hate to repeat things (That’s what computers are for aren’t they?))Fortunately Python allows you to create functions to remove duplication. Here’s the rewritten example:a = 23b = -23def my_abs(num):if num < 0:num = -numreturn numif my_abs(a) == my_abs(b):print "The absolute values of", a,"and",b,"are equal"else:print "The absolute values of a and b are different"with the output being:29The absolute values of 23 and -23 are equalThe key feature of this program is the def statement.

def (short for define) starts a function definition. def isfollowed by the name of the function my abs. Next comes a ( followed by the parameter num (num is passed fromthe program into the function when the function is called). The statements after the : are executed when the functionis used. The statements continue until either the indented statements end or a return is encountered. The returnstatement returns a value back to the place where the function was called.Notice how the values of a and b are not changed. Functions of course can be used to repeat tasks that don’t returnvalues.

Here’s some examples:def hello():print "Hello"def area(width,height):return width*heightdef print_welcome(name):print "Welcome",namehello()hello()print_welcome("Fred")w = 4h = 5print "width =",w,"height =",h,"area =",area(w,h)with output being:HelloHelloWelcome Fredwidth = 4 height = 5 area = 20That example just shows some more stuff that you can do with functions. Notice that you can use no arguments or twoor more. Notice also when a function doesn’t need to send back a value, a return is optional.7.2Variables in functionsOf course, when eliminiating repeated code, you often have variables in the repeated code.

These are dealt with in aspecial way in Python. Up till now, all variables we have see are global variables. Functions have a special type ofvariable called local variables. These variables only exist while the function is running. When a local variable has thesame name as another variable such as a global variable, the local variable hides the other variable. Sound confusing?Well, hopefully this next example (which is a bit contrived) will clear things up.30Chapter 7. Defining Functionsa_var = 10b_var = 15e_var = 25def a_func(a_var):print "in a_func a_varb_var = 100 + a_vard_var = 2*a_varprint "in a_func b_varprint "in a_func d_varprint "in a_func e_varreturn b_var + 10= ",a_var= ",b_var= ",d_var= ",e_varc_var = a_func(b_var)printprintprintprint"a_var"b_var"c_var"d_var====",a_var",b_var",c_var",d_varThe output is:in a_func a_var = 15in a_func b_var = 115in a_func d_var = 30in a_func e_var = 25a_var = 10b_var = 15c_var = 125d_var =Traceback (innermost last):File "separate.py", line 20, in ?print "d_var = ",d_varNameError: d_varIn this example the variables a var, b var, and d var are all local variables when they are inside the function a func.

After the statement return b var + 10 is run, they all cease to exist. The variable a var isautomatically a local variable since it is a parameter name. The variables b var and d var are local variablessince they appear on the left of an equals sign in the function in the statements b_var = 100 + a_var andd_var = 2*a_var .Inside of the function a var is 15 since the function is called with a func(b var). Since at that point in timeb var is 15, the call to the function is a func(15) This ends up setting a var to 15 when it is inside of a func.As you can see, once the function finishes running, the local variables a var and b var that had hidden the globalvariables of the same name are gone. Then the statement print "a_var = ",a_var prints the value 10 ratherthan the value 15 since the local variable that hid the global variable is gone.Another thing to notice is the NameError that happens at the end.

This appears since the variable d var no longerexists since a func finished. All the local variables are deleted when the function exits. If you want to get somethingfrom a function, then you will have to use return something.One last thing to notice is that the value of e var remains unchanged inside a func since it is not a parameter andit never appears on the left of an equals sign inside of the function a func. When a global variable is accessed insidea function it is the global variable from the outside.7.2.

Variables in functions31Functions allow local variables that exist only inside the function and can hide other variables that are outside thefunction.7.3Function walkthroughTODO Move this section to a new chapter, Advanced Functions.Now we will do a walk through for the following program:def mult(a,b):if b == 0:return 0rest = mult(a,b - 1)value = a + restreturn valueprint "3*2 = ",mult(3,2)Basically this program creates a positive integer multiplication function (that is far slower than the built in multiplication function) and then demonstrates this function with a use of the function.Question: What is the first thing the program does?Answer: The first thing done is the function mult is defined with the lines:def mult(a,b):if b == 0:return 0rest = mult(a,b - 1)value = a + restreturn valueThis creates a function that takes two parameters and returns a value when it is done.

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

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

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

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