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

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

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

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

Print Menu"print "6. Exit"def print_all_grades():print ’\t’,for i in range(len(assignments)):print assignments[i],’\t’,printkeys = students.keys()keys.sort()for x in keys:print x,’\t’,grades = students[x]print_grades(grades)def print_grades(grades):for i in range(len(grades)):print grades[i],’\t\t’,print55print_menu()menu_choice = 0while menu_choice != 6:printmenu_choice = input("Menu Choice (1-6):")if menu_choice == 1:name = raw_input("Student to add:")students[name] = [0]*len(max_points)elif menu_choice == 2:name = raw_input("Student to remove:")if students.has_key(name):del students[name]else:print "Student: ",name," not found"elif menu_choice == 3:print_all_grades()elif menu_choice == 4:print "Record Grade"name = raw_input("Student:")if students.has_key(name):grades = students[name]print "Type in the number of the grade to record"print "Type a 0 (zero) to exit"for i in range(len(assignments)):print i+1,’ ’,assignments[i],’\t’,printprint_grades(grades)which = 1234while which != -1:which = input("Change which Grade:")which = which-1if 0 <= which < len(grades):grade = input("Grade:")grades[which] = gradeelif which != -1:print "Invalid Grade Number"else:print "Student not found"elif menu_choice != 6:print_menu()and here is a sample output:1.2.3.4.5.6.Add studentRemove studentPrint gradesRecord gradePrint MenuExitMenu Choice (1-6):3hw ch 1#Max2556hw ch 225quiz50hw ch 325test100Chapter 11.

DictionariesMenu Choice (1-6):61. Add student2. Remove student3. Print grades4. Record grade5. Print Menu6. ExitMenu Choice (1-6):1Student to add:BillMenu Choice (1-6):4Record GradeStudent:BillType in the number of the grade to recordType a 0 (zero) to exit1hw ch 12hw ch 23quiz000Change which Grade:1Grade:25Change which Grade:2Grade:24Change which Grade:3Grade:45Change which Grade:4Grade:23Change which Grade:5Grade:95Change which Grade:0Menu Choice (1-6):3hw ch 1#Max25Bill25hw ch 22524quiz504540hw ch 3hw ch 3252350testtest10095Menu Choice (1-6):6Heres how the program works.

Basically the variable students is a dictionary with the keys being the nameof the students and the values being their grades. The first two lines just create two lists. The next linestudents = {’#Max’:max_points} creates a new dictionary with the key #Max and the value is set to be[25,25,50,25,100] (since thats what max_points was when the assignment is made) (I use the key #Maxsince # is sorted ahead of any alphabetic characters).

Next print_menu is defined. Next the print_all_gradesfunction is defined in the lines:57def print_all_grades():print ’\t’,for i in range(len(assignments)):print assignments[i],’\t’,printkeys = students.keys()keys.sort()for x in keys:print x,’\t’,grades = students[x]print_grades(grades)Notice how first the keys are gotten out of the students dictionary with the keys function in the line keys =students.keys() . keys is a list so all the functions for lists can be used on it. Next the keys are sorted in theline keys.sort() since it is a list.

for is used to go through all the keys. The grades are stored as a list insidethe dictionary so the assignment grades = students[x] gives grades the list that is stored at the key x. Thefunction print_grades just prints a list and is defined a few lines later.The later lines of the program implement the various options of the menu.The linestudents[name] = [0]*len(max_points) adds a student to the key of their name.

The notation[0]*len(max_points) just creates a array of 0’s that is the same length as the max_points list.The remove student entry just deletes a student similar to the telephone book example. The record grades choice isa little more complex. The grades are retrieved in the line grades = students[name] gets a reference to thegrades of the student name. A grade is then recorded in the line grades[which] = grade. You may notice thatgrades is never put back into the students dictionary (as in no students[name] = grades). The reason forthe missing statement is that grades is actually another name for students[name] and so changing gradeschanges student[name].Dictionaries provide a easy way to link keys to values.

This can be used to easily keep track of data that is attached tovarious keys.58Chapter 11. DictionariesCHAPTERTWELVUsing ModulesHere’s this chapter’s typing exercise (name it cal.py)1 :import calendaryear = input("Type in the year number:")calendar.prcal(year)And here is part of the output I got:Type in the year number:20012001Mo18152229Tu29162330JanuaryWe Th Fr3 4 510 11 1217 18 1924 25 2631Sa6132027Su7142128FebruaryMo Tu We Th Fr1 25 6 7 8 912 13 14 15 1619 20 21 22 2326 27 28Sa3101724Su4111825MarchMo Tu We Th Fr1 25 6 7 8 912 13 14 15 1619 20 21 22 2326 27 28 29 30Sa310172431Su4111825(I skipped some of the output, but I think you get the idea.) So what does the program do? The first line importcalendar uses a new command import. The command import loads a module (in this case the calendarmodule). To see the commands available in the standard modules either look in the library reference for python(if you downloaded it) or go to http://www.python.org/doc/current/lib/lib.html.

The calendarmodule is described in 5.9. If you look at the documentation lists a function called prcal that prints a calendar for ayear. The line calendar.prcal(year) uses the function. In summary to use a module import it and then usemodule name.function for functions in the module. Another way to write the program is:from calendar import prcalyear = input("Type in the year number:")prcal(year)This version imports a specific function from a module. Here is another program that uses the Python Library (nameit something like clock.py) (press Ctrl and the ’c’ key at the same time to kill the program):1 import actually looks for a file named calendar.py and reads it in. If the file is named calendar.py and it sees a ’import calendar’ it tries to readin itself which works poorly at best.59from time import time, ctimeprev_time = ""while(1):the_time = ctime(time())if(prev_time != the_time):print "The time is:",ctime(time())prev_time = the_timeWith some output being:The time is: Sun Aug 20 13:40:04The time is: Sun Aug 20 13:40:05The time is: Sun Aug 20 13:40:06The time is: Sun Aug 20 13:40:07Traceback (innermost last):File "clock.py", line 5, in ?the_time = ctime(time())KeyboardInterrupt2000200020002000The output is infinite of course so I canceled it (or the output at least continues until Ctrl+C is pressed).

The programjust does a infinite loop and each time checks to see if the time has changed and prints it if it has. Notice how multiplenames after the import statement are used in the line from time import time, ctime.The Python Library contains many useful functions. These functions give your programs more abilities and many ofthem can simplify programming in Python.12.1ExercisesRewrite the high low.py program from section 5.2 to use the last two digits of time at that moment to be the ’random’number.60Chapter 12. Using ModulesCHAPTERTHIRTEENMore on ListsWe have already seen lists and how they can be used. Now that you have some more background I will go into moredetail about lists.

First we will look at more ways to get at the elements in a list and then we will talk about copyingthem.Here are some examples of using indexing to access a single element of an list:>>> list = [’zero’,’one’,’two’,’three’,’four’,’five’]>>> list[0]’zero’>>> list[4]’four’>>> list[5]’five’All those examples should look familiar to you. If you want the first item in the list just look at index 0.

The seconditem is index 1 and so on through the list. However what if you want the last item in the list? One way could be touse the len function like list[len(list)-1]. This way works since the len function always returns the lastindex plus one. The second from the last would then be list[len(list)-2]. There is an easier way to do this.In Python the last item is always index -1.

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

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

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

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