PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] How to convert a text string in an input function into an integer?

 July 21, 2022     input, integer, python     No comments   

Issue

I am trying to write a very simple programme for a rock, paper, scissors game. I produce a random integer which is the opponent's move, and then I input my own "guess" in integer form. Then, I combine these two integers into a list and test these coordinates against a results matrix.

I have converted "rock", "paper" and "scissors" into integers as follows:

    guess = input("Enter your move: \"rock\", \"paper\", \"scissors\", or \"quit\": \n")
    if guess == "rock":
        guess = 0
    if guess == "paper":
        guess = 1
    if guess == "scissors":
        guess = 2
    if guess == "quit":
        break
    weapon = random.randint(0, 2)  # 0 is rock, 1 is paper, 2 is scissors
    outputGuess = (int(guess), int(weapon))

Is there a way to get rid of all the if statements? I have tried the following, but it does not work:

    guess = input("Enter your move: \"rock\", \"paper\", \"scissors\", or \"quit\": \n")
    "rock" = 0
    "paper" = 1
    "scissors" = 2
    weapon = random.randint(0, 2)  # 0 is rock, 1 is paper, 2 is scissors
    outputGuess = (int(guess), int(weapon))

Thank you!


Solution

You could use a dict to translate it into its integer counterpart.

guess = input("Enter your move: \"rock\", \"paper\", \"scissors\", or \"quit\": \n")

guesses = {'rock':0, 'paper':1, 'scissors':2}
weapon = random.randint(0, 2)
output = (guesses[guess], weapon)

You don't need to change the type of the weapon since it is already an integer.



Answered By - Austin
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing