Non-Programmer's Tutorial for Python 3 The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3 Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License. All example Python source code in this tutorial is granted to the public domain. Therefore you may modify it and relicense it under any license you please. Since you are expected to learn programming, the Creative Commons Attribution-ShareAlike license would require you to keep all programs that are derived from the source code in this tutorial under that license. Since the Python source code is granted to the public domain, that requirement is waived. This tutorial is more or less a conversion of Non-Programmer's Tutorial for Python 2.6. Older versions and some versions in Korean, Spanish, Italian and Greek are available from http://jjc.freeshell.org/easytut/ The Non-Programmers' Tutorial For Python 3 is a tutorial designed to be an introduction to the Python programming language. This guide is for someone with no programming experience. If you have programmed in other languages I recommend using Python Tutorial for Programmers written by Guido van Rossum. If you have any questions or comments please use the discussion pages or see Authors page for author contact information. I welcome questions and comments about this tutorial. I will try to answer any questions you have as best I can. Thanks go to James A. Brown for writing most of the Windows install info. Thanks also to Elizabeth Cogliati for complaining enough :) about the original tutorial (that is almost unusable for a non-programmer), for proofreading, and for many ideas and comments on it. Thanks to Joe Oppegaard for writing almost all the exercises. Thanks to everyone I have missed. Python Home Page Python 3 Documentation A Byte of Python by Swaroop C H Porting to Python 3: An in-depth guide So, you've never programmed before. As we go through this tutorial, I will attempt to teach you how to program. There really is only one way to learn to program. You must read code and write code (as computer programs are often called). I'm going to show you lots of code. You should type in code that I show you to see what happens. Play around with it and make changes. The worst that can happen is that it won't work. When I type in code it will be formatted like this: # Python is easy to learn print("Hello, World!") That's so it is easy to distinguish from the other text. If you're reading this on the Web, you'll notice the code is in color -- that's just to make it stand out, and to make the different parts of the code stand out from each other. The code you enter will probably not be colored, or the colors may be different, but it won't affect the code as long as you enter it the same way as it's printed here. If the computer prints something out it will be formatted like this: Hello, World! (Note that printed text goes to your screen, and does not involve paper. Before computers had screens, the output of computer programs would be printed on paper.) Note that this is a Python 3 tutorial, which means that most of the examples will not work in Python 2.7 and before. As well, all but a small number of the extra Python 2.7 libraries (third-party libraries) have been converted to Python 3. Most likely you will want to learn Python 3, but if you are learning Python for a specific package or set of modules that are only written in Python 2.7, you may want to consider learning from the Non-Programmer's Tutorial for Python 2.6. However, the differences between Python 2 and 3 are not particularly large, so if you learn one, you should be able to read programs written for the other without much difficulty. There will often be a mixture of the text you type (which is shown in bold) and the text the program prints to the screen, which would look like this: Halt! Who Goes there? Josh You may pass, Josh (Some of the tutorial has not been converted to this format. Since this is a wiki, you can convert it when you find it.) I will also introduce you to the terminology of programming - for example, that programming is often referred to as coding or hacking. This will not only help you understand what programmers are talking about, but also help the learning process. Now, on to more important things. In order to program in Python you need the Python 3 software. If you don't already have the Python software go to www.python.org/download and get the proper version for your platform. Download it, read the instructions and get it installed. For Python programming you need a working Python installation and a text editor. Python comes with its own editor, IDLE, which is quite nice and totally sufficient for the beginning. As you get more into programming, you will probably switch to some other editor like nano, emacs, vi or another. The Python download page is http://www.python.org/download. The most recent version is Python 3.9.6 (as of July 2021); Python 2.7 and older versions will not work with this tutorial. There are various different installation files for different computer platforms available on the download site. Here are some specific instructions for the most common operating systems: You are probably lucky and Python is already installed on your machine. To test it type python3 on a command line. If you see something like what is shown in the following section, you are set. IDLE may need to be installed separately, from its own package such as idle3 or as part of python-tools. If you have to install Python, first try to use the operating system's package manager or go to the repository where your packages are available and get Python 3. Python 3.0 was released in December 2008; all distributions should have Python 3 available, so you may not need to compile it from scratch. Ubuntu and Fedora do have Python 3 binary packages available, but they are not yet the default, so they need to be installed specially. Roughly, here are the steps to compile Python from source code in Unix (If these totally don't make sense, you may want to read another introduction to *nix, such as Introduction to Linux): Download the .tgz file (use your Web browser to get the gzipped tar file from https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgz) Uncompress the tar file (put in the correct path to where you downloaded it): $ tar -xvzf ~/Download/Python-3.7.4.tgz ... list of files as they are uncompressed Change to the directory and tell the computer to compile and install the program $ cd Python-3.7/ $ ./configure --prefix=$HOME/python3_install ... lots of output. Watch for error messages here ... $ make ... even more output. Hopefully no error messages ... $ make install Add Python 3 to your path. You can test it first by specifying the full path. You should add $HOME/python3_install/bin to your PATH bash variable. $ ~/python3_install/bin/python3 Python 3.7.4 (... size and date information ...) [GCC 9.1.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> The above commands will install Python 3 to your home directory, which is probably what you want, but if you skip the --prefix=$HOME/python3_install, it will install it to /usr/local. If you want to use the IDLE graphical code editor, you need to make sure that the tk and tcl libraries, together with their development files, are installed on the system. You will get a warning during the make phase if these are not available. Starting from Mac OS X Tiger (10.4), versions of Python 2 shipped with the operating system by default, but you will need to also install Python 3 unless Mac OS starts including Python 3 (check the version by starting python3 in a command line terminal). Also IDLE (the Python editor) might be missing in the standard installation. If you want to (re-)install Python, get the Mac OS installer from the Python download site. Download the appropriate Windows installer (the x86 MSI installer, if you do not have a 64-bit AMD or Intel chip). Start the installer by double-clicking it and follow the prompts. See https://docs.python.org/3/using/windows.html#installing-python for more information. The PATH environment variable is a list of folders, separated by semicolons, in which Windows will look for a program whenever you try to execute one by typing its name at a Command Prompt. You can see the current value of your PATH by typing this command at a Command Prompt: echo %PATH% The easiest way to permanently change environment variables is to bring up the built-in environment variable editor in Windows. How you get to this editor is slightly different on different versions of Windows. On Windows 8 or Windows 10: Press the Windows key and type Control Panel to locate the Windows Control Panel. Once you've opened the Control Panel, select View by: Large Icons, then click on System. In the window that pops up, click the Advanced System Settings link, then click the Environment Variables... button. On Windows 7 or Vista: Click the Start button in the lower-left corner of the screen, move your mouse over Computer, right-click, and select Properties from the pop-up menu. Click the Advanced System Settings link, then click the Environment Variables... button. Once you've brought up the environment variable editor, you'll do the same thing regardless of which version of Windows you're running. Under System Variables in the bottom half of the editor, find a variable called PATH. If there is is one, select it and click Edit.... Assuming your Python root is C:\Python37, add these two folders to your path (and make sure you get the semicolons right; there should be a semicolon between each folder in the list): C:\Python37 C:\Python37\Scripts Note: If you want to double-click and start your Python programs from a Windows folder and not have the console window disappear, you can add the following code to the bottom of each script: #stops console from exiting end_prog = "" while end_prog != "q": end_prog = input("type q to quit") Go into IDLE (also called the Python GUI). You should see a window that has some text like this: Python 3.0 (r30:67503, Dec 29 2008, 21:31:07) [GCC 4.3.2 20081105 (Red Hat 4.3.2-7)] on linux2 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 3.0 >>> The >>> is Python's way of telling you that you are in interactive mode. In interactive mode what you type is immediately run. Try typing 1+1 in. Python will respond with 2. Interactive mode allows you to test out and see what Python will do. If you ever feel you need to play with new Python statements, go into interactive mode and try them out. Go into IDLE if you are not already. In the menu at the top, select File then New File. In the new window that appears, type the following: print("Hello, World!") Now save the program: select File from the menu, then Save. Save it as "hello.py" (you can save it in any folder you want). Now that it is saved it can be run. Next run the program by going to Run then Run Module (or if you have an older version of IDLE use Edit then Run script). This will output Hello, World! on the *Python Shell* window. For a more in-depth introduction to IDLE, a longer tutorial with screenshots can be found at http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html. It is very useful to stick to some rules regarding the file names of Python programs. Otherwise some things might go wrong unexpectedly. These don't matter as much for programs, but you can have weird problems if you don't follow them for module names (modules will be discussed later). Always save the program with the extension .py. Do not put another dot anywhere else in the file name. Only use standard characters for file names: letters, numbers, dash (-) and underscore (_). White space (" ") should not be used at all (use underscores instead). Do not use anything other than a letter (particularly no numbers!) at the beginning of a file name. Do not use "non-English" characters (such as å, ɓ, ç, ð, é, õ, ü) in your file names—or, even better, do not use them at all when programming. Do not use module names for file names (such as print.py, math.py, list.py) If you don't want to use Python from the command line, you don't have to, just use IDLE. To get into interactive mode just type python3 without any arguments. To run a program, create it with a text editor (Emacs has a good Python mode) and then run it with python3 program_name. If you are using Unix (such as Linux, Mac OS, or BSD), if you make the program executable with chmod, and have as the first line: #!/usr/bin/env python3 you can run the python program with ./hello.py like any other command. At some point in your Python career you will probably get stuck and have no clue about how to solve the problem you are supposed to work on. This tutorial only covers the basics of Python programming, but there is a lot of further information available. First of all, Python is very well documented. There might even be copies of these documents on your computer that came with your Python installation: The official Python 3 Tutorial by Guido van Rossum is often a good starting point for general questions. For questions about standard modules (you will learn what these are later), the Python 3 Library Reference is the place to look. If you really want to get to know something about the details of the language, the Python 3 Reference Manual is comprehensive but quite complex for beginners. There are a lot of other Python users out there, and usually they are nice and willing to help you. This very active user community is organised mostly through mailing lists and a newsgroup: The tutor mailing list is for folks who want to ask questions regarding how to learn computer programming with the Python language. The python-help mailing list is python.org's help desk. You can ask a group of knowledgeable volunteers questions about all your Python problems. The Python newsgroup comp.lang.python (Google groups archive) is the place for general Python discussions, questions and the central meeting point of the community. Python wiki has a list of local user groups, you can join the group mailing list and ask questions. You can also participate in the user group meetings. LearnPython subreddit is another location where beginner level questions can be asked. In order not to reinvent the wheel and discuss the same questions again and again, people will appreciate very much if you do a web search for a solution to your problem before contacting these lists! If you don't want to download python, or you are using a computer that you cannot download programs on, such as a chromebook, you can use one of the many available online python editors. Once you've read and mastered this chapter, you should know how to edit programs in a text editor or IDLE, save them to the hard disk, and run them once they have been saved. Programming tutorials since the beginning of time have started with a little program called "Hello, World!" So here it is: print("Hello, World!") If you are using the command line to run programs then type it in with a text editor, save it as hello.py and run it with python3 hello.py Otherwise go into IDLE, create a new window, and create the program as in section Creating and Running Programs. When this program is run here's what it prints: Hello, World! Now I'm not going to tell you this every time, but when I show you a program I recommend that you type it in and run it. I learn better when I type it in and you probably do too. Now here is a more complicated program: print("Jack and Jill went up a hill") print("to fetch a pail of water;") print("Jack fell down, and broke his crown,") print("and Jill came tumbling after.") When you run this program it prints out: Jack and Jill went up a hill to fetch a pail of water; Jack fell down, and broke his crown, and Jill came tumbling after. When the computer runs this program it first sees the line: print("Jack and Jill went up a hill") so the computer prints: Jack and Jill went up a hill Then the computer goes down to the next line and sees: print("to fetch a pail of water;") So the computer prints to the screen: to fetch a pail of water; The computer keeps looking at each line, follows the command and then goes on to the next line. The computer keeps running commands until it reaches the end of the program. Now is probably a good time to give you a bit of an explanation of what is happening - and a little bit of programming terminology. What we were doing above was using a function called print. The function's name - print - is followed by parentheses containing zero or more arguments. So in this example print("Hello, World!") there is one argument, which is "Hello, World!". Note that this argument is a group of characters enclosed in double quotes (""). This is commonly referred to as a string of characters, or string, for short. Another example of a string is "Jack and Jill went up a hill". The combination of a function and parentheses with the arguments is a function call. A function and its arguments are one type of statement that python has, so print("Hello, World!") is an example of a statement. Basically, you can think of a statement as a single line in a program. That's probably more than enough terminology for now. \n, or newline in printing makes the strings after the \n in a new line, it is also an escape character, here is an example: print("Hello, World!\nWhat should I do?") Here is the output: Hello, World! What should I do? It can be used to put a bunch of strings that are supposed to be on different lines into 1 print statement instead of making multiple print statements The print statement also sort of uses \n even if you do not use it for example: print("Hello, World!") is actually print("Hello, World!\n") Well, there is a difference if you do it manually, but python actually adds a newline "behind the scenes" at the end of the string Here is another program: print("2 + 2 is", 2 + 2) print("3 * 4 is", 3 * 4) print("100 - 1 is", 100 - 1) print("(33 + 2) / 5 + 11.5 is", (33 + 2) / 5 + 11.5) And here is the output when the program is run: 2 + 2 is 4 3 * 4 is 12 100 - 1 is 99 (33 + 2) / 5 + 11.5 is 18.5 As you can see, Python can turn your thousand-dollar computer into a five-dollar calculator. In this example, the print function is followed by two arguments, with each of the arguments separated by a comma. So with the first line of the program print("2 + 2 is", 2 + 2) The first argument is the string "2 + 2 is" and the second argument is the arithmetic expression 2 + 2, which is one kind of expression. What is important to note is that a string is printed as is (without the enclosing double quotes), but an expression is evaluated, or converted to its actual value. Python has seven basic operations for numbers: Notice that there are two ways to do division, one that returns the repeating decimal, and the other that can get the remainder and the whole number. The order of operations is the same as in math: parentheses () exponents ** multiplication *, division /, integer division //, and remainder % addition + and subtraction - So use parentheses to structure your formulas when needed. Often in programming, you are doing something complicated and may not in the future remember what you did. When this happens the program should probably be commented. A comment is a note to you and other programmers explaining what is happening. For example: # Not quite PI, but a credible simulation print(22 / 7) Which outputs 3.14285714286 Notice that the comment starts with a hash: #. Comments are used to communicate with others who read the program and your future self to make clear what is complicated. Note that any text can follow comment and that when the program is run, the text after the # through to the end of that line is ignored. The # does not have to be at the beginning of a new line: # Output PI on the screen print(22 / 7) # Well, just a good approximation Each chapter (eventually) will contain examples of the programming features introduced in the chapter. You should at least look over them and see if you understand them. If you don't, you may want to type them in and see what happens. Mess around with them, change them and see what happens. Denmark.py print("Something's rotten in the state of Denmark.") print(" -- Shakespeare") Output: Something's rotten in the state of Denmark. -- Shakespeare School.py # This is not quite true outside of USA # and is based on my dim memories of my younger years print("Firstish Grade") print("1 + 1 =", 1 + 1) print("2 + 4 =", 2 + 4) print("5 - 2 =", 5 - 2) print() print("Thirdish Grade") print("243 - 23 =", 243 - 23) print("12 * 4 =", 12 * 4) print("12 / 3 =", 12 / 3) print("13 / 3 =", 13 // 3, "R", 13 % 3) print() print("Junior High") print("123.56 - 62.12 =", 123.56 - 62.12) print("(4 + 3) * 2 =", (4 + 3) * 2) print("4 + 3 * 2 =", 4 + 3 * 2) print("3 ** 2 =", 3 ** 2) Output: Firstish Grade 1 + 1 = 2 2 + 4 = 6 5 - 2 = 3 Thirdish Grade 243 - 23 = 220 12 * 4 = 48 12 / 3 = 4 13 / 3 = 4 R 1 Junior High 123.56 - 62.12 = 61.44 (4 + 3) * 2 = 14 4 + 3 * 2 = 10 3 ** 2 = 9 Write a program that prints your full name and your birthday as separate strings. Write a program that shows the use of all 7 arithmetic operations. Solution 1. Write a program that prints your full name and your birthday as separate strings. print("Ada Lovelace", "born on", "November 27, 1852") print("Albert Einstein", "born on", "14 March 1879") print(("John Smith"), ("born on"), ("14 March 1879")) Solution 2. Write a program that shows the use of all 7 arithmetic operations. print("5**5 = ", 5**5) print("6*7 = ", 6*7) print("56/8 = ", 56/8) print("14//6 = ", 14//6) print("14%6 = ", 14%6) print("5+6 = ", 5+6) print("9-0 = ", 9-0) Here is a great list of the famous "Hello, world!" program in many programming languages. Just so you know how simple Python can be... Now I feel it is time for a really complicated program. Here it is: print("Halt!") user_input = input("Who goes there? ") print("You may pass,", user_input) When I ran it, here is what my screen showed: Halt! Josh You may pass, Josh Note: After running the code by pressing F5, the python shell will only give output: Halt! You need to enter your name in the python shell, and then press enter for the rest of the output. Of course when you run the program your screen will look different because of the input() statement. When you ran the program you probably noticed (you did run the program, right?) how you had to type in your name and then press Enter. Then the program printed out some more text and also your name. This is an example of input. The program reaches a certain point and then waits for the user to input some data that the program can use later. Of course, getting information from the user would be useless if we didn't have anywhere to put that information and this is where variables come in. In the previous program user_input is a variable. Variables are like a box that can store some piece of data. Here is a program to show examples of variables: a = 123.4 b23 = 'Spam' first_name = "Bill" b = 432 c = a + b print("a + b is",c) print("first_name is",first_name) print("Sorted Parts, After Midnight or",b23) And here is the output: a + b is 555.4 first_name is Bill Sorted Parts, After Midnight or Spam Variables store data. The variables in the above program are a, b23, first_name, b, and c. The two basic types are strings and numbers. Strings are a sequence of letters, numbers and other characters. In this example b23 and first_name are variables that are storing strings. Spam, Bill, a + b is, first_name is, and Sorted Parts, After Midnight or are the strings in this program. The characters are surrounded by " or '. The other type of variables are numbers. Remember that variables are used to store a value, they do not use quotation marks (" and '). If you want to use an actual value, you must use quotation marks. value1 == Pim value2 == "Pim" Both look the same, but in the first one Python checks if the value stored in the variable value1 is the same as the value stored in the variable Pim. In the second one, Python checks if the string (the actual letters P,i, and m) are the same as in value2 (continue this tutorial for more explanation about strings and about the ==). Okay, so we have these boxes called variables and also data that can go into the variable. The computer will see a line like first_name = "Bill" and it reads it as "Put the string Bill into the box (or variable) first_name". Later on it sees the statement c = a + b and it reads it as "put the sum of a + b or 123.4 + 432 which equals 555.4 into c". The right hand side of the statement (a + b) is evaluated and the result is stored in the variable on the left hand side (c). This is called assignment, and you should not confuse the assignment equal sign (=) with "equality" in a mathematical sense here (that's what == will be used for later). Here is another example of variable usage: a = 1 print(a) a = a + 1 print(a) a = a * 2 print(a) And of course here is the output: 1 2 4 Even if the same variable appears on both sides of the equals sign (e.g., spam = spam), the computer still reads it as, "First find out the data to store and then find out where the data goes." One more program before I end this chapter: number = float(input("Type in a number: ")) integer = int(input("Type in an integer: ")) text = input("Type in a string: ") print("number =", number) print("number is a", type(number)) print("number * 2 =", number * 2) print("integer =", integer) print("integer is a", type(integer)) print("integer * 2 =", integer * 2) print("text =", text) print("text is a", type(text)) print("text * 2 =", text * 2) The output I got was: Type in a number: 12.34 Type in an integer: -3 Type in a string: Hello number = 12.34 number is a number * 2 = 24.68 integer = -3 integer is a integer * 2 = -6 text = Hello text is a text * 2 = HelloHello Notice that number was created with float(input()) ,int(input()) returns an integer, a number with no decimal point, while text created with input() returns a string(can be writen as str(input()), too). When you want the user to type in a decimal use float(input()), if you want the user to type in an integer use int(input()), but if you want the user to type in a string use input(). The second half of the program uses the type() function which tells what kind a variable is. Numbers are of type int or float, which are short for integer and floating point (mostly used for decimal numbers), respectively. Text strings are of type str, short for string. Integers and floats can be worked on by mathematical functions, strings cannot. Notice how when python multiplies a number by an integer the expected thing happens. However when a string is multiplied by an integer the result is that multiple copies of the string are produced (i.e., text * 2 = HelloHello). Operations with strings do different things than operations with numbers. As well, some operations only work with numbers (both integers and floating point numbers) and will give an error if a string is used. Here are some interactive mode examples to show that some more. >>> print("This" + " " + "is" + " joined.") This is joined. >>> print("Ha, " * 5) Ha, Ha, Ha, Ha, Ha, >>> print("Ha, " * 5 + "ha!") Ha, Ha, Ha, Ha, Ha, ha! >>> print(3 - 1) 2 >>> print("3" - "1") Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for -: 'str' and 'str' >>> Here is the list of some string operations: Rate_times.py # This program calculates rate and distance problems print("Input a rate and a distance") rate = float(input("Rate: ")) distance = float(input("Distance: ")) time=(distance/ rate) print("Time:", time) Sample runs: Input a rate and a distance Rate: 5 Distance: 10 Time: 2.0 Input a rate and a distance Rate: 3.52 Distance: 45.6 Time: 12.9545454545 Area.py # This program calculates the perimeter and area of a rectangle print("Calculate information about a rectangle") length = float(input("Length: ")) width = float(input("Width: ")) Perimeter=(2 * length + 2 * width) print("Area:", length * width) print("Perimeter:",Perimeter) Sample runs: Calculate information about a rectangle Length: 4 Width: 3 Area: 12.0 Perimeter: 14.0 Calculate information about a rectangle Length: 2.53 Width: 5.2 Area: 13.156 Perimeter: 15.46 Temperature.py # This program converts Fahrenheit to Celsius fahr_temp = float(input("Fahrenheit temperature: ")) celc_temp = (fahr_temp - 32.0) *( 5.0 / 9.0) print("Celsius temperature:", celc_temp) Sample runs: Fahrenheit temperature: 32 Celsius temperature: 0.0 Fahrenheit temperature: -40 Celsius temperature: -40.0 Fahrenheit temperature: 212 Celsius temperature: 100.0 Fahrenheit temperature: 98.6 Celsius temperature: 37.0 Write a program that gets 2 string variables and 2 number variables from the user, concatenates (joins them together with no spaces) and displays the strings, then multiplies the two numbers on a new line. Solution Write a program that gets 2 string variables and 2 number variables from the user, concatenates (joins them together with no spaces) and displays the strings, then multiplies the two numbers on a new line. string1 = input('String 1: ') string2 = input('String 2: ') float1 = float(input('Number 1: ')) float2 = float(input('Number 2: ')) print(string1 + string2) print(float1 * float2) Presenting our first control structure. Ordinarily the computer starts with the first line and then goes down from there. Control structures change the order that statements are executed or decide if a certain statement will be run. Here's the source for a program that uses the while control structure: a = 0 # FIRST, set the initial value of the variable a to 0(zero). while a < 10: # While the value of the variable a is less than 10 do the following: a = a + 1 # Increase the value of the variable a by 1, as in: a = a + 1! print(a) # Print to screen what the present value of the variable a is. # REPEAT! until the value of the variable a is equal to 9!? See note. # NOTE: # The value of the variable a will increase by 1 # with each repeat, or loop of the 'while statement BLOCK'. # e.g. a = 1 then a = 2 then a = 3 etc. until a = 9 then... # the code will finish adding 1 to a (now a = 10), printing the # result, and then exiting the 'while statement BLOCK'. # -- # While a < 10: | # a = a + 1 |<--[ The while statement BLOCK ] # print (a) | # -- And here is the extremely exciting output: 1 2 3 4 5 6 7 8 9 10 (And you thought it couldn't get any worse after turning your computer into a five-dollar calculator?) First it sees the line a = 0 and sets a to zero. Then it sees while a < 10: and so the computer checks to see if a < 10. The first time the computer sees this statement, a is zero, so it is less than 10. In other words, as long as a is less than ten, the computer will run the tabbed in statements. This eventually makes a equal to ten (by adding one to a again and again) and the while a < 10 is not true any longer. Reaching that point, the program will stop running the indented lines. Always remember to put a colon ":" at the end of the while statement line! Here is another example of the use of while: a = 1 s = 0 print('Enter Numbers to add to the sum.') print('Enter 0 to quit.') while a != 0: print('Current Sum:', s) a = float(input('Number? ')) s = s + a print('Total Sum =', s) Enter Numbers to add to the sum. Enter 0 to quit. Current Sum: 0 Number? 200 Current Sum: 200.0 Number? -15.25 Current Sum: 184.75 Number? -151.85 Current Sum: 32.9 Number? 10.00 Current Sum: 42.9 Number? 0 Total Sum = 42.9 Notice how print('Total Sum =', s) is only run at the end. The while statement only affects the lines that are indented with whitespace. The != means does not equal so while a != 0: means as long as a is not zero run the tabbed statements that follow. Note that a is a floating point number, and not all floating point numbers can be accurately represented, so using != on them can sometimes not work. Try typing in 1.1 in interactive mode. Now that we have while loops, it is possible to have programs that run forever. An easy way to do this is to write a program like this: while 1 == 1: print("Help, I'm stuck in a loop.") The "==" operator is used to test equality of the expressions on the two sides of the operator, just as "<" was used for "less than" before (you will get a complete list of all comparison operators in the next chapter). This program will output Help, I'm stuck in a loop. until the heat death of the universe or you stop it, because 1 will forever be equal to 1. The way to stop it is to hit the Control (or Ctrl) button and C (the letter) at the same time. This will kill the program. (Note: sometimes you will have to hit enter after the Control-C.) On some systems, nothing will stop it, short of killing the process--so avoid! Fibonacci-method1.py # This program calculates the Fibonacci sequence a = 0 b = 1 count = 0 max_count = 20 while count < max_count: count = count + 1 print(a, end=" ") # Notice the magic end=" " in the print function arguments # that keeps it from creating a new line. old_a = a # we need to keep track of a since we change it. a = b b = old_a + b print() # gets a new (empty) line. Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 Note that the output is on a single line because of the extra argument end=" " in the print arguments. Fibonacci-method2.py # Simplified and faster method to calculate the Fibonacci sequence a = 0 b = 1 count = 0 max_count = 10 while count < max_count: count = count + 1 print(a, b, end=" ") # Notice the magic end=" " a = a + b b = a + b print() # gets a new (empty) line. Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 Fibonacci-method3.py a = 0 b = 1 count = 0 maxcount = 20 #once loop is started we stay in it while count < maxcount: count += 1 olda = a a = a + b b = olda print(olda,end=" ") print() Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 Password.py # Waits until a password has been entered. Use Control-C to break out without # the password #Note that this must not be the password so that the # while loop runs at least once. password = str() # note that != means not equal while password != "unicorn": password = input("Password: ") print("Welcome in") Sample run: Password: auo Password: y22 Password: password Password: open sesame Password: unicorn Welcome in Write a program that asks the user for a Login Name and password. Solution Write a program that asks the user for a Login Name and password. name = input("What is your UserName: ") password = input("What is your Password: ") print("To lock your computer type lock.") command = None input1 = None input2 = None while command != "lock": command = input("What is your command: ") while input1 != name: input1 = input("What is your username: ") while input2 != password: input2 = input("What is your password: ") print("Welcome back to your system!") If you would like the program to run continuously, just add a while 1 == 1: loop around the whole thing. You will have to indent the rest of the program when you add this at the top of the code, but don't worry, you don't have to do it manually for each line! Just highlight everything you want to indent and click on "Indent" under "Format" in the top bar of the python window. Another way of doing this could be: name = input('Set name: ') password = input('Set password: ') while 1 == 1: nameguess="" passwordguess="" key="" while (nameguess != name) or (passwordguess != password): nameguess = input('Name? ') passwordguess = input('Password? ') print("Welcome,", name, ". Type lock to lock.") while key != "lock": key = input("") Notice the or in while (nameguess != name) or (passwordguess != password), which we haven't yet introduced. You can probably figure out how it works. As always, I believe I should start each chapter with a warm-up typing exercise, so here is a short program to compute the absolute value of an integer: n = int(input("Number? ")) if n < 0: print("The absolute value of", n, "is", -n) else: print("The absolute value of", n, "is", n) Here is the output from the two times that I ran this program: Number? -34 The absolute value of -34 is 34 Number? 1 The absolute value of 1 is 1 So what does the computer do when it sees this piece of code? First it prompts the user for a number with the statement "n = int(input("Number? "))". Next it reads the line "if n < 0:". If n is less than zero Python runs the line "print("The absolute value of", n, "is", -n)". Otherwise it runs the line "print("The absolute value of", n, "is", n)". More formally Python looks at whether the expression n < 0 is true or false. An if statement is followed by an indented block of statements that are run when the expression is true. Optionally after the if statement is an else statement and another indented block of statements. This second block of statements is run if the expression is false. There are a number of different tests that an expression can have. Here is a table of all of them: Another feature of the if command is the elif statement. It stands for else if and means if the original if statement is false but the elif part is true, then do the elif part. And if neither the if or elif expressions are true, then do what's in the else block. Here's an example: a = 0 while a < 10: a = a + 1 if a > 5: print(a, ">", 5) elif a <= 3: print(a, "<=", 3) else: print("Neither test was true") and the output: 1 <= 3 2 <= 3 3 <= 3 Neither test was true Neither test was true 6 > 5 7 > 5 8 > 5 9 > 5 10 > 5 Notice how the elif a <= 3 is only tested when the if statement fails to be true. There can be more than one elif expression, allowing multiple tests to be done in a single if statement. # This Program Demonstrates the use of the == operator # using numbers print(5 == 6) # Using variables x = 5 y = 8 print(x == y) And the output False False high_low.py # Plays the guessing game higher or lower # This should actually be something that is semi random like the # last digits of the time or something else, but that will have to # wait till a later chapter. (Extra Credit, modify it to be random # after the Modules chapter) number = 7 guess = -1 print("Guess the number!") while guess != number: guess = int(input("Is it... ")) if guess == number: print("Hooray! You guessed it right!") elif guess < number: print("It's bigger...") elif guess > number: print("It's not so big.") Sample run: Guess the number! Is it... 2 It's bigger... Is it... 5 It's bigger... Is it... 10 It's not so big. Is it... 7 Hooray! You guessed it right! even.py # Asks for a number. # Prints if it is even or odd number = float(input("Tell me a number: ")) if number % 2 == 0: print(int(number), "is even.") elif number % 2 == 1: print(int(number), "is odd.") else: print(number, "is very strange.") Sample runs: Tell me a number: 3 3 is odd. Tell me a number: 2 2 is even. Tell me a number: 3.4895 3.4895 is very strange. average1.py # keeps asking for numbers until 0 is entered. count = 0 sum = 0.0 number = 1 # set to something that will not exit the while loop immediately. print("Enter 0 to exit the loop") while number != 0: number = float(input("Enter a number: ")) if number != 0: count = count + 1 sum = sum + number if number == 0: print("The average was:", sum / count) Sample runs Sample runs: Enter 0 to exit the loop Enter a number: 3 Enter a number: 5 Enter a number: 0 The average was: 4.0 Enter 0 to exit the loop Enter a number: 1 Enter a number: 4 Enter a number: 3 Enter a number: 0 The average was: 2.66666666667 average2.py # keeps asking for numbers until count numbers have been entered. #Notice that we use an integer to keep track of how many numbers, # but floating point numbers for the input of each number sum = 0.0 print("This program will take several numbers then average them") count = int(input("How many numbers would you like to average: ")) current_count = 0 while current_count < count: current_count = current_count + 1 print("Number", current_count) number = float(input("Enter a number: ")) sum = sum + number print("The average was:", sum / count) Sample runs: This program will take several numbers then average them How many numbers would you like to average: 2 Number 1 Enter a number: 3 Number 2 Enter a number: 5 The average was: 4.0 This program will take several numbers then average them How many numbers would you like to average: 3 Number 1 Enter a number: 1 Number 2 Enter a number: 4 Number 3 Enter a number: 3 The average was: 2.66666666667 Write a program that asks the user their name, if they enter your name say "That is a nice name", if they enter "John Cleese" or "Michael Palin", tell them how you feel about them ;), otherwise tell them "You have a nice name." Solution name = input('Your name: ') if name == 'Bryn': print('That is a nice name.') elif name == 'John Cleese': print('... some funny text.') elif name == 'Michael Palin': print('... some funny text.') else: print('You have a nice name.') Modify the higher or lower program from this section to keep track of how many times the user has entered the wrong number. If it is more than 3 times, print "That must have been complicated." at the end, otherwise print "Good job!" Solution number = 7 guess = -1 count = 0 print("Guess the number!") while guess != number: guess = int(input("Is it... ")) count = count + 1 if guess == number: print("Hooray! You guessed it right!") elif guess < number: print("It's bigger...") elif guess > number: print("It's not so big.") if count > 3: print("That must have been complicated.") else: print("Good job!") Write a program that asks for two numbers. If the sum of the numbers is greater than 100, print "That is a big number." Solution number1 = float(input('1st number: ')) number2 = float(input('2nd number: ')) if number1 + number2 > 100: print('That is a big number.') "As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs." — Maurice Wilkes discovers debugging, 1949 By now if you have been messing around with the programs you have probably found that sometimes the program does something you didn't want it to do. This is fairly common. Debugging is the process of figuring out what the computer is doing and then getting it to do what you want it to do. This can be tricky. I once spent nearly a week tracking down and fixing a bug that was caused by someone putting an x where a y should have been. This chapter will be more abstract than previous chapters. The first thing to do (this sounds obvious) is to figure out what the program should be doing if it is running correctly. Come up with some test cases and see what happens. For example, let's say I have a program to compute the perimeter of a rectangle (the sum of the length of all the edges). I have the following test cases: I now run my program on all of the test cases and see if the program does what I expect it to do. If it doesn't then I need to find out what the computer is doing. More commonly some of the test cases will work and some will not. If that is the case you should try and figure out what the working ones have in common. For example here is the output for a perimeter program (you get to see the code in a minute): Height: 3 Width: 4 perimeter = 15 Height: 2 Width: 3 perimeter = 11 Height: 4 Width: 4 perimeter = 16 Height: 2 Width: 2 perimeter = 8 Height: 5 Width: 1 perimeter = 8 Notice that it didn't work for the first two inputs, it worked for the next two and it didn't work on the last one. Try and figure out what is in common with the working ones. Once you have some idea what the problem is finding the cause is easier. With your own programs you should try more test cases if you need them. The next thing to do is to look at the source code. One of the most important things to do while programming is reading source code. The primary way to do this is code walkthroughs. A code walkthrough starts at the first line, and works its way down until the program is done. while loops and if statements mean that some lines may never be run and some lines are run many times. At each line you figure out what Python has done. Lets start with the simple perimeter program. Don't type it in, you are going to read it, not run
{'wiki_source': 'wikibooks', 'other_info': '{\'content_model\': \'wikitext\', \'language\': \'en\', \'title\': "Non-Programmer\'s Tutorial for Python 3/Print version", \'type\': \'text\'}'}