start python

Upload: maher-melki

Post on 06-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Start Python

    1/29

    Start Programming

    withPython

    by

    Bryce Embry

    www.bembry.org

  • 8/3/2019 Start Python

    2/29

    Start Programming with Python --2Table of Contents:

    Lesson Topic Sample Program

    Starting Out Basic Operations IDLE practice

    Lesson 1 Variables Customized hello

    Lesson 2 String Operators Print a sentence 100 times

    Lesson 3 Data Types Print a sentence as many times as you want

    Lesson 4 Random Text Random text ... almost

    Lesson 5 Loops Random text, really

    Lesson 6 All together now ... Random Password

    Lesson 7 If ... else tests Testing a password

    Lesson 8 String indexes and slices Name-based password

    Lesson 9 Reading text file Password based on word in text file

    Lesson 10 Readlines and iterations Multiple passwords based on text file

    Lesson 11 Saving to a file Saving passwords

    Example 1 Batch Editing File Names

    Example 2 Batch Edit Text Files in Directory

    Appendix A Hello World Language Comparisons

    Appendix B Resources for Further Learning

    Appendix C Extending Python Capabilities

    Copyright (c) 2002 Bryce EmbryPermission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License,Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Section, with the Front-Cover Texts

    being Start Programming with Python by Bryce Embry (www.bembry.org)", and with no Back-Cover Texts. A copy of the license isincluded in the section entitled "GNU Free Documentation License".

  • 8/3/2019 Start Python

    3/29

    Start Programming with Python --3Starting OutSo, you want to program? Well, first you have to choose a language. Lots of folks want to start out bylearning Java or C++, thinking they'll earn millions of dollars if they can master one of these quickly. But bothof these languages are rather complicated; it takes half a dozen lines of code just to say Hello world. C++and Java have earned their reputation as powerful languages, but wouldn't it be nice to learn a powerfullanguage that wasn't so complicated? If that dream sounds good to you, let me introduce you to Python.

    Python is an open-source object-oriented programming language that combines the power of Java with asimplicity all its own. The Python language is used to build powerful programs, has a friendly and supportiveuser community, and can help you create the tools you need faster than you could in Java or C++. Some folksclaim it is the best programming language in the world. There's only one way to find out let's try it.

    Before we can start writing programs in Python we need to install the Python interpreter. Python is aninterpreted language, which means that the Python interpreter must be installed on a computer before it canrun the code we write in Python. The Python interpreter is available free at www.python.org for Windows,Mac OS, and Linux, so many Python programs can be run on any operating system without changes.

    We are going to start out writing code in IDLE, the interactive interpreter environment that comes withPython. So, once you have Python installed, fire up the IDLE program (Python GUI) and let's start playing.

    Code:Type these lines in the Python interpreter IDLE. Press enter after each line.

    print "hello world"print 3*4print 3**2print 3/4print 3.0/4print 11%5import calendarcalendar.prcal(2002)

    The division results may not make sense at first because Python handles integers and decimals differently.When two whole numbers (integers) are divided, Python returns the resulting integer portion of the quotientonly. So 3/2 yields 1, and 1/2 yields 0.

    Points to Remember:The Python interpreter must be installed on a computer in order to run Python programs.Python commands can be run in the interactive interpreter.Python is case sensitive. Print is not the same as print.

    To have Python print text, the text must be enclosed in quotation marks.The mathematic operators in Python are:

    + add- subtract* multiply/ divide** exponential power % remainder

    When two whole numbers (integers) are divided, Python returns only the integer (whole number)portion of the quotient.

  • 8/3/2019 Start Python

    4/29

    Start Programming with Python --4Program 1: VariablesNow that we've played around in the interpreter, it's time to start our first program. We've gotten Python tosay Hello, now can we get it to call the user by his name?

    For all of the programs we write we are going to use the text editor instead of the interactive interpreter. Inthe interactive interpreter, our code is executed immediately and then lost. When we us a text editor, we canwrite out the whole program, save it, and then have Python run it all at once. Technically, we could writePython code in Notepad or any other text editor, Python comes with a special editor that has some usefulfeatures. To get to this editor, in the IDLE interpreter click File --> New Window.

    When we save a program, we must save it with the extension .py so that Python will recognize it as code.This code file can be executed from a DOS prompt by typing either myscript.py or python myscript.py,depending on your installation of Python. Usually, though, we'll run our programs by clicking Edit --> RunScript in the IDLE text editor. Or, if we are really lazy, we'll press [Ctrl] [F5] to run the program.

    Now that we're writing code in the text editor, let's figure out how to get our program to personalize its

    greeting. In order to get our program to know our name, we are going to create a variable. Variables are codenames we make up that let us feed information we create in one part of a program to a process in a differentpart of the program. Variable names in Python can be any text we choose as long as it does not start with anumber and is not a reserved Python keyword.

    Chances are that you don't have all the reserved Python keywords memorized, so you may not know whichwords you cannot use as a variable name. This is where writing our code in IDLE comes in handy. Any timeyou type a reserved Python keyword in the IDLE text editor, IDLE colors the word orange. So, if you makeup a variable name and it turns orange, you'll know its a reserved keyword and you can't use that word.

    Code:

    user_name = raw_input("What is your name? ")print "Hello", user_name

    In line one we set our variable name user_name equal to something called raw_input(). This raw_input()creature is a built-in function that asks the user for a response and stores that response in the variable. INquotation marks inside the parentheses, we type the prompt we want the users to see.

    On line two we tell Python to print the word Hello and then print whatever the user typed in. The commabetween Hello and user_name is important. Python does not use a lot of punctuation marks to direct thecode, but the few it uses are important to remember. Here, the comma tells Python that there is more to printon this line after it's done printing Hello.

    Points to Remember:Python code is saved with the extension .py.Code can be executed in IDLE by pressing [Ctrl] [F5]Variable names cannot start with a number.Variable names cannot be keywords reserved by Python.In Python, each command must be on a separate line.Python does not use a lot of punctuation, but when it does, it is critical.Values being sent to functions are enclosed in parentheses.

  • 8/3/2019 Start Python

    5/29

    Start Programming with Python --5Program 2: String OperatorsA favorite punishment of some teachers is to make students copy sentences a hundred times. If we could justget the computer to write their sentences for them, we could make life a lot easier on these poor students.

    We've already learned how to let a user type in a sentence and have the program print it out, now we need tofigure out how to do that a hundred times. We could write the print command a hundred times in ourprogram, but that's not any better than having to write I will not talk in school a hundred times, so there hasto be a better way. We could set up a loop that will execute our print command a hundred times, but we aren'tready for that yet. The easiest way to get our computer to print out a sentence one hundred times is to tellPython to multiply our sentence by one hundred.

    Code:

    sentence= raw_input("Enter sentence: ")print sentence*100

    The trick to this code is the second line, which tells Python to multiply our sentence by one hundred and printthe result. When multiplication operator is used on text strings, Python repeats the string as many times as wetell it.

    When you run this program, you'll notice that Python printed the sentence one hundred times, but thesentences are all crammed together. We need some way to tell Python to put each sentence on a new line.Technically, we can do this by adding a newline character to the end of the sentence before printing it.

    Sentence = raw_input("Enter sentence: ")text_line = sentence + \nprint text_line*100

    In line two, the + operator takes our sentence and adds something to the end of it. Who would ever think ofusing + to add text strings together? Go figure.

    That strange \n that we added to our sentence is called an escape character and is the code for a line break.There are a number of escape characters available in Python. They are all preceded by a back-slash and mustbe in a string (quotation marks) to work. These special codes include \t for a tab, \ for a quotation mark(when we want one printed, instead of indicating the end of a string), and \\ when we want a backslash.

    Points to RememberText strings can be repeated by using the * operator.

    Text strings can be added together using the + operator.Special codes can be included in a text string by using escape characters such as:

    \n Newline (line break)\t Tab\ Quotation mark \\ A real, honest-to-goodness, backslash

    Escape characters must be inside quotation marks

  • 8/3/2019 Start Python

    6/29

    Start Programming with Python --6Program 3: Data TypesCome to think of it, teachers don't always make students write a sentence a hundred times. Sometimes theywant you to write a sentence five hundred times, or even more. I remember working at a school whose policywas to assign students writing assignments as punishment. At the end of each day students would comparehow many pages they had to write that night. So, let's expand our program to let the student tell us how manysentences to print out.

    If you're thinking ahead, you might have figured that we could just make another raw_input() statement thatasks the user how many times they want the sentence written, then tell the computer to multiply by thatnumber. Well, that's almost right. The problem we'd have with this approach is that when Python readsinformation from raw_input(), it reads it in as a text string. Telling the program to multiply a sentence by atext string just makes no sense. How can you multiply I will not talk in class by mud?

    In Python, there are different kinds of data. There are strings (text, like words and sentences), integers (wholenumbers), floating point numbers (numbers with decimal values), lists (lists of stuff), and even complexnumbers, long numbers, tuples,and dictionaries (don't ask). Data can be changed from one type to another

    using the correct commands. So, in order to let our troubled user select how many times to print his sentencewe must first ask him for the sentence (a string), ask him how many times he needs the sentence printed (a textstring), then convert his numeral (text string that looks like a number) into an integer. Once we have theinteger, we multiply his sentence by the integer and print it out.

    Code

    sentence = raw_input("Enter sentence: ")text_line = sentence + \nrepeats_entry = raw_input("How many times? ")num_repeats = int(repeats_entry)print text_line * num_repeats

    This program is the same as the one before with the addition of lines three and four. Line three asks the userhow many times he wants his sentence printed. We expect the user to enter a numeral on this line. Line fourtakes the numeral the user typed in and changes it into an integer using the int() function. If the user types in5, it will be changed into the number five and our program will work. If the user types in the word five,the int() function will have no idea what number he wants and will just crash the program. The int() functioncan only change a numeral into an integer, it can't read your mind.

    Points to Remember:Python has different types of data:

    Strings (text)Integers (whole numbers, positive or negative)Floating point numbers (numbers with decimal values)And more ... (long numbers, complex numbers, tuples, lists, dictionaries)

    The raw_input() function imports data as a string (text).Data can be converted from one type to another, if it is in an acceptable form.The int() function changes a numeral into an integer value.

  • 8/3/2019 Start Python

    7/29

    Start Programming with Python --7Program 4: Random TextHaving aided and abetted our miscreants, it's time to turn our attentions to loftier matters garbage text.There comes a time in a geek's life when he wants a chunk of random text. It doesn't matter what it says, aslong as it fills up space and doesn't have a predictable pattern.

    To get Python to print out random text, first we will want a list of words for Python to choose from. Pythonhas a special data type called a list that will just fit our needs. We create a list in Python by placing all thechoices in brackets [ ] and putting a comma between each choice. Our choices can be strings, integers, otherlists, or anything other type of Python data. For our random text, we'll make a list of strings, with each word(or phrase) enclosed in quotation marks to identify it as a string.

    Once we have a list of choices, we will use a special function in Python to randomly choose items from ourlist. Python has a myriad of special functions available. Most of these functions are stored in sets calledmodules and have to be imported into Python before they can be used. Module sets include functions foremail, HTML parsing, sound, network sockets, random selections, calendars, files, operating systemfunctions, and a whole lot more, and they can make a seemingly impossible job very simple. To see a list of

    modules, click Help --> Documentation in IDLE, then select the Module Index. You'll be amazed what allyou can do with just a few commands.

    For our program, we need to import the module called random. That module contains a number of differentfunctions, so we'll have to declare which one we want. The function designed to randomly pick an item out ofa list is called choice. To use this choice function in our code we must identify that choice is a functionfrom the random module, so we call it using the code random.choice(). The random.choice() function needsto know what list to randomly choose its text from, so we put the name of our list inside the parentheses.

    Code

    text_choices = ["dog", "cat", "bird", "fish"]

    repeats_entry = raw_input("How many words? ")num_repeats = int(repeats_entry)import randomword = random.choice(text_choices)print word * num_repeats

    When we run this program it only chooses one key word and prints it over and over. We were really wantingthe program to pick a new word each time. Can you see why this program doesn't do that? To get thisprogram the way we want, we need to learn about looping code, which we'll do next.

    Points to Remember:Lists are contained in brackets [ ] with each item separated by a comma.

    Modules contain pre-made functions for Python.To use the functions in a module, you must import the module first.To call the function, give the module name, a period, and then the function name.The Module Index in the documentation has lots of cool stuff.

  • 8/3/2019 Start Python

    8/29

    Start Programming with Python --8Program 5: LoopsOne of the joys of writing a computer program is making your computer automatically do those repetitivetasks that can drive you crazy, like changing the extension of every file in a directory, creating dozens (orhundreds) of new user accounts, searching through files for a certain word, and so forth. The tasks are routine-- do step A, then B, then C, then D, get a new file, repeat. In programming, we call it a loop.

    The mundane task we want our program to do is pick a new random word, print it, then repeat. Anythingthat we want the program to repeat we put inside the loop, everything else is outside the loop. Inside the loopin our program we need to tell Python to pick a new word and print it, since that is the code we want repeated.We don't need Python to repeat the part about asking us how many words we want, so we'll keep that outsidethe loop.

    To set up our loop, first we create a counter variable. This is a variable that we'll use to keep track of howmany times the program has gone through the loop. We will start this counter at zero and add one to it eachtime the program goes through the loop. It is very important to remember to add one to it during the loop,otherwise our poor little computer will spend the rest of its days printing random text and never increment the

    counter (it will always think it's still on the first pass through the loop). This is a common error to make. Ifyour program seems to be not responding, it may be stuck in a loop. Press [Ctrl] [C] to rescue it.

    We start the loop in our program with the keyword while. Since we know how many words we want, wetell the program while our counter is less than the number of words we want, do this. Actually, we don't sayit exactly like that. We have to phrase the test in the form of a mathematical expression, so it looks more likewhile count < num_repeats. At the end of this line we put a colon to let the program know we are startingthe section of code it is supposed to repeat.

    After we create our while test, we write the instructions we want repeated. Each instruction that is part of ourloop is indented to identify it as part of the special loop program. This indentation doesn't just make the codelook prettier, it is required in Python. The indentation is what Python uses to separate the portion of theprogram that is part of the loop from the portion that is outside the loop.

    Code:

    repeats_entry = raw_input("How many words? ")num_repeats = int(repeats_entry)text_choices = ["dog", "cat", "bird", "fish"]counter = 1import randomwhile counter < num_repeats:

    word = random.choice(text_choices)print wordcounter += 1

    The last line has a nifty little operator, +=. The code means add one to the counter variable and is a shortcutto writing counter = counter + 1. This += operator will work for adding text to a string just as well as it doesin adding a number to an integer. There are also some related operators, such as - = (subtract from variable)and *= (multiply variable by), which can be useful.

    And now, at last, our program does what we want; it creates random text.

  • 8/3/2019 Start Python

    9/29

    Start Programming with Python --9

    Points to Remember:Sections of code can be repeated by placing them in a while loop.A while loop will repeat until the test statement is false.

    Comparison tests use the following syntax:A = = B A equals BA != B A does not equal BA < B A is less than BA > B A is greater than BA = B A is greater than or equal to B

    The while statement must end in a colon.If your program locks up, you may have it caught in an infinite loop.Commands that are part of a loop must be indented.The following operators will manipulate integer variables:

    A += B Add B to A. (Also works for strings.)A - = B Subtract B from AA *= B Multiply A by B. (Also works for strings.)A /= B Divide A by BA **= B Raise A to the power B

  • 8/3/2019 Start Python

    10/29

    Start Programming with Python --10Program 6: Random Password GeneratorIf we can write a program that will generate random text, then what's to stop us from writing a program thatwill generate a random password?

    The main difference between a random text generator and a random password generator is that we areworking with individual letters instead of whole words, and we want to collect all the letters together beforeprinting them. To collect our letters together we create a variable and designate it as an empty string of text.Then, inside a loop, we have the program randomly pick one letter and add it to our variable each time it goesthrough the loop. Once our word is as long as we want it to be, we exit the loop and print the variable. Forthis program, we will name that variable password.

    Once the password is complete, the program should print it out. It is important that our print passwordstatement comes after the loop; otherwise, the program will print each step it takes to build the password (p,pa, pas, pass, and so on). To designate the print statement as being separate from the loop, we dedentit. Dedent is the opposite of indent (bet you never thought about indent having an opposite). In otherwords, we signify that this line of code is outside the loop by aligning it with the while statement itself.

    This makes our code pretty, the logic of the code easier to follow, and is actually required to make theprogram work correctly.

    It is also important that we create that password variable before we start our loop, outside the loop itself. Ifwe put the password = code inside the loop, every time the loop started over the program would set ourpassword variable to be an empty string, effectively erasing any letters that were previously added to ourpassword. With this construction, no matter how many times we went through the loop, our program wouldalways have only one letter in it. That's why we create the password variable outside the loop.

    Code:

    char_list = ["a", "b", "c", "d", "e", "f", "g"]

    length_entry = raw_input(Password length: ")pwd_length = int(length_entry)

    counter = 1password = ""import randomwhile counter

  • 8/3/2019 Start Python

    11/29

    Start Programming with Python --11Program 7: if ... else testsNow that we have a password, let's give our user a chance to test it. Let's add a feature to our program thatlets the user type in the password, then checks if he typed it correctly.

    Our password test needs to have three parts. First, we'll ask the user to enter the password. Next we'llcompare their input with the password created earlier. And finally, depending on whether their input matchesthe password or not, we'll run either the correct code or the incorrect code. Getting the password from theuser is just a matter of using another raw_input(), which we have done before. The new trick we need to learnis how to compare the two words and select with section of code to run. We do this using an if ... else test.

    An if test is something like the while test we did in program five when we worked with loops. For thetest we ask Python to compare two items (in this case two words) and execute the following indented codeonly if the test result is true. In our password testing program, we ask if the word the user entered(user_password_entry) matches the password created earlier in the program. The actual code says ifpassword = = user_password_entry:. We use the = = operator to see if the two text strings are identical,including capitalization. If they are, the indented code beneath will be executed. If they are not identical,

    then the subsequent indented code will be skipped.

    When the if statement is false (the two words don't match), and the associated if commands are skipped,we need to provide an alternative set of code to run. To do this, we create an else portion of code. Anycode in the else section will be executed only when the if portion is skipped. This else code must be thefirst dedented line after the if section, and the commands associated with this else feature must beindented beneath it.

    Code

    # Create random passwordchar_list = ["a", "b", "c", "d", "e", "f", "g"]

    pwd_length_entry = raw_input("Password length: ")pwd_length = int(pwd_length_entry)

    counter = 1password = ""import randomwhile counter

  • 8/3/2019 Start Python

    12/29

    Start Programming with Python --12You'll notice in this code a couple lines that begin with #. The # symbol is used to mark a comment in thecode. Comments are not executed by Python, they are just notes to help humans reading the code.

    Points to Remember:A program can choose one of two sets of code to run based on an if test.An if test compares two or more values and runs the if code when the test is true.An else section of code is run only when the if test is false.The else command must be the first dedented line after the if section of code.Lines beginning with # are comments and will not be processed by Python.

  • 8/3/2019 Start Python

    13/29

    Start Programming with Python --13Program 8: Manipulating StringsIn the real world, truly random passwords provide poor security. They are hard to remember, so users writethe password on a post-it note by the computer, which is bad security. It's usually a better idea to generatepasswords that are only partially random. So, to improve our password program, let's create a program thatmakes a password by taking the first two letters of a user's last name and adding a random number to the end.

    To create such a program, first we want to get a random number. We could use random.choice() to randomlypick a number from a list, but then we'd have to create a list with hundreds of choices, which sounds like a lotof work. To save time, we'll use another function in the random module called randrange(). This functionreturns a random number within a range of numbers we specify. If we set the range from 100 to 999,random.randrange() will return a random three-digit number.

    Once we have a three-digit number, we want to get the first two letters from the user's last name. To get this,we'll ask the user to type in their whole last name then make the program pick the first two letters. Theraw_input() function will get the last name for us, so the trick is how to make the program pick only the firsttwo letters. The easiest way to do this is to use a feature called string slicing.

    In Python, every letter of a string is assigned an index number, which is kind of like an address for accessingthat letter. In the word Python, the letter P is at index 0, y is at index 1, t is at index 2, and so on.Since each letter in a text string has an index address, we can use a special feature in Python to tell it whichcharacters in the text string we want. To get only the first two letters from a text string assigned to thevariable last_name, we say last_name[0:2]. When given this command, Python will get the characters fromindex zero up to index two, but will not actually get the character at index two. If we wanted the first threecharacters, we'd use the code last_name[0:3]. If we wanted everything except the first character, we'd saylast_name[1:]. By not declaring the last index, Python just gets everything from the first index we declare tothe end of the word. Using the index numbers, we can get any portion of a text string we want.

    Now we have the first letters and a random number. It would seem we are done with our program, but thereare two important details we need to consider. First, are the letters in our password going to be capitalized ornot? If we want both letters capitalized we need to use a special function in the string module to convert theletters to uppercase. So, before adding our two letters to the password, we need to import the string moduleand use the string.upper() function. The string.upper() function capitalizes all the letters in a string. If wewanted both letters in lowercase, we would use the function string.lower(), which puts all letters in lowercase.

    The second concern in creating our hybrid password is that Python cannot add an integer to a string, so it willcrash if we just say add this number to these letters. The random.randrange() function gave us a randominteger. If we want to add this integer to the letters of the last name, we need to convert the number into astring first. We've done something similar before when we converted a string to an integer using the int()function. Now, to convert the integer to a string we use the str() function. Once Python has a set of numeralsin string format it can add them to the letters we yanked out of the user's last name.

    And finally our program is ready. It's taken a lot of work, but for all this explanation, the code is really notthat long.

  • 8/3/2019 Start Python

    14/29

    Start Programming with Python --14Code:

    # Generate a three-digit random numberimport random

    number = random.randrange(100, 999)

    # Get first two letters of last namebase_name = raw_input("Enter last name: ")name_prefix = base_name[0:2]

    #Put letters in uppercaseimport stringname_prefix_upper = string.upper(name_prefix)

    # New passwordpassword = name_prefix_upper + str(number)print password

    Notice that we did not convert the number to a string until we were ready to add it to the password. We couldhave converted it to a string any time after we generated it, and technically speaking the variable number isstill an integer, but converting it on this line saves us from having to create a new variable while showing thatthis in-line conversion is possible.

    Points to Remember:The function random.randrange() returns a random integer in the given range.Each character in a string has an index address.A portion of a string can be obtained by slicing the string.

    To slice a string, place brackets [ ] after the variable name. Inside the brackets include the startindex and the stop index, separated by a colon. Example: variable_name[0:2]If a stop index is not provided in a slice description, the end of the string is assumed.Python will not add an integer to a string.Use str() to convert an integer to a string.

  • 8/3/2019 Start Python

    15/29

    Start Programming with Python --15Program 9: Reading from Text FileHaving a user type in his last name to create a password will work great as long as we have only one or twousers. When it comes time to create passwords for a few hundred students, however, we really don't want tosit in front of the computer all day typing in last names. It would be a lot easier if the program could just readthe names from a text file. So, let's start working in that direction. In this program we will read text from afile that has only one word in it. You'll want to make such a file before running the program.

    The main structure of the password generating program is going to stay the same. We still need to generate arandom number, get a last name, find the first two letters of the last name and then add the random number tothe end. The process that is going to change is how we get the name. In this program, we want to read from afile.

    Reading from a file in Python is a three step process. Step one is opening the file and assigning the openedfile to a variable name, or file handle. Step two is actually reading the information from the file located at thefile handle. When we read a file we can read it in as either a single text string or as a list where each line ofthe text file is a separate item in the list. Since our file has only one word, we'll read it in as a text string. The

    last step for reading a text file is closing the file. We close the file as soon as we are done reading it. The textthat has been read into the program will remain available throughout the program, but there is no need to keepthe file open once we have finished reading it.

    Our code, then, starts with opening the text file. Opening a file requires that we know the file name (includingit's extension) and know what mode we want to open it in. The mode is a declaration of what we want to dowith the file -- read from it(r), write to it(w), or add stuff to the end of the file(a). In this program wewant to read the text in the file, so we will open it in read mode, r. To open the file we use the built-infunction open(), and assign this function to a variable name (aka file handle) so we can manipulate the openfile later. The open() function expects two pieces of information, the filename and the mode, and it requiresthat the information is presented to it in that order.

    Once the file is open in read mode, we need to actually read the contents of the file using the read() function.The read() function takes the text from the file, imports it as a string, and stores it in a variable. Before it canread a file, the read() function has to know which file it is reading. To tell it the file name, we first type thevariable name we used for opening the file, then put a period, and finally the read() function call. So, if wenamed our file handle open_file, then we would read the open file using the code open_file.read(). Pythonwill then read the contents of the file and store the resulting string into our assigned variable.

    Finally, once the contents of the file have been read into the program and we are done working with the actualfile, we need to close the file. Amazingly enough, we use the close() function to close the file. The closefunction works just like the open() function, requiring the file handle followed by a period and then the close()function call.

    Since our text file has only one name in it, the part of our that takes the name and creates a random password

    will not change.

  • 8/3/2019 Start Python

    16/29

    Start Programming with Python --16Code:

    # Generate random number for password

    import randomnumber = random.randrange(100, 999)

    # Open file and read last namefilename = raw_input("Name of input file: ")file = open(filename, "r")file_text = file.read()file.close()

    #Get first two letters of last namename_prefix = file_text[0:2]

    #Put letters in uppercase

    import stringname_prefix_upper = string.upper(name_prefix)

    # New passwordpassword = name_prefix_upper + str(number)print password

    Points to Remember:There are three steps to reading a file:

    Open file using open()

    Read from file using read() or readlines()Close file using close()When a file is opened it must be assigned to a file handle (variable name).Files may be opened in one of three different modes:

    r Read onlyw Write onlya Append (add stuff to the end)

    The read() function reads text from a file into the program as a simple text string.To read from a from a file, the file handle must be identified Ex: file_handle.read().To close a file, the file handle must be identified Ex. file_handle.close().

  • 8/3/2019 Start Python

    17/29

    Start Programming with Python --17Program 10: Readlines and IterationsNow that we've gotten a program to read in one word from a file, let's get it to read lots of names from a file.For this program, we will assume that each name is on a separate line, as they would be if the contents of adatabase had been saved as a comma delimited text file. Before starting this program, create a text file with adifferent name on each line.

    We need to make two fundamental changes to our previous code to get it to handle multiple names onmultiple lines. First, instead of reading the text file into a single string, we will want to read it in as a list, witheach name being a separate item in the list. The second change is to put our password creation code into aloop, so that for every name in our list the program develops a new password.

    To read the text file in as a list we simply change the file.read() instruction to file.readlines(). The readlinesfunction is a built-in function designed to read a text file with multiple lines and save each line as a new itemin a list. So, if the file had the names Adam, Barnabas, Caleb, Daniel each on a separate line, readlines()would create a list like this: [Adam\n, Barnabas\n, Caleb\n, Daniel\n]. That goofy \n at the end ofeach name is the newline character, and for this program we can just ignore it.

    With our list of names imported, the next thing to do is set up a special loop to create a password based oneach name in the list. We could use a while loop, but that can get a little confusing when working with lists.A better solution is to use a for loop. A for loop automatically runs the loop code for each item in the list.It starts with the first item in the list, stores that name in the variable we designate, runs the code using thatname, then goes back and gets the next name in the list. To set up the for loop we use the code for name inname_list:. The variable name is actually a variable we make up at this point. The name variable willhold the current name we are working on in the list and let us access it in the loop sequence.

    So, with our for loop in place, the only thing left to do is move the password creation code into our for loop.Make sure each of these commands is indented correctly, and we're ready to go.

    Code:# Open file and read last namesfilename = raw_input("Name of input file: ")file = open(filename, "r")names_list = file.readlines()file.close()

    #Create a password for each name in listimport random, stringfor name in names_list:

    name_prefix = name[0:2]number = random.randrange(100, 999)

    name_prefix_upper = string.upper(name_prefix)password = name_prefix_upper + str(number)print password

    Note that the code has the import commands grouped together before the loop. Since we only have toimport the modules once, there is no need to have the import statement as part of the loop code.

  • 8/3/2019 Start Python

    18/29

    Start Programming with Python --18

    Points to Remember:readlines() imports a text file into a list, with each line from the file as a different item in the list.The readlines() function also reads in the line break character.

    A for loop runs a set of code for each item in a list.When creating a for loop, create a variable name for the value to be accessed inside the loopsequence.

  • 8/3/2019 Start Python

    19/29

    Start Programming with Python --19Program 11: Saving to a fileOur last program printed all these great passwords, but as soon as we exit Python, we've lost all of them. So,let's put some finishing touches on this program and get it to save our names and passwords together in a newcomma-delimited text file. A comma-delimited text file is a special format that allows our data to be portedinto a database, which will make our output even more useful.

    To create this program we start with the same code from program ten. The two programs will createpasswords in the same way, so that portion of the code will not change. The main change will be saving ourpasswords in a text file. Saving to a text file is similar to reading from a text file and involves three steps:opening the file in write or append mode, writing text to the file, and closing the file. If we open the file inappend mode we can write one line at a time to the file, adding each new line as we create the new passwords.If we used write mode, we would have to write all the passwords at once, since write mode overwrites existingtext by default. So, for our program we will want to open the file in append mode.

    Once we have the file opened we are ready to write to it. It would be nice if we could make the Pythonprogram create a comma-delimited text file so that we could import this information back into a database. So,

    we'll set up each line of our new text file with the user's name, a comma, and then their new password, andwe'll make sure each user is placed on a different line. Using that format, we'll be able to share with ourdatabase.

    So, the first item on each line in the text file will be the user's name. Before saving the user's name to our filewe need to edit it. When we read our name in from the text file it had a \n character at the end of everyname. If we leave this character in the name and try to put the password right after it, the password willactually end up on a different line (that's what the new line character does, after all). So we need to cut that\n off the name using the string slicing technique. The code name[:-1] will give us all of the name exceptthe last character, which in this case is our unwanted newline character.

    With that pesky newline cut off the user name, all we need to do is add the whole line together. To do thatwe will create a new variable named whole_line and fill it with the name, a comma, the password, and anewline character. Once the whole line is assembled, we write it to the file. If we include this write commandinside the loop that creates the new passwords, each password will be written to the line as it is created.

    At the very end, once all the user names and passwords have been written to the file, we close the file.

    And now, at last, we have created some semi-random passwords for all of our users and have a text file thatcontains both the user name and their password. Not bad for one day's work, especially since we were writingHello World when we started.

  • 8/3/2019 Start Python

    20/29

    Start Programming with Python --20Code:

    # Open file and read last namesfilename = raw_input("Name of input file: ")

    file = open(filename, "r")names_list = file.readlines()file.close()

    # Open a file for saving passwordsoutfile_name = raw_input("Name of output file: ")outfile = open(outfile_name, "a")

    #Create a password for each name in listimport random, stringfor name in names_list:

    number = random.randrange(100, 999)name_prefix = name[0:2]

    name_prefix_upper = string.upper(name_prefix)password = name_prefix_upper + str(number)whole_line = name[:-1] + ", " + password + "\n"outfile.write(whole_line)

    #Close output fileoutfile.close()print "Finished"

    Points to Remember:Open a text file in append mode if you will writing to the file more than once.A string index of [:-1] cuts off the last letter of a string.

    A comma-delimited text file has a comma separating the different data types.

  • 8/3/2019 Start Python

    21/29

    Start Programming with Python --21Example 1: Batch Editing File NamesAs an extra bonus for this training session, here is a script that will change the names of the files in adirectory, so you can find all the .htm files and rename them .html, or whatever name changes you need tomake.

    This program relies heavily on a module called os. The os module contains functions that allow Python towork with the operating system, performing such tasks as listing files in a directory, erasing files, andrenaming files. When using the os commands it is important to set the current working directory so you knowwhere Python is erasing or renaming files. The os.chdir() function sets the working directory.

    Another important tool in this script is the try ... except sequence. This is a special type of if ... elsestatement that is designed to catch errors. In our script we ask Python to open the directory designated by theuser. If that directory does not exist (the user misspelled the directory name, for instance), Python wouldnormally return an error code that will crash the program. By placing the os.chdir() function inside a trysequence, Python will try to enter the directory. If the directory does not exist, instead of just crashing theprogram, Python will jump to the statements in the except portion of the code and run those. The try ...

    except setup is a nice way to cleanly catch possible errors, instead of just letting a program die.

    Code:

    print Program to change file names

    #Get desired directorydirectory_entry = raw_input("What directory: ")

    #if directory exists, move focus to that directoryimport osdir_found = "false"while dir_found == "false":

    try:os.chdir(directory_entry)dir_found = "true"

    except:print "Invalid directory."directory_entry = raw_input("What directory: ")

    #What to replaceold_text = raw_input("Search for: ")new_text = raw_input("Replace with: ")

    #rename each file in directory accordinglyfile_list = os.listdir(directory_entry)

    import stringfor filename in file_list:

    if string.find(filename, old_text) >= 0:new_filename = string.replace(filename, old_text, new_text)os.rename(filename, new_filename)print "Renaming ", filename, " to ", new_filename

    else:pass

    print "Finished"

  • 8/3/2019 Start Python

    22/29

    Start Programming with Python --22Example 2: Batch-Edit Text Files in DirectoryThis is a program that finds all the occurrences of a text string in a set of text files and changes the text asindicated by the user. The program is case sensitive, and is limited to the files in a single directory (it does notdrill down into subdirectories). This is another bonus program to play with. Enjoy.

    Code:#program to change file namesprint Batch Edit Text in Text Files

    #Get desired directorydirectory_entry = raw_input("What directory: ")import osdir_found = "false"

    #if directory exists, move focus to that directorywhile dir_found == "false":

    try:os.chdir(directory_entry)dir_found = "true"

    except:print "Invalid directory."directory_entry = raw_input("What directory: ")

    #What to replaceold_text = raw_input("Search for: ")new_text = raw_input("Replace with: ")

    #rename each file in directory accordinglyfile_list = os.listdir(directory_entry)

    import string, os.pathfor filename in file_list:if os.path.isfile(filename):

    input_file = open(filename, "r")orig_file_text = input_file.read()input_file.close()

    else:continue

    if string.find(orig_file_text, old_text) >= 0:

    print "Editing ", filenamenew_file_text = string.replace(orig_file_text, old_text,new_text)output_file = open(filename, "w")

    output_file.write(new_file_text)output_file.close()else:

    pass

    print "Finished"

  • 8/3/2019 Start Python

    23/29

    Start Programming with Python --23Appendix A:

    Sample Code from Other LanguagesLest you think Python is too confusing, here is a look at the code required to get the computer to print hello

    world in a few other programming languages.

    X86 Assembly Hello World

    title Hello World Program (hello.asm); This program displays "Hello, World!" dosseg.model small.stack 100h .datahello_message db 'Hello, World!',0dh,0ah,'$' .codemain procmov ax,@datamov ds,ax mov ah,9mov dx,offset hello_messageint 21h mov ax,4C00hint 21hmain endpend main

    C++ Hello World

    #include main(){cout

  • 8/3/2019 Start Python

    24/29

    Start Programming with Python --24Appendix B:

    Resources for Learning MoreThis is a highly subjective survey of books and resources available for learning Python.

    Books:Learning Python by Mark Lutz, et al

    This text is a solid introduction to Python and a good reference to come back to. The book assumessome understanding of basic programming concepts, so it is not an introduction to programming asmuch as an introduction to Python. I have found this very useful and would probably make it one of my

    top recommendations.

    Learn to Program Using Python by Alan GauldThis book is not exactly a Python reference; it is really an introduction to programming in general,using Python as the teaching language. I found this book very helpful for getting started, and a gentleintroduction to many programming concepts, including some concepts found in other programminglanguages. It is a book you will likely grow out of, but it's nice to have a starter book like this.

    Python Programming on Win32 by Mark Hammond and Andy RobinsonIf you are thinking about writing scripts that will automate tasks you do in Microsoft programs, you'llwant this book. It is one of the only references available for learning how to access the COMinterfaces in Microsoft through Python, and it is written well.

    Python How to Program by Deitel and DeitelThis book provides by far the broadest coverage of Python, giving you a little information on a lot ofdifferent topics. The book includes chapters on creating graphical interfaces with Tkinter, workingwith databases, making CGI-BIN applications, using the Pygame module to make multimediaapplications, working with XML, and a smorgasboard of other topics. The breadth of the coverage in

    this book is impressive, though most of the topics are not covered in any depth. I found the writing inthis book to be less clear than other books, but it does offer a lot of information.

    Python and Tkinter Programming by John GraysonThis is one of the most complete references on how to create graphical user interfaces using thestandard Tkinter module in Python. Documentation on Tkinter is hard to find, and the appendix to thistext is the most comprehensive reference available. The text itself is not always helpful, often givingonly cursory explanations and then referring you to the appendix, but it does have some well developedexamples.

    Teach Yourself Python in 24 Hours by Ivan Van LaninghamThis is probably the weakest of all the books listed. The examples are not practical (unless you really

    like working with ancient calendars), and the content just does not measure up to the other books.

    Other Books I've Heard Good Things About

    Core Python Programming by Wesley ChunThe Quick Python Book by Daryl Harms and Kenneth McDonald

  • 8/3/2019 Start Python

    25/29

    Start Programming with Python --25Online:

    bembry.orgThis is my personal site. It contains my teaching notes from the high school Python course I taught.The notes start with what is a programming language and move into how to create graphical user

    interfaces using Tkinter. I also have a number of useful links on the site, as well as a PDF version ofthese notes. My email address is there too, so feel free to contact me if you have questions.

    URL: http://www.bembry.org

    Python Tutor mailing [email protected] is a mailing list dedicated to folks asking, and answering, questions about how toprogram in Python. The questions range from the most simple to some rather challenging quandaries.Folks on the list usually post their code, so you get a chance to see how other programmers approach acertain problem. The site below includes a link to the archives, where you can search through pastquestions and answers.

    URL: http://mail.python.org/mailman/listinfo/tutor

    Python.orgThis is the official homepage for the Python programming language. The site contains a number oflinks for learning more about the language, downloading the current version, looking up languagereferences, and more. Good resource in general.

    URL: http://www.python.org

    Useless PythonAnother rich resource, Useless Python contains a vast collection of sample codes (some of them trulyworthless, as the name suggests), along with links to some really good resources and materials. Lookaround this site for a while, it's a lot of fun. (My favorite is peggame.py, a program designedspecifically to give you a solution to those stupid triangular peg games they have at restaurants).

    URL: http://www.uselesspython.com

  • 8/3/2019 Start Python

    26/29

    Start Programming with Python --26Appendix C:

    Extending Python's CapabilitiesHere are some more modules and extensions available for doing even more with Python.

    py2exeThe py2exe code allows you to convert a Python program into a stand-alone executable, so it can be run onany Windows computer without having Python installed. This site includes the download and notes on howto use the program. The script can be a bit confusing to learn at first, but the code works well.

    URL: http://starship.python.net/crew/theller/py2exe/

    PygamePygame is a set of Python modules for designing games and multimedia applications. This site also includes anumber of neat games made entirely in Python.

    URL: http: //www.pygame.org/

    Python Imaging LibraryIf you are interested in manipulating images with Python, you'll want to get this set of modules. Thesemodules allow you to create programs that can edit images, including scaling, enhancing, and changing imageformats.

    URL: http://www.pythonware.com/products/pil/index.htm

    TkinterTkinter is a set of modules for designing graphical user interfaces for your Python programs. Tkinter is a

    standard part of Python, so there is nothing extra to download. There is not much documentation on Tkinteravailable, so figuring out how to use it can be a kind of treasure hunt. There are a few sites on the Internet thatare helpful, and I also have some notes available on bembry.org that might be useful.

    Win32 ExtensionsThe win32 extensions are modules that allow Python to access Microsoft COM interfaces. In other words, it'sa way to mess with Windows and Microsoft applications through Python, doing such things as automatingWindows NT/ 2000 administration tasks, extracting and manipulating information from an Excel worksheet,and more. If you use Windows and Python, this is a very useful set of modules to have in your tool chest.

    URL: http://starship.python.net/crew/mhammond/

  • 8/3/2019 Start Python

    27/29

    Start Programming with Python --27

    GNU Free Documentation LicenseVersion 1.1, March 2000

    Copyright (C) 2000 Free Software Foundation, Inc.

    59 Temple Place, Suite 330, Boston, MA 02111-1307 USAEveryone is permitted to copy and distribute verbatim copiesof this license document, but changing it is not allowed.

    0. PREAMBLE

    The purpose of this License is to make a manual, textbook, or other written document "free" in the sense of freedom: to assure everyone the effectivefreedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for theauthor and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.

    This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements theGNU General Public License, which is a copyleft license designed for free software.

    We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program shouldcome with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for anytextual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purposeis instruction or reference.

    1. APPLICABILITY AND DEFINITIONS

    This License applies to any manual or other work that contains a notice placed by the copyright holder saying it can be distributed under the terms ofthis License. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you".

    A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modificationsand/or translated into another language.

    A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers orauthors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overallsubject. (For example, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationshipcould be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political positionregarding them.

    The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that theDocument is released under this License.

    The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Documentis released under this License.

    A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public,whose contents can be viewed and edited directly and straightforwardly with generic text editors or (for images composed of pixels) generic paint

    programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a varietyof formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup has been designed to thwart ordiscourage subsequent modification by readers is not Transparent. A copy that is not "Transparent" is called "Opaque".

    Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XMLusing a publicly available DTD, and standard-conforming simple HTML designed for human modification. Opaque formats include PostScript, PDF,

    proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are notgenerally available, and the machine-generated HTML produced by some word processors for output purposes only.

    The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this Licenserequires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominentappearance of the work's title, preceding the beginning of the body of the text.

    2. VERBATIM COPYING

    You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices,and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever tothose of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute.However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditionsin section 3.

    You may also lend copies, under the same conditions stated above, and you may publicly display copies.

    3. COPYING IN QUANTITY

    If you publish printed copies of the Document numbering more than 100, and the Document's license notice requires Cover Texts, you mustenclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts onthe back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full titlewith all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the

  • 8/3/2019 Start Python

    28/29

    Start Programming with Python --28covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.

    If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover,and continue the rest onto adjacent pages.

    If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copyalong with each Opaque copy, or state in or with each Opaque copy a publicly-accessible computer-network location containing a complete Transparentcopy of the Document, free of added material, which the general network-using public has access to download anonymously at no charge using public-standard network protocols. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies inquantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute anOpaque copy (directly or through your agents or retailers) of that edition to the public.

    It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them achance to provide you with an updated version of the Document.

    4. MODIFICATIONS

    You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release theModified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modificationof the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:

    A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (whichshould, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original

    publisher of that version gives permission.

    B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version,together with at least five of the principal authors of the Document (all of its principal authors, if it has less than five).

    C. State on the Title page the name of the publisher of the Modified Version, as the publisher.

    D. Preserve all the copyright notices of the Document.

    E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices.

    F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the termsof this License, in the form shown in the Addendum below.

    G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice.

    H. Include an unaltered copy of this License.

    I. Preserve the section entitled "History", and its title, and add to it an item stating at least the title, year, new authors, and publisher of theModified Version as given on the Title Page. If there is no section entitled "History" in the Document, create one stating the title, year,authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previoussentence.

    J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise thenetwork locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omita network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it

    refers to gives permission.K. In any section entitled "Acknowledgements" or "Dedications", preserve the section's title, and preserve in the section all the substanceand tone of each of the contributor acknowledgements and/or dedications given therein.

    L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are notconsidered part of the section titles.

    M. Delete any section entitled "Endorsements". Such a section may not be included in the Modified Version.

    N. Do not retitle any existing section as "Endorsements" or to conflict in title with any Invariant Section.

    If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from theDocument, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in theModified Version's license notice. These titles must be distinct from any other section titles.

    You may add a section entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--forexample, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.

    You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of CoverTexts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made

    by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same

    entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher thatadded the old one.

    The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or implyendorsement of any Modified Version.

    5. COMBINING DOCUMENTS

    You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions,provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as InvariantSections of your combined work in its license notice.

    The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If thereare multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in

  • 8/3/2019 Start Python

    29/29

    Start Programming with Python --29parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the sectiontitles in the list of Invariant Sections in the license notice of the combined work.

    In the combination, you must combine any sections entitled "History" in the various original documents, forming one section entitled "History";likewise combine any sections entitled "Acknowledgements", and any sections entitled "Dedications". You must delete all sections entitled"Endorsements."

    6. COLLECTIONS OF DOCUMENTS

    You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of thisLicense in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatimcopying of each of the documents in all other respects.

    You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this Licenseinto the extracted document, and follow this License in all other respects regarding verbatim copying of that document.

    7. AGGREGATION WITH INDEPENDENT WORKS

    A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage ordistribution medium, does not as a whole count as a Modified Version of the Document, provided no compilation copyright is claimed for thecompilation. Such a compilation is called an "aggregate", and this License does not apply to the other self-contained works thus compiled with theDocument, on account of their being thus compiled, if they are not themselves derivative works of the Document.

    If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one quarter of the entireaggregate, the Document's Cover Texts may be placed on covers that surround only the Document within the aggregate. Otherwise they must appear on

    covers around the whole aggregate.

    8. TRANSLATION

    Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing InvariantSections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections inaddition to the original versions of these Invariant Sections. You may include a translation of this License provided that you also include the originalEnglish version of this License. In case of a disagreement between the translation and the original English version of this License, the original Englishversion will prevail.

    9. TERMINATION

    You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy,modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who havereceived copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

    10. FUTURE REVISIONS OF THIS LICENSE

    The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will

    be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.

    Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "orany later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has

    been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may chooseany version ever published (not as a draft) by the Free Software Foundation.