Results 1 to 10 of 10

Thread: Dictionaries and the formatting function: Python basics

Threaded View

  1. #1
    Join Date
    May 2007
    Location
    West Indies
    Beans
    497
    Distro
    Ubuntu

    Dictionaries and the formatting function: Python basics

    Take a look at the python script (code copied at the end of this post). I got it from a learn-to-program magazine. The rock-paper-scissors game code is intended to teach basic python programming.

    I can follow along line by line in the script and mostly understand what is going on. The two areas which I don’t really understand are lines 40 and 76.

    At line 39, the names variable creates a dictionary distinguishing the previously declared variable “rock” to be printed as the string “Rock”. Same is true for paper and scissors. I think I understand that much. But in the next line, line 40, the rules variable is declared as a dictionary containing rock: scissors, paper: rock, scissors: paper. Here I’m confused. What is happening at this line? I understand the relationship at least. Like, I get that rock beats scissors, paper beats rock, scissors beats paper. Those are the rules. But how does the colon bind that relationship of ‘beat’ between the three sets of two corresponding variables?

    The documentation found in the magazine explaining lines 39 and 40 read:
    Here we specify the rules for the game, and the text representations of each move for the rest of the code. When called upon, our script will print the names of any of the three moves, mainly to tell the player how the computer moved. These names are only equated to these variables when they are needed – this way, the number assigned to each of them is maintained while it’s needed.
    I get the first sentence there. But the final sentence escapes me. Can anyone shed some light here or lend a helping hand? How would you explain what is happening on line 40?

    With respect to the other line which I don’t understand, it's line 76, which reads:

    Code:
     print "Computer threw {0}!".format(names[computer])
    It’s a string printed with a variable which will change every time you run the script, indicated by the {0}. What is the formatting function doing? I Google ‘format function python’ which turned up the official python doc on the subject. It reads:

    Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces*{}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.
    ...which completely escapes me as well. Any thoughts?

    Thanks for your attention.

    I kept the line numbers in the code sample below to enhance readability here on this forum. Attached is the raw code so you can try it out yourself if you are so inclined.

    Code:
      1 # !/usr/bin/env python2
      2 
      3 '''
      4 
      5 Rock, Scissors, Paper: The Video Game
      6 
      7 Copyright (c) 2015 Linux User & Developer
      8 
      9 Permission is hereby granted, free of charge, to any person obtaining a copy
     10 of this software and associated documentation files (the "Software"), to deal
     11 in the Software without restriction, including without limitation the rights
     12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     13 copies of the Software, and to permit persons to whom the Software is
     14 furnished to do so, subject to the following conditions:
     15 
     16 The above copyright notice and this permission notice shall be included in
     17 all copies or substantial portions of the Software.
     18 
     19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     22 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     24 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
     25 SOFTWARE.
     26 
     27 '''
     28 
     29 import pdb
     30 import random
     31 import time
     32 
     33 # initiation of variables
     34 
     35 rock = 1
     36 paper = 2
     37 scissors = 3
     38 
     39 names = { rock: "Rock", paper: "Paper", scissors: "Scissors" }
     40 rules = { rock: scissors, paper: rock, scissors: paper }
     41 
     42 player_score = 0
     43 computer_score = 0
     44 
     45 def start():
     46         print " "
     47         print "Whaddya say, lets play a game of Rock, Paper, Scissors, shall we?"
     48         while game():
     49                 pass
     50         scores()
     51 
     52 def game():
     53         player = move()
     54         computer = random.randint(1,3)
     55         result(player, computer)
     56         return play_again()
     57 
     58                 print " "  #"[placeholder]"
     59                 player = raw_input("Rock = 1 \nPaper = 2 \nScissors = 3\nChoose a hand >>    ")
     60                 print " "  #"[placeholder]"
     61                 try:
     62                         player = int(player)
     63                         if player in (1,2,3):
     64                                 return player
     65                 except ValueError:
     66                         pass
     67                 print "Ooops! I didn't understand that. Please enter 1, 2 or 3."
     68 
     69 def result(player, computer):
     70         print "Sea..."
     71         time.sleep(0.75)
     72         print "Sum..."
     73         time.sleep(0.75)
     74         print "Sue..."
     75         time.sleep(0.25)
     76         print "Computer threw {0}!".format(names[computer])
     77         global player_score, computer_score
     78         print " "  #"[placeholder]"
     79         if player == computer:
     80                 print "Tie Game"
     81         else:
     82                 if rules[player] == computer:
     83                         print "Your victory has been assured"
     84                         player_score += 1
     85                 else:
     86                         print "The player laughs as you realize you've been defeated"
     87                         computer_score += 1
     88 
     89 def play_again():
     90         answer = raw_input("Would you like to play again? >>    ")
     91         if answer in ("y", "yes", "Yes", "Y", "Of Course"):
     92                 return start()
     93         elif answer in ("n", "no", "No", "N", "Nope"):
     94                 print "Thank you for playing our game. See you next time!"
     95                 return scores()
     96         else:
     97                 print "I didn't quite get that.  Please try again."
     98                 return play_again()
     99 
    100 def scores():
    101         global player_score, computer_score
    102         print "HIGH SCORES"
    103         print "Player: ", player_score
    104         print "Computer: ", computer_score
    105 
    106 if __name__ == '__main__':
    107         start()
    Attached Files Attached Files
    Last edited by Drone4four; August 8th, 2017 at 02:34 AM. Reason: added questions, thanks
    My rig:
    IBM Personal System/2 Model 30-286 - - Intel 80286 (16 bit) 10 Mhz - - 1MB DRAM - - Integrated VGA Display adapter
    1.44MB capacity Floppy Disk - - PS/2 keyboard (no mouse)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •