This game is used to settle disputes and make random decisions. There are actually competitions where money is at stake. A televised contest in Las Vegas had a prize of $50,000.
In this game, each of two players selects one item from the list (rock, paper, or scissors) in secret, and then both display their choice simultaneously. If both players selected the same item, then they try again. Otherwise, rock beats scissors, scissors beat paper, and paper beats rock. This contest can be repeated for a “best out of N” competition.
Solving the Rock-Paper-Scissors Problem
Both of these games form the first problem set, and serve as the motivation for learning the elements of the Python language.
2. Solving the Rock-Paper-Scissors Problem
The solution to this problem has no new requirements, but re-enforces the language features of the previous solutions. One solution to this problem is as follows:
- Select a random choice form the three items rock, paper, or scissors. Save this choice in a variable named choice.
- Ask the player for their choice. Use an integer value, where 1 = rock, 2 = paper, and 3 = scissors.
- Read the player’s selection into a variable named player.
- If player is equal to choice:
- Print the message “Tie. We’ll try again.”
- Repeat from Step 1
- If player is equal to rock
- If choice is equal to scissors go to Step 17
- Else go to Step 18
- If player is equal to paper
- If choice is equal to scissors go to Step 17
- Else go to step 18
- If player is equal to scissors
- If choice is equal to rock go to Step 17
- Else go to Step 18
- Print error message and terminate.
- Print “Computer wins” and terminate
- Print “You win” and terminate
For each player selection, one of the alternate items will beat it and one will lose to it. Each choice is checked and the win/lose decision is made based on the known outcomes.
The solutions to both problems require similar language elements: a way to store a value (a variable), a way to execute specific parts of the program depending on the value of a variable or expression (an if statement), a way to read a value from the keyboard, a way to print a message on the screen, and a way to execute code repeatedly (a loop).
2.1. Variables and Values-Experimenting with the Graphical User Interface
A variable is a name the programmer defines to represent a value, usually a number or a text string. It represents the place where the computer stores that value; it is a symbol in text form, representing a value. Everything that a computer does is ultimately done with numbers, so the location of any thing is a number that represents the place in computer memory where that thing is stored. It’s like offices in building. Each office has a number (its address) and usually has a name, too (the occupant or business found there). Additionally, the office has contents, and those contents are often described by the name given. Figure 1.2 shows a collection of offices in a building. In this metaphor, the office number corresponds to the address and the name (variable name), being more human friendly, is how it is often referred to by a person (programmer). In all cases, though, it is the contents of the office (location) that are important. The number and name are ways to access it. So, someone might say “Bring me the Python manual from the Server Room” or “Bring me the Python manual from 607” and both would mean the same thing. The Python manual is the content of location 607. Now, someone could say “Put this Python manual in the Digital Media Lab”, which would change the content of location 611. In actual Python, the act of retrieving a value from a location does not change the content of that location, but instead makes a copy, but the basic metaphor is sound.
Not all strings or characters can be variable names. A variable cannot begin with a digit, for example, or with most non-alphabetic characters like “&” or “!,” although in some cases beginning with “_” is acceptable. A variable name can contain upper- or lowercase letters, digits, and “_”. Uppercase and lowercase letters are not considered the same, so the variables Hello and hello are different.
A variable can change values but, unlike a real office, a simple variable can hold only one value at a time. The name chosen does not have to be significant. Programs often have variables named i or x. However, it is a good idea to select names that represent the kind of value that the variable contains so as to communicate that meaning to another person. For example, the value 3.1415926 should be stored in a variable named pi, because that’s the name everyone else gives to this value.
In the GUI, type pi = 3.1415926. Python responds with a prompt, and that it has no value to print. If you now type pi, the response is 3.1415926; the variable named pi that was just created now has a value.
In the syntax of Python, the name pi is a variable, the number 3.1415926 is a constant, but is also an expression, and the symbol = means assign to. In the precise domain of computer language, pi = 3.1415926 is an assignment statement and gives the variable named pi the specified value.
Continuing with this example, define a new variable named radius to be 10.0 using an assignment statement radius = 10.0. If you type radius and press the “Enter” key, Python responds with 10.0. Finally, we know that the circumference of a circle is 2πr in math terms, or 2 times pi times the radius in English. Type 2*pi*radius into the Python GUI, and it responds with 62.831852, which is the correct answer. Now type circumference = 2*pi*radius and Python assigns the value of the computation to the variable circumference.
Python defines a variable when it is given a value for the first time. The type of the variable is defined at that moment too; that is, if a number is assigned to a name, then that name is expected to represent a number from then on. If a string is assigned to a name, then that name is expected to be a string from then on. Trying to use a variable before it has been given a value and a type is an error. Attempting the calculation
area = side*side
is not allowed unless there is a variable named side already defined at this point. The following is acceptable because it defines side first, and then in turn is used to define area:
side = 12.0
area = side*side
The two lines above are called statements in a programming language, and in Python, a statement usually ends at the end of the line (the “Enter” key was pressed). This is a bit unusual in a computer language, and people who already know Java or C++ have some difficulty with this idea at first. In other computer languages, statements are separated by semicolons, not by the end of the line. In fact, in most languages the indenting of lines in the program does not have any meaning except to the programmer. In Python, that’s not the case either, as will be seen shortly.
The expressions we use in assignments can be pretty complicated, but are really only things that we learned in high school (add, subtract, multiply, and divide). Multiplication and division are performed before addition and subtraction, which is called a precedence rule, so 3*2+1 is 7, not 9; otherwise evaluation is done left to right, so 6/3*2 is 4 (do the division first) as opposed to 1 (if the multiplication was done first). These are rules that should be familiar because it is how people are taught to do arithmetic. The symbol ** means exponent or to the power of, so 2**3 is 23 which is 8, and this operator has a higher precedence (i.e., is done before) than the others. Parentheses can be used to specify the order of things. So, for example, (2+3)**2 is 25, because the expression within the parentheses is done first, then the exponent.
2.2. Exchanging Information with the Computer
When using most programming languages, it is necessary to carefully design the communication with the computer program. This goes two ways: the program informs the user of information, such as the circumference of a circle given a specific radius, and the user may want to tell the program certain things, like the value of the radius with which to computer the circumference. We communicate with a program using text, characters typed into a keyboard. When a computer is presenting results, that text is often in the form of human language. “The circumference is 62.831852” could be such a message. The sentence is actually composed by a programmer and has a number or collection of numbers embedded within it.
Python allows a programmer to send a message to the screen, and hence to the user, using a print directive. This is the word print followed by a character string, which is often a set of characters in quotes. An example is as follows:
print (“The answer is yes.”)
The parentheses are used to enclose everything that is to be printed; such a statement can print many strings if they are separated by commas. Numbers will be converted into strings for printing. So the following is correct:
print (“The circumference is “, 62.831852)
If a variable appears in the list following print then the value of that variable will be printed, not the name of the variable. Therefore, the following is also correct:
print (“The circumference is”, circumference)
2.3. Example 1: Draw a Circle Using Characters
Let’s print a circle with a constant predefined radius. This can be done with a few print statements. The planning of the graphic itself (the circle) can be done using graph paper. Assuming that each character uses the same amount of space, a circle can be approximated using some skillfully placed * characters. Then, we print each row of characters using a print statement. A sample solution is shown in Figure 1.4
2.4. Strings, Integers, and Real Numbers
Computer programs deal mainly with numbers. Integers, or whole numbers, and real number (reals) or floating-point numbers, which represent fractions, are represented differently and arithmetic works differently on the two types of numbers. A Python variable can hold either type, but if a variable contains an integer, then it is treated as an integer, and if it’s holding a floating-point number, then it is treated as one of those. What’s the difference? First, there’s a difference in how they are printed out. If we make the assignment var = 1 and then print the value of var, it prints simply as 1. If we make the assignment var = 1.0 and then print var, it prints as 1.0. In both cases var is a real or floating-point number and is treated as such. Numeric constants are considered real numbers. However, a variable can be first one thing and then another. It will be the last thing it was assigned.
Arithmetic differs between integers and reals, but the only time that difference is really apparent is when doing division. Integers are always whole, nonfractional numbers. If we divide 3 by 2, both 3 and 2 are integers and so the division must result in an integer: the result is 1. This is because there is exactly a single 2 in 3, or if you like, 2 goes into 3 just once, with a remainder of 1. There is a specific operator for doing integer division: //. So, 3//2 is equal to 1. The remainder part can’t be handled and is discarded, but can be found separately using the % operator. For example, 8//5 is 1, and 8%5 is the remainder, 3. This explanation is an approximation to the truth, and one that can be cleared up later, but works perfectly well for positive numbers.
Of course, fractions work fine for real numbers, and are printed as decimal fractions: 8.0/5.0 is 1.6, for example. What happens if we mix real numbers and integers? In those cases, numbers get converted into real numbers, but now things get more complicated because order can matter a great deal. The expression 7//2*2.0 does the division 7//2 first, which is 3, and then multiplies that by 2.0, yielding the result 6.0; the result of 8/3*3.0 is 5.333. Mixing integers and real numbers is not a good idea, but if done, then the expressions should use parentheses to specify how the expression should be evaluated.
A real number can be used in place of an integer in most places, but the result is a real number. Thus, 2.0 * 3 = 6.0, not 6, and 6.0//2 is 3.0, not 3. There are some exceptions. To convert an integer to a real number, there is a special operation named float: float(3) yields 3.0. Of course, it’s possible to simply multiply by 1.0, and the result is a floating value, too. Converting float values to integers is more complicated because of the fraction issue: what happens to the digits to the right of the decimal? The operation int takes a floating-point value and throws away the fraction. The value of int (3.5) is 3, as a result. We can round this to the nearest integer, and the operation round (3.5) does that, resulting in 4.
2.5. Number Bases
In elementary school, the idea of positional number systems is taught. The number 216 is a way to write the value of 6 + 1*10 + 2*100. Not all civilizations use such a scheme; Roman numerals are not positional, for example. Still, most people are comfortable with the idea. What people are not as comfortable with is changing the number base away from 10. In Chapter 0, the binary system, or base 2, was discussed, but any base that is a power of 2 is of some interest, especially base 8 and base 16.
Humans use a base 10 scheme (probably because we have 10 fingers). We have a symbol for each of the 10 digits, 0 through 9, and each digit position to the left of the first digit is multiplied by the next power of 10. The number 216 is 2* 102 + 1* 101 + 6* 100. The base is 10, and each digit represents a power of the base multiplied by a digit. What if the base is 8? In that case, 216 is really 2*82 +1*81 + 6. If the arithmetic is carried out, this number is 128+8+6 = 142.
If multiple number bases are used, it is common to give the base as a subscript. The number 216 in base 8 is written as 2168. The default would be base 10. In base 8, there are only 8 digits, 0 through 7. The digits 8 and 9 cannot appear. In bases larger than 10, more symbols are needed. A common base used on computers is 16, or hexadecimal (hex for short). In a hex number, 16 digits are needed, so the regular ones are used and then “A” represents 10, “B” is 11, “C” is 12, “D” is 13, “E” is 14, and “F” is 15. The hex number 12 is 1*16 + 2, or 18in. The number
1A16 is 1*16 + 10 = 2610.
In Python, numbers are given in decimal (base 10) by default. However, if a number constant begins with “0o” (zero followed by the letter “o”), Python assumes it is base 8 (octal). The number 0o21, for example, is 218 = 1710. A number that begins with “0x” is hexadecimal. 0x21 is 2116 = 3310. This applies only to integers.
Base 2 is the most important number base because it underlies all of the numbers on a computer. All numbers on a modern digital computer are represented in base 2, or binary, in their internal representation. A binary number has only two digits, 0 and 1, and each represents a power of 2. Thus, 11012 is 1*23 + 1*22 + 0*21+ 1 = 8 + 4 + 1 = 1310. In Python, a binary number begins with “0b,” so the number 0b10101 represents 2110.
These number bases are important for many reasons, but base 2 is fundamental, and bases 8 and 16 are important because they are powers of 2 and so convert very easily to binary but have fewer digits. One example of the use of hex is for colors. In Python, they can represent a color, and on Web pages they are certainly used that way. The number 0xFF0000 is the color red, for example, if used on a Web page.
2.6. Example 2: Compute the Circumference of Any Circle
When humans input information into a computer program, the text tends to be in the form of numbers. The Python code that was written to calculate the radius of a circle only did the calculation for a single radius: 10. That’s not as useful as a program that computes the circumference of any circle, and that would mean allowing the user to tell the program what radius to use. This should be easy to do, because it is something that is needed frequently. In the case of sending a number into a program in Python, the word input can used within a program. For example,
radius = input ()
accepts a number from the keyboard, typed by the user, and returns it as a string of characters. This makes sense because the user typed it as a string of characters, but it can’t be used in a calculation in this form. To convert it into the internal form of a number, we must specifically ask for this to be done:
radius = input()
radius = float(radius)
reads a string into radius, then converts it into a floating point (real) number and assigns it to the variable radius again. This can be done all in one statement:
radius = float(input())
Now the variable radius can be used to calculate a circumference. If the value of radius is an integer, the code is as follows:
radius = int(input())
If the conversion to a number is not done then Python will give an error message when the calculation is performed, like:
Traceback (most recent call last):
File “<pyshell#13>”, line 1, in <module> circumference = 2*pi*radius
TypeError: can’t multiply sequence by non-int of
The line of code at which the error occurs is given and the term TypeError is descriptive. This error means that something that can’t be multiplied (a string) was used in an expression involving multiplication. That thing is the variable radius in this instance because it was and text string and was not converted to a number.
Note that int(input()) can present problems when the input string is not an integer. If it is a floating-point number, this results in an error. The expression int (“3.14159”) is interpreted as an attempt convert pi into an integer, and so has the value 3 (which is erroneous). The function int was passed a string and the string contained a float, not an integer. This is something of a quirk of Python. It is better to convert input numbers into floats.
2.7. Guess a Number Again
The simple version of the guessing program can now nearly be written in Python. Examining the method of solution, here’s what can be coded so far; versions depend on who is guessing. The computer should pick the number and the human user should guess, because the other way around can involve some complex programming. In that case, here’s what has to happen:
- The computer selects a number.
choice = 7
- The computer asks the player to guess.
print (“Please guess a number between 1 and 10: “)
- The player types a number on the keyboard and the computer reads it in.
playerchoice = input()
- The computer compares the input number against the one that it selected and if the two agree, then the player wins. Otherwise the computer wins.
It is the final step that is still not possible with what is known. It is necessary in this program, as it is in most computer programs, to make a decision and to execute certain code (i.e., do specific things) conditionally based on the outcome of that decision. People do that sort of thing all of the time in real life. Examples include the following:
“If the light is red, then stop; otherwise continue through the intersection.”
“If all tellers are busy when you arrive at the bank, then stand in line and wait
for the next one to become available.”
“If you need bread or milk, then stop at the grocery store on the way home.”
“If it rains, the picnic will be cancelled.”
Notice that all of these examples use the word “if” This word indicates a standard conditional sentence in English. The condition in the first case is the phrase “if the light is red” (called in English the protasis or antecedent) and the consequence to that is the phrase “then stop” (the apodosis or consequent). Terminology aside, the intent is clear to an English speaker: on the condition that or in the event that the light is red, then the necessary action is that the driver is to stop their car. The action is conditional on the antecedent, which in Python is called an expression or more precisely a logical expression, which has the value True or False.
The structure or syntax of this sort of thing in Python is as follows:
if the light is red:
or more exactly,
if light == red:
# execute whatever code makes the car stop
This is called an if statement.
Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.