«Если рабочий хочет хорошо выполнять свою работу, он должен сначала заточить свои инструменты» — Конфуций, «Аналитики Конфуция. Лу Лингун»
титульная страница > программирование > Руководство для начинающих по Python

Руководство для начинающих по Python

Опубликовано 5 ноября 2024 г.
Просматривать:595

Beginners guide to Python

For Hugo. Choose your own doors to open.

What is this article?

Think of this article as a taster session. By the end of it you will have:

  • Written a complete program in Python to play a game.
  • Learnt enough Python to write your own simple programs.
  • Encountered the sorts of problems programmers have to deal with every day, and seen how to solve them.

Hopefully you will enjoy it. If you do there a number of suggestions for further learning at the end. If you don't you will at least understand what it is a programmer does, and the effort it takes to make a computer do what you want it to. Above all the aim is to help you realize that you can learn to program a computer, if you want to.

A joke

Did you hear the one about the programmer's wife? She asked her husband to go to the supermarket and buy a loaf of bread. As he headed out the door, she said "if they have eggs, get a dozen". The programmer dutifully came home with twelve loaves of bread.

Confused? Don't worry, it's most likely because you don't know how to think like a computer programmer (yet).

Hello, world!

We learn best by doing. Let's write some code. We will use the Python programming language as it is simple to read and write. To keep setup to a minimum, we will use the free online Python programming environment at trinket.io. You can use any device with an internet connection and you don't need to install anything.

Task

Go to the trinket.io website. Click the Sign Up link at the top. Fill out the form to create a free account.

Once you have completed the sign up process, you need to login to the website.

Task

Click the Log In link at the top. Enter your username and password on the form.

Trinket refers to each program you write as a trinket. To create a new program click the blue New Trinket and select Python from the list.

Task

Create a new trinket, select Python from the available options.

You should now see the program editor page. The left hand side of the screen is where you will type in Python code. It has a tab named main.py. We will call this the code pane. The right hand side of the screen is where you will see the output from running your code. We will call this the output pane. At the moment this is blank. Up top there should be space for giving this trinket a name. It currently has the text untitled.

Task

Give your trinket the name hello world by clicking on the untitled text and typing it in. Click the save button to save your changes.

You are now ready to write a Python program.

Task

In the code pane carefully enter the following two lines of text, including all the punctuation marks.

#!/bin/python3

print("Hello world!")

Save your changes by clicking the Save button again. Get in to the habit of saving your work regularly. The internet is mostly reliable but sometimes things go wrong. We don't want to lose our work.

We've typed in a program! But nothing happened. We need to tell Python to run our program. Running a program makes Python read each line of our code, and turn it into instructions the computer can understand.

Task

Click the large triangle button at the top of the code pane. This is the Run button. See what happens.

Did it work?

If all went well you should have seen the text Hello world! in the output pane. Don't worry if you didn't. I'll help you to diagnose and fix the problem.

Fixing problems in your code is called debugging and programmers do it a lot. Even if your code worked it is still worth reading through the steps below. Sooner or later you'll need to use them.

  1. Python should give you an error message when something goes wrong. This is shown in a pale red box at the bottom of the screen.

  2. The error message will often include the number of the line in your code Python had a problem with. This is the best place to start looking for a bug.

  3. Double check that what you typed in on that line matches the code given in the example. Punctuation is important, as are letters being upper case or lower case. In some cases spacing is also important (we will cover these later).

  4. Correct the line so it matches the code in the example. Save your changes and run your program again.

It's common to have to go through these steps several times before you get a working program, especially when learning. As you get familiar with Python code this will happen less often, so don't worry.

Task

If your program didn't work, go through the process outlined above until you see the message Hello world! in the output pane.

What's with the funny looking first line?

Our program actually only has one line of code that does something, the one with the print() command on it. The first line is a special one that tells the computer to use version 3 of Python. This is the most up to date version of Python and is the one we will be using.

Printing other things

The print statement we saw in the previous program can be used to say any number of things on the screen. The message we want to display appears between the beginning and end quote marks ".

Task

Change the print() command in your program to say different things. Run your program after each change to see if Python will print out your new message.

Are there any things it can't print out? Do some messages cause an error?

This sort of trial and error approach to writing code is a useful way of learning a new feature of a language. Hopefully you got Python to successfully print out another message.

You might also have discovered that trying to print out a message that included the double quote " symbol caused an error. This is because we use " to mark the beginning and end of the message. If we want to print out a message that includes a " we have two options:

  1. Use a single quote ' to mark the beginning and end of the message instead of a double quote. For example print('A "word" in double quote marks.').

  2. Precede the double quotes in the message with a backslash \ character. For example print("Another \"word\" in double quote marks.").

Task

Type in both of the examples for printing a message with double quote marks in it. Add these lines to the end of your program. Run your program and check the messages shown on screen include the quote marks.

Using a backslash to print a quote mark is known as escaping. It tells Python to ignore the special meaning of the quote mark that follows. The print() command supports a number of different escape sequences for printing out difficult characters. The following ones often come in handy.

Escape sequence     Output
-------------------------------------------------------------------------------
\\                  A backslash.
\'                  A single quote mark.
\"                  A double quote mark.
\n                  A newline.
\t                  A tab.

Task

Write a print() command for each of the following messages. Add the necessary escape sequences to each one. For example, the first one needs a newline added to it.

  1. This is on one line. This is on another.

  2. This "message" has double and 'single' quotes in it.

  3. These words each have a tab between them.

  4. There's a \ in this message.

Sometimes we want to write a lot of text spanning several lines. When this is the case Python lets us begin and end the block of text with three of the same quote marks - either """ or '''. Messages written in this way will be printed out as is.

print("""This is a very long
message that will be 
printed
out across several lines!""")

Task

Write a print() command that uses the triple quotes for its message. Make the message span several lines. Run your program and see how Python outputs it on screen.

Can you use any of the escape sequences in your triple quoted message?

Asking questions

So far our program can output messages to the screen. It would be useful if we could also receive input from somewhere too.

The input() command lets us do just this. We can use it to prompt for input from the keyboard.

Task

Add the following lines of code to the end of your program. Save your changes.

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

Task

Run your program. In the output pane type in your name when prompted and press enter. Your program should say hello to you.

What just happened?

Despite only being two lines of code, quite a lot just happened. Let's break it down.

  1. We created a variable called name. A variable is a label we use to remember things in a program.

  2. We got some input from the keyboard using the input() command, and assigned it to name using the equals = sign. Assignment is like putting a sticky label on something. In this case we put the label name on to some input from the keyboard.

  3. We passed two arguments to the print() command. One was the message Hello, the other was the name variable.

Note how Python didn't print out the word name, but instead whatever we typed in at the keyboard and had assigned to name.

Task

Try running your program several times typing in something different each time. We called our variable name but Python lets us type in any text we like.

Anything we want to remember in a program must be assigned to a variable. You can have as many variables as you like in a program, the only limit is the amount of memory present on the computer.

Making decisions

Alongside input and output another basic ability our programs need is to make decisions. Programs typically look at the content of one or more variables and then decide what to do. Python uses the if statement for this purpose.

#!/bin/python3

birthplace = input("Where were you born?")

if birthplace == "England":
    print("So was I!")

In the code above Python will print out the message So was I! only if you enter a birthplace of England (with a capital letter E).

The statement birthplace == "England" is known as a condition. Conditions can be true or false. When the condition is true the code associated with the if runs.

How does Python know what lines to run when the if statement is true? First we end the line with a colon :. Then we indent the lines it should run with a single tab. Any lines that are indented Python considers to be part of the if statement.

We use a double equals == to see if one thing is the same as another in Python. It's a common mistake to get this mixed up with the single equals = which is used for assignment to a variable (as we saw with the input() command earlier).

Task

Create a new trinket and give it the name Questions. Type in the lines from the example above and save your changes.

Task

Run your program twice - once with "England" as the input and once with somewhere else. See that the message is only printed out for England.

Making more than one decision

We can add additional statements to the basic if to check for other conditions. The simplest of these is else. Lines associated with an else only run when the if condition isn't true. Let's expand our example.

#!/bin/python3

birthplace = input("Where were you born?")

if birthplace == "England":
    print("So was I!")
else:
    print(birthplace, "is a nice place.")

Task

Change your birthplace program to look like the one above. Note the use of else: and the indentation of the second print() command with a tab.

If we run this new version of our program we should see that it prints out one message or the other depending on if we input England or something else.

Task

Run your program several times with different place names. See which message gets printed out for each palce.

We can also add conditions with elif, which is short for else if. The program below shows how to do this.

#!/bin/python3

birthplace = input("Where were you born?")

if birthplace == "England":
    print("So was I!")
elif birthplace == "Ireland":
    print ("Next door to me.")
else:
    print(birthplace, "is a nice place.")

Task

Modify your program again, this time adding in the elif statement and associated print() command.

Running this new program we should see one of three messages in the output pane, depending on if we enter England, Ireland, or somewhere else when prompted.

Task

Run your program several times with different place names. See which message gets printed out for each place.

Making a game

Believe it or not we now know (almost) enough Python to write a game. With input, output, and decisions we can play Rock, Paper, Scissors!

For those unfamiliar with the game, a quick summary. A game for two players, on the count of three both pick one of rock, paper, or scissors by making an appropriate shape with their hand. The winner is determined as follows:

  • Rock blunts scissors.
  • Paper wraps rock.
  • Scissors cut paper.

If both players make the same choice the game is a draw.

In our version of the game you will be one player and the computer the other. We'll need a way for the computer to make a choice. Also we can't use hand shapes (at the time of writing computers don't come with hands), so we'll have to find some other way to represent the choices you and the computer make.

Task

Create a new trinket and call it Rock, Paper, Scissors. Write the funny first line that tells the computer to use Python version 3. Save your changes.

An algorithm

Before starting to write code we should get a clear idea of what we want our program to do. Let's write out the steps needed to play the game in plain English.

  1. Make the computer pick a random choice between rock, paper, or scissors.
  2. Remember the choice in a variable.
  3. Ask the player to choose either rock, paper, or scissors.
  4. Remember the choice in a variable.
  5. Print both choices on screen - for example rock vs scissors.
  6. Compare the two variables to see who has won, or if the game is a draw.
  7. Print out a message to say if the player won, drew, or lost the game.

The description we just wrote is our algorithm for playing Rock, Paper, Scissors. An algorithm helps us get a clear understanding of what our program is trying to do before we sit down to write code. If ever we get stuck coding, we can refer to our algorithm to remind us what to do next.

Task

Write out each line of the algorithm in the code pane, putting a hash # symbol at the start of each line. This symbol tells Python the line is a comment. Comments are there to help the programmer with useful information and are ignored by Python.

#!/bin/python3

# 1. Make the computer pick a random choice between rock, paper, or scissors.
# 2. Remember the choice in a variable.
# 3. Ask the player to choose either rock, paper, or scissors.
# 4. Remember the choice in a variable.
# 5. Print both choices on screen - for example `rock vs scissors`.
# 6. Compare the two variables to see who has won, or if the game is a draw.
# 7. Print out a message to say if the player won, drew, or lost the game.

The computer's choice

Python is often described as coming with batteries included. This is because there is a large library of pre-written code that you can use in your programs. Such code can do useful things for us without having to work out how to do it for ourselves. Generating random things is one of those useful functions we can find in the Python library.

To use a part of the Python library we must first import it into our program by name. Parts of the library are known as modules and they all have a unique name to identify them. To make the computer pick something at random we will import the random module.

Task

Add the line below to your program, after the comments describing the algorithm, to import the random module.

import random

The first port of call when using a new module is to take a look at the documentation for it. This gives details on all the functions contained in the module. Functions are pieces of named code that do specific things. The print() and input() commands we have been using so far are actually functions. From now on we will use the term function instead of command.

Task

Trinket has built in documentation for some Python modules. To access it click on the hamburger menu (the three horizontal lines) above your code pane. Click the Modules link to open the documentation. Scroll down the list and click on the random entry.

Have a look at the information but don't worry if it doesn't make sense just yet! To get back to your code, click the hamburger menu again and click on Modules to close the documentation.

It may look quite intimidating but after some practice coding, the documentation will become easier to understand. For now, know that we are interested in the function random.randint(). This function is used to make the computer generate a random number between a minimum and maximum that we decide.

How does this help us with our game? Well we can't get the computer to pick the words rock, paper, or scissors, but we can use the numbers 1, 2, and 3 to represent the choices.

1 rock
2 paper
3 scissors

Let's do this in our program now.

Task

Add the following lines to the end of your program.

# Get computer choice.
comp_choice = random.randint(1,3)

Here we ask the randint() function for a random number between 1 and 3, and assign it to a variable named comp_choice (short for computer choice).

The player's choice

One choice down one to go. We can prompt the player for their choice using the input() function, like we did in previous exercises. As with the computer we want the player to choose a number between 1 and 3.

player_choice = input ("1 rock, 2 paper, 3 scissors?")

This will capture the keyboard input and assign it to the player_choice variable. There is however a problem. To understand it we need to expand our knowledge of variables a little.

Types of things

All variables in Python have a type associated with them. The type describes what sort of data the variable refers to. Our comp_choice variable is of type int which is short for integer. An integer is a whole number (one without a decimal point in it). 1, 23, and 2006 are all examples of integers.

On the other hand our player_choice variable is of type str which is short for string. A string is any piece of text. "Hello", "nice to meet you", and "tasty bacon" are all examples of strings.

When we come to work out who has won the game we are going to need to compare both choices. It is here that the problem arises. The integer 1 is not the same as the string "1". So how do we solve this problem?

Python provides functions for converting one type of data to another. We can use the int() function on a string to to turn it into an integer, and assign this to a new variable.

Confused? Let's see an example.

# Get player choice.
input_str = input ("1 rock, 2 paper, 3 scissors? ")
player_choice = int(input_str)

This revised code for getting the players choice first assigns the keyboard input (which is a string) to the variable input_str. It then uses the int() function to turn the string in to an integer, and assigns it to the variable player_choice.

Task

Add the code for getting the player's choice given in the sample above to the end of your program. Run your program and enter a number between 1 - 3. There wont be any output yet, but neither should there be any errors.

Showing both choices

Now that we have both choices we can print out a message along the lines of rock vs paper on screen. Alas we now have another issue relating to how choices are represented in our program. Both choices are numbers, and printing out 1 vs 2 isn't what we want to see. What we want to see is rock vs paper.

Using if, elif, and else we can write code to print out the correct word for each choice.

# Show player choice.
if player_choice == 1:
    print("rock", end=" ")
elif player_choice == 2:
    print("paper", end=" ")
else:
    print("scissors", end=" ")

What's with the extra end=" " argument in the call to print()? Normally the print function will automatically add a newline to the end of the text we give it. For us that is a problem as we want rock vs paper to appear all on one line, and we haven't finished writing it all out to the screen yet. We can change this behaviour by giving the print function an end argument that has a different character to use at the end of a line. We will use a single space instead of the default newline.

Task

Add the code to print out the players choice to the end of your program. Run your program and see that it successfully prints out your choice as a word.

Our message is halfway there. Let's print out the computer's choice to finish the job.

# Show computer choice.
if comp_choice == 1:
    print("vs rock")
elif comp_choice == 2:
    print("vs paper")
else:
    print("vs scissors")

In this case we can let the print function add a newline to the end, as we have now written out the full message.

Task

Add the code to print out the computer's choice to the end of your program. Run your program and see that it successfully prints out both choices on one line.

Winners and losers

The only thing left to do is determine the outcome of the game. Before writing any code for this we need to work out how many possible outcomes there are. Both players can make one of three choices, so there are nine possible outcomes for our game.

player      computer    winner
--------------------------------
rock        rock        draw
rock        paper       computer
rock        scissors    player
paper       rock        player
paper       paper       draw
paper       scissors    computer
scissors    rock        computer
scissors    paper       player
scissors    scissors    draw

Once again we can use if statements to work out the correct message to display.

Task

Given the list above, work out how many if statements we will need to check all possible outcomes of the game. Don't write any code just yet, instead see if you can work it out on paper or in your head.

Can we use less than 9 if statements (one for each outcome of the game)?

The first thing to notice is the three draw outcomes can be handled with one condition player_choice == comp_choice. It doesn't matter if the game is rock vs rock, paper vs paper, or scissors vs scissors. What matters is if the choices are the same as each other.

Our first if statement looks like this.

# Determine who won.
if player_choice == comp_choice:
    print("A draw.")

Let's look at winning next. From the table of outcomes we can see three ways the player can win. We will need to check for each of these outcomes separately.

So far our if statements have only checked if one thing equals another, as in some_variable == "this value". However to work out if a player has won the game, we will need to check both the player_choice and comp_choice in one if statement. Its no good just checking the player's choice.

We can check both choice variables in one if statement by using the and operator. and joins two conditions together returning true only when both conditions are true. For example player_choice == 1 and comp_choice == 3 checks if the player chose 1 (rock) and the computer chose 3 (paper). Remember, our choice variables contain the numbers of each choice not the word.

Lets add the three winning conditions to our code for determining the outcome of the game.

# Determine who won.
if player_choice == comp_choice:
    print("A draw.")
elif player_choice == 1 and comp_choice == 3:
    print("Rock blunts scissors. You win!")
elif player_choice == 2 and comp_choice == 1:
    print("Paper wraps rock. You win!")
elif player_choice == 3 and comp_choice == 2:
    print("Scissors cut paper. You win!")

That just leaves the three outcomes where the player loses. However in this case we don't need to check all three possibilities. We have already checked for a draw and winning. This means if none of those conditions have matched, whatever combination of choices is left must be a loss for the player.

In other words, if you didn't draw and you didn't win, you must have lost.

This can be written using the else statement. Our final code for determining the outcome of the game is as follows.

# Determine who won.
if player_choice == comp_choice:
    print("A draw.")
elif player_choice == 1 and comp_choice == 3:
    print("Rock blunts scissors. You win!")
elif player_choice == 2 and comp_choice == 1:
    print("Paper wraps rock. You win!")
elif player_choice == 3 and comp_choice == 2:
    print("Scissors cut paper. You win!")
else:
    print("You lose :(")

It turns out we only needed 5 statements to cover all possible outcomes of the game. Is this how many you thought would be needed? If not, can you see where the code is different to your approach?

Task

Add the final version of the code given above for checking the outcome of the game to the end of your program.

That's it, we have a complete game of Rock, Paper, Scissors written in Python!

Try running your program several times to make sure it works correctly. In particular see if:

  • The message on screen matches the choices made by the player and computer.
  • The program correctly reports the outcome of the game.

Go through the debugging steps outlined earlier if you have any errors. Keep testing and debugging your code until it plays the game correctly.

Reviewing our game

We have a complete game, which is an achievement to appreciate. However programmers are forever on the look out for ways to improve their work, so let's take a step back and cast a critical eye over our program.

Only once

The most obvious limitation of our game is that it only lets you play once. Sure we can run the program again, but it would be nice if we could keep playing. If we did this we might even be able to write a tougher computer opponent, one that remembers each game and makes a choice more likely to beat you, instead of picking numbers at random.

Let's keep a list of all the potential improvements we could make to our game. Programmers often refer to such a list as a backlog. It's common to have more in the backlog than you have time for! Part of being a progrmmer is accepting there is always more that could be done to improve things.

Backlog for Rock, Paper, Scissors

- Feature: Let the game be played more than once, until the player decides to stop.

Invalid input

When playing the game you may have noticed a bug. What happens if you entered a number other than 1, 2, or 3? The input() function just reads the keys entered on the keyboard. It does nothing to validate the input, to make sure it is one of the numbers our program recognises. In fact we could enter a letter, word, or a whole line of text instead of a number. This gives our program a real headache.

Task

Run your program and enter a letter instead of a number when prompted. See the error that Python reports at the bottom of the screen.

Good programs are written to cope with such invalid input. Instead of erroring they gently prompt the user again until a proper choice is made. Let's make our program one of the good ones.

Backlog for Rock, Paper, Scissors

- Feature: Let the game be played more than once, until the player decides to stop.

- Bug: Player can enter an invalid choice, causing an error. Make sure the game only plays when 1, 2, or 3 is chosen.

Improving the code

Finally you may have noticed a lot of the code in our program was to do with mapping between the numbers of the choice variables, and printing out the words rock, paper, and scissors. Here's all of the code we used for that.

if player_choice == 1:
    print("rock", end=" ")
elif player_choice == 2:
    print("paper", end=" ")
else:
    print("scissors", end=" ")

if comp_choice == 1:
    print("vs rock")
elif comp_choice == 2:
    print("vs paper")
else:
    print("vs scissors")

That's nearly half of our program! If the Python library had a function called choice_to_word() that gave us the correct word for each number, we could simplify this code a great deal.

player_word = choice_to_word(player_choice)
comp_word = choice_to_word(comp_choice)
print(player_word, "vs", comp_word)

Python's library doesn't have such a function. However we can write one to do just that. Writing our own functions lets us use the same code in many places in a program without having to write it all again. The less code, the less chance of errors.

Backlog for Rock, Paper, Scissors

- Feature: Let the game be played more than once, until the player decides to stop.

- Bug: Player can enter an invalid choice, causing an error. Make sure the game only plays when 1, 2, or 3 is chosen.

- Feature: Write a function to map the numbers 1, 2, and 3, to the words `rock`, `paper`, and `scissors`.

So that's our backlog. Of the three items it's fair to say the bug should be our first priority. Deciding which of the two features we do next is a bit harder. Playing the game many times is an improvement that players will notice. Whereas writing our own function doesn't change the game, but improves our code. Some programmers prioritise new features, others like to have cleaner code. Either choice is valid.

Personally I would add the function first, then tackle the feature to play the game many times.

Making improvements

The top item on our backlog is to fix the bug caused by an invalid player choice. Let's remind ourselves of the code we use to get the choice.

input_str = input ("1 rock, 2 paper, 3 scissors? ")
player_choice = int(input_str)

We get the input from the keyboard with the first line, and turn it into an integer with the second. The important thing to note is the input() function simply reads whatever is typed on the keyboard until the return key is pressed. Our message prompts for a number from 1 to 3, but the player is free to type in anything.

So what kinds of input could we end up with in our input_str variable?

  • A valid number between 1 and 3.
  • An invalid number, less than 1 or greater than 3.
  • Something that isn't a number at all.

There are two types of bad input we want to avoid here: a number outside the range we want, and something that isn't a number at all. Ideally our program should keep asking the player for their choice until we get something we can use. Let's write out an algorithm that describes this process.

An algorithm for getting the player's choice

  1. Prompt for player input from the keyboard and assign it to input_str.
  2. If input_str is a number, convert it and assign to player_choice as before.
  3. If input_str is not a number, assign zero to player_choice.
  4. Repeat these steps while player_choice is not 1, 2, or 3.

It might not be obvious why we need step three. If something other than a number is added, we know this is invalid input. Setting the player_choice variable to zero makes our check in step four simpler. We only have to check if the number is outside the range we want. (Don't worry, this will make more sense when you see the code.)

To implement this in code we need to know two new things in Python.

  • How to check if a variable refers to a number.
  • How to repeat running some code until a condition is satisfied.

The first can be done with a function called isnumeric(). The second requires us to learn about looping, which is the term programmers use for running some code multiple times.

Asking variables questions

Some variables allow us to call functions on them. Functions called in this way are known as methods. Let's see an example.

my_str = "3"
my_str.isnumeric() # This is True.
my_other_str = "h"
my_other_str.isnumeric() # This is False.

For now it is enough to know that methods exist on some types of variables, and you call them by putting a dot . after the variable name, followed by the method name and it's arguments. Using the isnumeric() method our code for getting the player's choice now looks as follows.

# Get player choice.
player_choice = 0
input_str = input ("1 rock, 2 paper, 3 scissors? ")
if input_str.isnumeric():
    player_choice = int(input_str)

Task

Find the following lines of code in your program, and replace them with the new code given above for getting the player's choice.

# Get player choice.
input_str = input ("1 rock, 2 paper, 3 scissors? ")
player_choice = int(input_str)

Repeating code with while

We are almost finished with our improved way of getting the player's choice. The last piece of the puzzle is for our program to keep asking the player until their choice is a valid one.

Python offers multiple ways to repeat blocks of code. What we would like to say here is "while the player's choice is outside the range 1 to 3, ask them for their input again". The key word here is while, and Python has a while loop that does just what we need.

Using a while loop our code to get the player's choice now looks as follows.

# Get player choice.
player_choice = 0
while player_choice  3:
    input_str = input ("1 rock, 2 paper, 3 scissors? ")
    if input_str.isnumeric():
        player_choice = int(input_str)

Note the new line starting with the word while. This introduces the loop. Immediately afterwards we give two conditions, joined with an or. This code will keep running while the player_choice variable is less than 1 or greater than 3. In other words outside our range of 1 to 3.

Task

Change your program again, this time adding in the line with the while loop on it. Make sure you add it in the correct place, immediately after we set player_choice = 0. Pay attention to the indentation of lines. Note how the lines under the while are indented with a tab, and the line under the if statement is indented with two tabs. This spacing is important to Python.

Writing our own function

Programmers are lazy (in the best possible way) and like to save time and effort where they can. Writing our own functions lets us use the same code in many places in a program, without having to write it all again.

Defining a function is done with def. Here is an example that defines a function called say().

def say():
    print("Inside our own function!")
    print("Time to leave.")

Note that Python does not run the code inside the function until we call it. The def merely defines the function.

We can call this function in the same way we do print() and other built-in ones. Here is part of a program that uses the say() function.

print("Outside the function.")
say()
print("Outside again.")

The above program would output:

Outside the function.
Inside our own function!
Time to leave.
Outside again.

We can also define functions that expect arguments. These act as input to the function, and are assigned to variables only it can use. To write a function like this we need to add variable names to the function definition. We can then use these variables inside the function.

def say(message):
    print("The message is:")
    print(message)

When defining functions in this way, we say that the list of variables given in the definition are the function's parameters. A function defined with parameters must be given arguments for them when called. Let's see that in action in a complete program.

#!/bin/python3

def say(message):
    print("The message is:")
    print(message)

say("hi there!")
say("goodbye...")

If you were to run this program you would see the following output.

The message is:
hi there!
The message is:
goodbye...

Finally we can also return values from a function. This is done with the return statement. Here is a program that defines a function to add two numbers and return the result to the caller.

#!/bin/python3

def add(a, b):
    total = a   b
    return total

print("10   20 =", end=" ")
result = add(10,20)
print(result)
print("5   6 =", end=" ")
result = add(5,6)
print(result)

When run we see the output.

10   20 = 30
5   6 = 11

Writing the choice to word function

Now we know how to write a function that takes input in the form of arguments and returns a result, we can implement our choice_to_word() function. Recall that this function will greatly reduce the code we need in our program to print out the player and computer choices to screen.

Our function will take a single parameter called choice, which is a number from 1 to 3. It will return the word relating to that number in our game as a string (one of Rock, Paper, or Scissors).

# Map the numbers 1,2,3 to the words Rock, Paper, Scissors. 
def choice_to_word(choice):
    if choice == 1:
        word = "Rock"
    elif choice == 2:
        word = "Paper"
    else:
        word = "Scissors"
    return word

Task

Add the definition for the choice_to_word() to your program. Functions must be defined before they are used. Therefore it is good practice to place function definitions at the top of your code. Add the function definition after the comments you wrote outlining our algorithm, and before the line starting import random.

Now we can replace all of this code...

# Show player choice.
if player_choice == 1:
    print("rock", end=" ")
elif player_choice == 2:
    print("paper", end=" ")
else:
    print("scissors", end=" ")
# Show computer choice.
if comp_choice == 1:
    print("vs rock")
elif comp_choice == 2:
    print("vs paper")
else:
    print("vs scissors")

...with these lines.

# Show player and computer choice.
player_word = choice_to_word(player_choice)
comp_word = choice_to_word(comp_choice)
print(player_word, "vs", comp_word)

Task

Delete the old code for printing out the player and computer choices, and replace it with the lines that use our new function. Test your program to see that it still prints out the correct choices for a game. Remember to follow the debugging steps if you have errors.

Play again?

The final task remaining on our backlog is to make the game playable many times. It would be nice if, after a game, we ask the player whether they want to play again. This will require two changes to our program: a prompt to get player input, and another while loop to make the game code keep running.

We have already seen how a while loop can be used to repeat a block of code. If we wrap all our code for playing the game in such a loop, we can play multiple times.

Task

After the line import random in your program, add the following two lines of code. Note the colon : at the end of the second line.

playing = True
while playing:

Task

Indent the start of every line that comes after the while playing: line with an extra tab. Your code should look as follows.

#!/bin/python3

# 1. Make the computer pick a random choice between rock, paper, or scissors.
# 2. Remember the choice in a variable.
# 3. Ask the player to choose either rock, paper, or scissors.
# 4. Remember the choice in a variable.
# 5. Print both choices on screen - for example `rock vs scissors`.
# 6. Compare the two variables to see who has won, or if the game is a draw.
# 7. Print out a message to say if the player won, drew, or lost the game.

# Map the numbers 1,2,3 to the words Rock, Paper, Scissors. 
def choice_to_word(choice):
    if choice == 1:
        word = "Rock"
    elif choice == 2:
        word = "Paper"
    else:
        word = "Scissors"
    return word

import random
playing = True
while playing:
    # Get computer choice.
    comp_choice = random.randint(1,3)
    # ... rest of lines are also indented ...

After we have printed out the message telling the player the outcome of the game, we can use the input() function to ask if they want to play again. Inputting anything other than a y for yes will cause our game loop to stop. We do this by setting the playing variable to False.

# Ask player for another game.
again = input("Play again? ")
if again != "y":
    playing = False

The next time the while loop evaluates it's condition it will be false. Python will run whatever code comes immediately after the block associated with the loop. Let's add a goodbye message to the very end of our program.

# Say goodbye.
print("Thank you for playing!")

Task

Add the code for the play again prompt and goodbye message to your program. Remember that the play again prompt is part of the while loop block, so must be indented. The goodbye message is outside the loop, so doesn't require indentation. Your whole program should look as follows.

#!/bin/python3

# 1. Make the computer pick a random choice between rock, paper, or scissors.
# 2. Remember the choice in a variable.
# 3. Ask the player to choose either rock, paper, or scissors.
# 4. Remember the choice in a variable.
# 5. Print both choices on screen - for example `rock vs scissors`.
# 6. Compare the two variables to see who has won, or if the game is a draw.
# 7. Print out a message to say if the player won, drew, or lost the game.

# Map the numbers 1,2,3 to the words Rock, Paper, Scissors. 
def choice_to_word(choice):
    if choice == 1:
        word = "Rock"
    elif choice == 2:
        word = "Paper"
    else:
        word = "Scissors"
    return word

import random
playing = True
while playing:
  # Get computer choice.
  comp_choice = random.randint(1,3)
  # Get player choice.
  player_choice = 0
  while player_choice  3:
      input_str = input ("1 rock, 2 paper, 3 scissors? ")
      if input_str.isnumeric():
          player_choice = int(input_str)
  # Show player and computer choice.
  player_word = choice_to_word(player_choice)
  comp_word = choice_to_word(comp_choice)
  print(player_word, "vs", comp_word)
  # Determine who won.
  if player_choice == comp_choice:
      print("A draw.")
  elif player_choice == 1 and comp_choice == 3:
      print("Rock blunts scissors. You win!")
  elif player_choice == 2 and comp_choice == 1:
      print("Paper wraps rock. You win!")
  elif player_choice == 3 and comp_choice == 2:
      print("Scissors cut paper. You win!")
  else:
      print("You lose :(")
  # Ask player for another game.
  again = input("Play again? ")
  if again != "y":
      playing = False
# Say goodbye.
print("Thank you for playing!")

That's it! We have tackled all the items on our backlog for improving our game. Our game now handles invalid input from the player and lets us play for as long as we want to. Take some time to study the final code listing and make sure you are happy with how it all works.

A better computer player

Rock, paper, scissors is not a very complex game, but there is still room for a bit of strategy. Playing against another human being we tend to pick up, at least subconsciously, on all sorts of things. Perhaps the other person likes to play rock more often than the other choices. Maybe after they lose a round, they always change the choice they make to something else. As a human being it is unlikely that you would remember all the outcomes of all the games, but you would develop some intuition or gut feeling about how the other person plays.

Sadly our computer player is a little simple in this regard. It just picks a choice at random every time it plays. Can we make it a better player? What if we could make it behave more like a human? Whatever it is that gives us as humans the ability to develop intuition, to have a hunch, or gut feeling about something, whatever that spark is, computers do not have it.

So is random the best we can do for our computer player? As it turns out, no. We can do better. Computers may not have gut feelings like humans, but they excel at remembering things. In fact we can make our computer player remember every choice the human player makes. In the absence of intuition we can use statistics to help the computer make a better choice, and ultimately be a more rewarding opponent.

Retrospective

A retrospective is a term programmers use to mean looking back on the work they have just done. Typically a retrospective is held at the end of a piece of work. The aim is to see what went well, went went wrong, and what new things can be tried next time. We will use our retrospective to review all the Python we have learnt in the previous parts, fill in a few blanks in our knowledge, and give some links to resources for further learning.

What exactly is Python?

Python is an interpreter that sits between us and the computer. The code we write is read one line at a time by Python and turned into instructions the computer can understand. Technically speaking then we do not program the computer, we program Python.

Because Python runs our code in this way, any errors will only be reported when Python tries to read a line it doesn't understand. The following program contains a bug that illustrates this behaviour.

#!/bin/python3

secret_word = "cheeseburger"
guess = input("Guess >")
if guess == secret_word:
    prnt("Correct!")
else:
    print("Incorrect")

The first branch of the if statement contains a typo - prnt instead of print. So if we run this program Python will give us an error right? Maybe.

The line with the error will only run when the condition guess == secret_word is True. So if we run the program and type in something else for our guess, Python will never read the line with the error. It will look like our program is working correctly.

These kinds of bugs can be hard to find, especially when you have a lot of code. The best way to find them is to test each path of execution in your program. The program given above has two paths through it, one when the guess is cheeseburger and one when it is anything else. Running the program multiple times and giving input for both branches would uncover the error.

How much should I know?

The first function we saw was print() and we used it in multiple ways.

print("Hello world!")
print("Hello", name)
print("rock", end=" ")

All of the above are valid ways of calling the print() function. Different functions expect different arguments. A significant part of learning a language is becoming familiar with its functions and how to call them with the correct arguments. (Reading the Python documentation can help with this.)

As we have seen already you can write complete programs knowing very few functions. Python's library is rather large, so don't get hung up trying to learn it all. Most professional programmers only know a small portion of it. It's about learning what you can do with the little you do know. Above all remember to have fun while learning!

Limitations of trinket.io

The trinket website is a fantastic resource for learning Python. It requires no setup on your part and is free. The downside to that is it only has a small subset of the full Python library available. This is unlikely to cause you any issues when learning the basics, the people behind trinket have made the most useful modules of the library available. Just bear in mind that some more advanced Python programs may not work under trinket because of this limitation.

To see a list of the available modules, open up any trinket and click the hamburger menu (three stacked lines) on the left of the code pane. Click the Modules link to see the list.

Further learning

If you want to take your understanding of Python further, now would be a good time to follow up with a more detailed tutorial. Here are some of the most accessible:

  • Official Python tutorial
  • Hour of code
  • How to think like a computer scientist (online book)
  • How to think like a computer scientist (interactive edition)

If you prefer to work on specific project instead of follow a tutorial, the Code Club website has several that are free to use.

  • Module 1
  • Module 2

Once you get a firm grasp of the basics, it helps to have some problems to try and solve. This is a list of some problem sets that can be fun to try and solve in Python:

  • Practice Python
  • Project Rosalind
  • Rosetta code

Hopefully that will help you on your way to Python proficiency!

Заявление о выпуске Эта статья воспроизведена по адресу: https://dev.to/robc79/beginners-guide-to-python-756?1. Если есть какие-либо нарушения, свяжитесь с [email protected], чтобы удалить их.
Последний учебник Более>

Изучайте китайский

Отказ от ответственности: Все предоставленные ресурсы частично взяты из Интернета. В случае нарушения ваших авторских прав или других прав и интересов, пожалуйста, объясните подробные причины и предоставьте доказательства авторских прав или прав и интересов, а затем отправьте их по электронной почте: [email protected]. Мы сделаем это за вас как можно скорее.

Copyright© 2022 湘ICP备2022001581号-3