Don't spend your time doing work a well-trained monkey could do. Even if you've never written a line of code, you can make your computer do the grunt work.
Learn how in Automate the Boring Stuff with Python. Al Sweigart is a software developer and teaches programming to kids and adults. He has written several books for beginners and makes them freely available at InventWithPython. Pro Python, 2nd Edition Apress, J. Computers Posted on Posted on Computer programming Posted on Juvenile Nonfiction Posted on Young Adult Nonfiction Posted on Python will keep evaluating parts of the expression until it becomes a single value, as shown in Figure Figure Evaluating an expression reduces it to a single value.
These rules for putting operators and values together to form expressions are a fundamental part of Python as a programming language, just like the grammar rules that help us communicate. This grammatically is sentence not English correct a. Professional software developers get error messages while writing code all the time. The Integer, Floating-Point, and String Data Types Remember that expressions are just values combined with operators, and they always evaluate down to a single value.
A data type is a category for values, and every value belongs to exactly one data type. The most common data types in Python are listed in Table The values -2 and 30, for example, are said to be integer values. The integer or int data type indicates values that are whole numbers. Numbers with a decimal point, such as 3. Note that even though the value 42 is an integer, the value Always surround your string in single quote ' characters as in 'Hello' or 'Goodbye cruel world!
You can even have a string with no characters in it, '', called a blank string. Strings are explained in greater detail in Chapter 4. Your code will have to explicitly convert the integer to a string, because Python cannot do this automatically.
Converting data types will be explained in Dissecting Your Program when talking about the str , int , and float functions. Enter a string multiplied by a number into the interactive shell to see this in action.
Otherwise, Python will just display an error message. If you want to use the result of an evaluated expression later in your program, you can save it inside a variable. An assignment statement consists of a variable name, an equal sign called the assignment operator , and the value to be stored.
Think of a variable as a labeled box that a value is placed in, as in Figure This is called overwriting the variable. When a new value is assigned to a variable, the old one is forgotten. Variable Names Table has examples of legal variable names. You can name a variable anything as long as it obeys the following three rules: 1. It can be only one word. It is a Python convention to start your variables with a lowercase letter.
Some experienced programms may point out that the official Python code style, PEP 8, says that underscores should be used. When in doubt, use your best judgment. Imagine that you moved to a new house and labeled all of your moving boxes as Stuff. The file editor is similar to text editors such as Notepad or TextMate, but it has some specific features for typing in source code. The file editor lets you type in many instructions, save the file, and run the program.
In the Save As window, enter hello. You should save your programs every once in a while as you type them. Your program should run in the interactive shell window that appeared when you first started IDLE. Remember, you have to press F5 from the file editor window, not the interactive shell window.
Enter your name when your program asks for it. What is your name? Al It is good to meet you, Al The length of your name is: 2 What is your age? You can also say that the Python program exits. You can close the file editor by clicking the X at the top of the window.
Do that now, and in the window that appears, choose hello. Your previously saved hello. Comments The following line is called a comment. Python ignores comments, and you can use them to write notes or remind yourself what the code is trying to do. Any text for the rest of the line following a hash mark is part of a comment. Sometimes, programmers will put a in front of a line of code to temporarily remove it while testing a program. You can remove the later when you are ready to put the line back in.
Python also ignores the blank line after the comment. You can add as many blank lines to your program as you want. This can make your code easier to read, like paragraphs in a book. The print Function The print function displays the string value inside the parentheses on the screen. A value that is passed to a function call is an argument. Notice that the quotes are not printed to the screen. They just mark where the string begins and ends; they are not part of the string value.
NOTE You can also use this function to put a blank line on the screen; just call print with nothing in between the parentheses. When writing a function name, the opening and closing parentheses at the end identify it as the name of a function. Chapter 2 describes functions in more detail. You can think of the input function call as an expression that evaluates to whatever string the user typed in.
If 'Al' is the value stored in myName on the previous line, then this expression evaluates to 'It is good to meet you, Al'. This single string value is then passed to print , which prints it on the screen. The len Function You can pass the len function a string value or a variable containing a string , and the function evaluates to the integer value of the number of characters in that string.
It is then passed to print to be displayed on the screen. Notice that print allows you to pass it either integer values or string values. You get the same error message if you type the expression into the interactive shell on its own.
You can fix this by using a string version of the integer instead, as explained in the next section. This is the value that is passed to the print function. The str , int , and float functions will evaluate to the string, integer, and floating- point forms of the value you pass, respectively. Try converting some values in the interactive shell with these functions, and watch what happens.
The str function is handy when you have an integer or float that you want to concatenate to a string. The int function is also helpful if you have a number as a string value that you want to use in some mathematics. For example, the input function always returns a string, even if the user enters a number.
If you want to do math using the value in spam, use the int function to get the integer form of spam and then store this as the new value in spam. If you want to round a floating-point number up, just add 1 to it afterward. Because the input function always returns a string even if the user typed in a number , you can use the int myAge code to return an integer value of the string in myAge.
The string value returned is then concatenated with the strings 'You will be ' and ' in a year. This large string is finally passed to print to be displayed on the screen. The string '4' is converted to an integer, so you can add one to it. The result is 5. The str function converts the result back to a string, so you can concatenate it with the second string, 'in a year.
These evaluation steps would look something like Figure You can even do string replication easily by copying and pasting text. But expressions, and their component values — operators, variables, and function calls — are the basic building blocks that make programs. Once you know how to handle these elements, you will be able to instruct Python to operate on large amounts of data for you.
A few different functions were introduced as well. The print and input functions handle simple text output to the screen and input from the keyboard. The len function takes a string and evaluates to an int of the number of characters in the string. The str , int , and float functions will evaluate to the string, integer, or floating- point number form of the value they are passed.
In the next chapter, you will learn how to tell Python to make intelligent decisions about what code to run, what code to skip, and what code to repeat based on the values it has.
This is known as flow control, and it allows you to write programs that make intelligent decisions. Practice Questions Q: 1. Which of the following are operators, and which are values? Which of the following is a variable, and which is a string? Name three data types. What is an expression made up of? What do all expressions do? What is the difference between an expression and a statement? What does the variable bacon contain after the following code runs?
What should the following two expressions evaluate to? Why is eggs a valid variable name while is invalid? What three functions can be used to get the integer, floating-point number, or string version of a value?
Q: Why does this expression cause an error? How can you fix it? Flow Control So you know the basics of individual instructions and that a program is just a series of instructions.
Based on how the expressions evaluate, the program can decide to skip instructions, repeat them, or choose one of several instructions to run. In fact, you almost never want your programs to start from the first line of code and simply execute every line, straight to the end.
Flow control statements can decide which Python instructions to execute under which conditions. Follow the path made by the arrows from Start to End. A flowchart to tell you what to do if it is raining In a flowchart, there is usually more than one way to go from the start to the end.
The same is true for lines of code in a computer program. Flowcharts represent these branching points with diamonds, while the other steps are represented with rectangles. The starting and ending steps are represented with rounded rectangles. But before you learn about flow control statements, you first need to learn how to represent those yes and no options, and you need to understand how to write those branching points as Python code.
Boolean Values While the integer, floating-point, and string data types have an unlimited number of possible values, the Boolean data type has only two values: True and False. Boolean is capitalized because the data type is named after mathematician George Boole. When typed as Python code, the Boolean values True and False lack the quotes you place around strings, and they always start with a capital T or F, with the rest of the word in lowercase.
Enter the following into the interactive shell. Comparison Operators Comparison operators compare two values and evaluate down to a single Boolean value. Table lists the comparison operators. After all, instead of typing 'dog'! Boolean Operators The three Boolean operators and, or, and not are used to compare Boolean values. Like comparison operators, they evaluate these expressions down to a Boolean value.
The and operator evaluates an expression to True if both Boolean values are True; otherwise, it evaluates to False. Enter some expressions using and into the interactive shell to see it in action.
Table is the truth table for the and operator. If both are False, it evaluates to False. The not operator simply evaluates to the opposite Boolean value. Table shows the truth table for not. Recall that the and, or, and not operators are called Boolean operators because they always operate on the Boolean values True and False. Try entering some Boolean expressions that use comparison operators into the interactive shell.
When it knows the Boolean value for each, it will then evaluate the whole expression down to one Boolean value. You can also use multiple Boolean operators in an expression, along with the comparison operators. After any math and comparison operators evaluate, Python evaluates the not operators first, then the and operators, and then the or operators. Elements of Flow Control Flow control statements often start with a part called the condition, and all are followed by a block of code called the clause.
Conditions always evaluate down to a Boolean value, True or False. A flow control statement decides what to do based on whether its condition is True or False, and almost every flow control statement uses a condition.
Blocks of Code Lines of Python code can be grouped together in blocks. You can tell when a block begins and ends from the indentation of the lines of code. There are three rules for blocks. Blocks begin when the indentation increases.
Blocks can contain other blocks. The program execution or simply, execution is a term for the current instruction being executed. If you print the source code on paper and put your finger on each line as it is executed, you can think of your finger as the program execution.
Not all programs execute by simply going straight down, however. The statements represent the diamonds you saw in the flowchart in Figure , and they are the actual decisions your programs will make. The clause is skipped if the condition is False. Pretend name was assigned some value earlier. Figure shows what a flowchart of this code would look like. Or else, execute that code. The flowchart for an else statement elif Statements While only one of the if or else clauses will execute, you may have a case where you want one of many possible clauses to execute.
It provides another condition that is checked only if any of the previous conditions were False. You can see the flowchart for this in Figure However, if both of the conditions are False, then both of the clauses are skipped.
It is not guaranteed that at least one of the clauses will be executed. When there is a chain of elif statements, only one or none of the clauses will be executed. For example, open a new file editor window and enter the following code, saving it as vampire. Figure shows the flowchart for this. The flowchart for multiple elif statements in the vampire. Remember that the rest of the elif clauses are automatically skipped once a True condition has been found, so if you swap around some of the clauses in vampire.
Change the code to look like the following, and save it as vampire2. You might expect the code to print the string 'Unlike you, Alice is not an undead, immortal vampire.
Remember, at most only one of the clauses will be executed, and for elif statements, the order matters! Figure shows the flowchart for the previous code. Optionally, you can have an else statement after the last elif statement. In that case, it is guaranteed that at least one and only one of the clauses will be executed. If the conditions in every if and elif statement are False, then the else clause is executed.
Else, if the second condition is true, do that. Otherwise, do something else. First, there is always exactly one if statement. Any elif statements you need should follow the if statement.
Second, if you want to be sure that at least one clause is executed, close the structure with an else statement. The flowchart for the vampire2. The crossed-out path will logically never happen, because if age were greater than , it would have already been greater than Flowchart for the previous littleKid.
In code, a while statement always consists of the following: The while keyword A condition that is, an expression that evaluates to True or False A colon Starting on the next line, an indented block of code called the while clause You can see that a while statement looks similar to an if statement.
The difference is in how they behave. At the end of an if clause, the program execution continues after the if statement. But at the end of a while clause, the program execution jumps back to the start of the while statement. The while clause is often called the while loop or just the loop. But when you run these two code snippets, something very different happens for each one.
For the if statement, the output is simply "Hello, world. Take a look at the flowcharts for these two pieces of code, Figure and Figure , to see why this happens. The flowchart for the while statement code The code with the if statement checks the condition, and it prints Hello, world.
The code with the while loop, on the other hand, will print it five times. In the while loop, the condition is always checked at the start of each iteration that is, each time the loop is executed. If the condition is True, then the clause is executed, and afterward, the condition is checked again. The first time the condition is found to be False, the while clause is skipped. This is so that the name! Since this is the last line of the block, the execution moves back to the start of the while loop and reevaluates the condition.
If the value in name is not equal to the string 'your name', then the condition is True, and the execution enters the while clause again. But once the user types your name, the condition of the while loop will be 'your name'! Figure shows a flowchart for the yourName.
A flowchart of the yourName. Press F5 to run it, and enter something other than your name a few times before you give the program what it wants. Please type your name. Al Please type your name. Albert Please type your name. Here, the input call lets the user enter the right string to make the program move on.
In other programs, the condition might never actually change, and that can be a problem. In code, a break statement simply contains the break keyword. Pretty simple, right?
Enter the following code, and save the file as yourName2. The expression True, after all, always evaluates down to the value True. The program execution will always enter the loop and will exit it only when a break statement is executed.
An infinite loop that never exits is a common programming bug. Since this condition is merely the True Boolean value, the execution enters the loop to ask the user to type your name again. See Figure for the flowchart of this program. Run yourName2. The rewritten program should respond in the same way as the original.
The flowchart for the yourName2. Note that the X path will logically never happen because the loop condition is always True. This is also what happens when the execution reaches the end of the loop. This will send a KeyboardInterrupt error to your program and cause it to stop immediately. To try it, create a simple infinite loop in the file editor, and save it as infiniteloop. Enter the following code into a new file editor window and save the program as swordfish. What is the password?
It is a fish. When it reevaluates the condition, the execution will always enter the loop, since the condition is simply the value True.
Otherwise, the execution continues to the end of the while loop, where it then jumps back to the start of the loop. A flowchart for swordfish. The X path will logically never happen because the loop condition is always True. When used in conditions, 0, 0. You could have typed not name! Run this program and give it some input. Who are you? I'm fine, thanks. Joe Hello, Joe. Mary Who are you?
You can do this with a for loop statement and the range function. The first time it is run, the variable i is set to 0. The print call in the clause will print Jimmy Five Times 0. The variable i will go up to, but will not include, the integer passed to range. Figure shows a flowchart for the fiveTimes.
The flowchart for fiveTimes. In fact, you can use continue and break statements only inside while and for loops.
If you try to use these statements elsewhere, Python will give you an error. As another for loop example, consider this story about the mathematician Karl Friedrich Gauss. When Gauss was a boy, a teacher wanted to give the class some busywork. The teacher told them to add up all the numbers from 0 to Young Gauss came up with a clever trick to figure out the answer in a few seconds, but you can write a Python program with a for loop to do this calculation for you.
By the time the loop has finished all of its iterations, every integer from 0 to will have been added to total. Even on the slowest computers, this program takes less than a second to complete.
Clever kid! An Equivalent while Loop You can actually use a while loop to do the same thing as a for loop; for loops are just more concise. The Starting, Stopping, and Stepping Arguments to range Some functions can be called with multiple arguments separated by a comma, and range is one of them. This lets you change the integer passed to range to follow any sequence of integers, including starting at a number other than zero. The first two arguments will be the start and stop values, and the third will be the step argument.
Otherwise, Python will just display an error message. If you want to use the result of an evaluated expression later in your program, you can save it inside a variable. An assignment statement consists of a variable name, an equal sign called the assignment operator , and the value to be stored. Figure This is called overwriting the variable. Enter the following code into the interactive shell to try overwriting a string:. Just like the box in Figure , the spam variable in this example stores 'Hello' until you replace it with 'Goodbye'.
Table has examples of legal variable names. You can name a variable anything as long as it obeys the following three rules:. It is a Python convention to start your variables with a lowercase letter.
Some experienced programmers may point out that the official Python code style, PEP 8, says that underscores should be used. When in doubt, use your best judgment.
A good variable name describes the data it contains. Imagine that you moved to a new house and labeled all of your moving boxes as Stuff. The file editor is similar to text editors such as Notepad or TextMate, but it has some specific features for typing in source code. The file editor lets you type in many instructions, save the file, and run the program. When the file editor window opens, type the following into it:.
In the Save As window, enter hello. You should save your programs every once in a while as you type them. Your program should run in the interactive shell window that appeared when you first started IDLE.
Remember, you have to press F5 from the file editor window, not the interactive shell window. Enter your name when your program asks for it. When there are no more lines of code to execute, the Python program terminates ; that is, it stops running.
You can also say that the Python program exits. You can close the file editor by clicking the X at the top of the window. Do that now, and in the window that appears, choose hello.
Your previously saved hello. Python ignores comments, and you can use them to write notes or remind yourself what the code is trying to do. Any text for the rest of the line following a hash mark is part of a comment. Sometimes, programmers will put a in front of a line of code to temporarily remove it while testing a program.
You can remove the later when you are ready to put the line back in. Python also ignores the blank line after the comment. You can add as many blank lines to your program as you want.
This can make your code easier to read, like paragraphs in a book. The print function displays the string value inside the parentheses on the screen. The line print 'Hello world! A value that is passed to a function call is an argument. Notice that the quotes are not printed to the screen. They just mark where the string begins and ends; they are not part of the string value.
0コメント