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

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

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

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

The string is split by spaces by default or by the optionalsecond argument (in this case a comma).70Chapter 14. Revenge of the Strings14.1Examples#This program requires a excellent understanding of decimal numbersdef to_string(in_int):"Converts an integer to a string"out_str = ""prefix = ""if in_int < 0:prefix = "-"in_int = -in_intwhile in_int / 10 != 0:out_str = chr(ord(’0’)+in_int % 10) + out_strin_int = in_int / 10out_str = chr(ord(’0’)+in_int % 10) + out_strreturn prefix + out_strdef to_int(in_str):"Converts a string to an integer"out_num = 0if in_str[0] == "-":multiplier = -1in_str = in_str[1:]else:multiplier = 1for x in range(0,len(in_str)):out_num = out_num * 10 + ord(in_str[x]) - ord(’0’)return out_num * multiplierprintprintprintprintprintprintto_string(2)to_string(23445)to_string(-23445)to_int("14234")to_int("12345")to_int("-3512")The output is:223445-234451423412345-351214.1.

Examples7172CHAPTERFIFTEENFile IOHere is a simple example of file IO:#Write a fileout_file = open("test.txt","w")out_file.write("This Text is going to out file\nLook at it and see\n")out_file.close()#Read a filein_file = open("test.txt","r")text = in_file.read()in_file.close()print text,The output and the contents of the file test.txt are:This Text is going to out fileLook at it and seeNotice that it wrote a file called test.txt in the directory that you ran the program from.

The \n in the string tellsPython to put a newline where it is.A overview of file IO is:1. Get a file object with the open function.2. Read or write to the file object (depending on how it was opened)3. Close itThe first step is to get a file object. The way to do this is to use the open function. The format isfile_object = open(filename,mode) where file_object is the variable to put the file object,filename is a string with the filename, and mode is either "r" to read a file or "w" to write a file. Next thefile objects functions can be called. The two most common functions are read and write.

The write functionadds a string to the end of the file. The read function reads the next thing in the file and returns it as a string. If noargument is given it will return the whole file (as done in the example).Now here is a new version of the phone numbers program that we made earlier:73import stringtrue = 1false = 0def print_numbers(numbers):print "Telephone Numbers:"for x in numbers.keys():print "Name: ",x," \tNumber: ",numbers[x]printdef add_number(numbers,name,number):numbers[name] = numberdef lookup_number(numbers,name):if numbers.has_key(name):return "The number is "+numbers[name]else:return name+" was not found"def remove_number(numbers,name):if numbers.has_key(name):del numbers[name]else:print name," was not found"def load_numbers(numbers,filename):in_file = open(filename,"r")while true:in_line = in_file.readline()if in_line == "":breakin_line = in_line[:-1][name,number] = string.split(in_line,",")numbers[name] = numberin_file.close()def save_numbers(numbers,filename):out_file = open(filename,"w")for x in numbers.keys():out_file.write(x+","+numbers[x]+"\n")out_file.close()def print_menu():print ’1.

Print Phone Numbers’print ’2. Add a Phone Number’print ’3. Remove a Phone Number’print ’4. Lookup a Phone Number’print ’5. Load numbers’print ’6. Save numbers’print ’7. Quit’print74Chapter 15. File IOphone_list = {}menu_choice = 0print_menu()while menu_choice != 7:menu_choice = input("Type in a number (1-7):")if menu_choice == 1:print_numbers(phone_list)elif menu_choice == 2:print "Add Name and Number"name = raw_input("Name:")phone = raw_input("Number:")add_number(phone_list,name,phone)elif menu_choice == 3:print "Remove Name and Number"name = raw_input("Name:")remove_number(phone_list,name)elif menu_choice == 4:print "Lookup Number"name = raw_input("Name:")print lookup_number(phone_list,name)elif menu_choice == 5:filename = raw_input("Filename to load:")load_numbers(phone_list,filename)elif menu_choice == 6:filename = raw_input("Filename to save:")save_numbers(phone_list,filename)elif menu_choice == 7:passelse:print_menu()print "Goodbye"Notice that it now includes saving and loading files.

Here is some output of my running it twice:75> python tele2.py1. Print Phone Numbers2. Add a Phone Number3. Remove a Phone Number4. Lookup a Phone Number5. Load numbers6. Save numbers7. QuitType in a number (1-7):2Add Name and NumberName:JillNumber:1234Type in a number (1-7):2Add Name and NumberName:FredNumber:4321Type in a number (1-7):1Telephone Numbers:Name: JillNumber: 1234Name: FredNumber: 4321Type in a number (1-7):6Filename to save:numbers.txtType in a number (1-7):7Goodbye> python tele2.py1. Print Phone Numbers2. Add a Phone Number3. Remove a Phone Number4. Lookup a Phone Number5. Load numbers6.

Save numbers7. QuitType in a number (1-7):5Filename to load:numbers.txtType in a number (1-7):1Telephone Numbers:Name: JillNumber: 1234Name: FredNumber: 4321Type in a number (1-7):7GoodbyeThe new portions of this program are:76Chapter 15. File IOdef load_numbers(numbers,filename):in_file = open(filename,"r")while 1:in_line = in_file.readline()if len(in_line) == 0:breakin_line = in_line[:-1][name,number] = string.split(in_line,",")numbers[name] = numberin_file.close()def save_numbers(numbers,filename):out_file = open(filename,"w")for x in numbers.keys():out_file.write(x+","+numbers[x]+"\n")out_file.close()First we will look at the save portion of the program. First it creates a file object with the commandopen(filename,"w").

Next it goes through and creates a line for each of the phone numbers with the command out_file.write(x+","+numbers[x]+"\n"). This writes out a line that contains the name, a comma,the number and follows it by a newline.The loading portion is a little more complicated.It starts by getting a file object.Then it uses awhile 1: loop to keep looping until a break statement is encountered. Next it gets a line with the linein_line = in_file.readline(). The readline function will return a empty string (len(string) == 0)when the end of the file is reached.

The if statement checks for this and breaks out of the while loop when thathappens. Of course if the readline function did not return the newline at the end of the line there would be no wayto tell if an empty string was an empty line or the end of the file so the newline is left in what readline returns.Hence we have to get rid of the newline. The line in_line = in_line[:-1] does this for us by dropping thelast character.

Next the line [name,number] = string.split(in_line,",") splits the line at the commainto a name and a number. This is then added to the numbers dictionary.15.1ExercisesNow modify the grades program from section 11 so that is uses file IO to keep a record of the students.15.1. Exercises7778CHAPTERSIXTEENDealing with the imperfect (or how tohandle errors)So you now have the perfect program, it runs flawlessly, except for one detail, it will crash on invalid user input. Haveno fear, for Python has a special control structure for you. It’s called try and it tries to do something.

Here is anexample of a program with a problem:print "Type Control C or -1 to exit"number = 1while number != -1:number = int(raw_input("Enter a number: "))print "You entered: ",numberNotice how when you enter @#& it outputs something like:Traceback (innermost last):File "try_less.py", line 4, in ?number = int(raw_input("Enter a number: "))ValueError: invalid literal for int(): @#&As you can see the int function is unhappy with the number @#& (as well it should be).

The last line shows what theproblem is; Python found a ValueError. How can our program deal with this? What we do is first: put the placewhere the errors occurs in a try block, and second: tell Python how we want ValueErrors handled. The followingprogram does this:print "Type Control C or -1 to exit"number = 1while number != -1:try:number = int(raw_input("Enter a number: "))print "You entered: ",numberexcept ValueError:print "That was not a number."Now when we run the new program and give it @#& it tells us “That was not a number.” and continues with what itwas doing before.When your program keeps having some error that you know how to handle, put code in a try block, and put the wayto handle the error in the except block.7916.1ExercisesUpdate at least the phone numbers program so it doesn’t crash if a user doesn’t enter any data at the menu.80Chapter 16.

Dealing with the imperfect (or how to handle errors)CHAPTERSEVENTEENThe EndI have run out of interest in adding more to this tutorial.However, I have put it up on Wikibooks athttp://wikibooks.org/wiki/User:Jrincayc/Contents, where you can edit it and discuss it. For the moment I recommendlooking at The Python Tutorial by Guido van Rossum. You should be able to understand a fair amount of it.This tutorial is very much a work in progress.

Thanks to everyone who has emailed me. If you have comments, Iwould recomend that you put them on the Wikibooks version (Note the discussion link on each page) so that everyonecan discuss and think about them.Happy programming, may it change your life and the world.TODO=[ ’errors’,’how to make modules’,’more on loops’,’more on strings’, ’file io’,’how to use onlinehelp’,’try’,’pickle’,’anything anyone suggests that I think is a good idea’]8182CHAPTEREIGHTEENFAQCan’t use programs with input.

If you are using IDLE then try using command line. This problem seems to be fixedin IDLE 0.6 and newer. If you are using an older version of IDLE try upgrading to Python 2.0 or newer.Is there a printable version? Yes, see the next question.Is there a PDF or zipped version? Yes, go to http://www.honors.montana.edu/˜jjc/easytut/ for several different versions.What is the tutorial written with? LATEX, see the ‘easytut.tex’ file.I can’t type in programs of more than one line. If the programs that you type in run as soon as you are typing themin, you need to edit a file instead of typing them in interactive mode. (Hint: interactive mode is the mode withthe >>> prompt in front of it.)My question is not answered here. Email me and ask.

Please send me source code if at all relevent (even, (or maybeespecially) if it doesn’t work). Helpful things to include are what you were trying to do, what happened, whatyou expected to happen, error messages, version of Python, Operating System, and whether or not your cat wasstepping on the keyboard. (The cat in my house has a fondness for space bars and control keys.)I want to read it in a different language.

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

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

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

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