简体   繁体   中英

How do you input a string then assign a number to it

Hello i'm doing some personal python learning and i have a practice problem i'm trying to figure out. The main goal is to play paper rock scissors with the computer. Your supposed to input "paper" "rock" or "Scissors" as a user answer and the computer will randomly generate a number from 1-3 that corresponds to a particular choice. I can get the program to work fine if the user inputs a number from 1-3 but that's not what the question asks. I feel like i've tried everything like assigning each name to the corresponding number, creating an if then statement that then reassigns the choice to the numerical value but it always just gets stuck after the input prompt and doesn't move forward with the code. I know the issue lies most likely in the line 6 because thats the last spot it executes.. not sure how to fix it. Also if anyone can give me some pointers on how this could look a little cleaner or if this is roughly what is should look like in terms of efficiency and cleanliness. Keep in mind i have not learned anything too advanced like dictionaries lists ect. Problem should be solved using basic stuff for now. Thank you!

import random

def main():
    global user_answer
    print('lets play paper rock scissors')
    number = comp_answer()
    user_answer = int(input('What do you choose?')) <--- # i know the change would be 
    while number = comp_answer():                        # here.... maybe str(input(' ')) 
        tie(number)                                      # then define the choices? tried 
    paper_rock_scissors(number)                          # that and failed not sure if i'm 
                                                         # doing it wrong.

def comp_answer():
    number = random.randint(1,4)
    return number

def tie(number):
    print("its a tie!")
    print ("tie breaker")
    user_answer = input('What do you choose?')

def paper_rock_scissors(number):

    if number == 3 and user_answer == 1:
        print("computer: scissors")
        print("you: ",user_answer )
        print("you won!")
        print("rocks smashes scissors")

    elif number == 3 and user_answer == 2:
        print("computer: scissors")
        print("you: ",user_answer )
        print("Game over")
        print("scissors cuts paper")

    elif number == 1 and user_answer == 3:
        print("computer: rock")
        print("you: ",user_answer )
        print("Game over")
        print("rocks smashes scissors")
    elif number == 2 and user_answer == 3:
        print("computer: paper")
        print("you: ",user_answer )
        print("you won!")
        print("scissors cuts paper")

    elif number == 1 and user_answer == 2:
        print("computer: rock")
        print("you: ",user_answer )
        print("you won!")
        print("paper covers rock")
    elif user_answer == 1 and number == 2:
        print("computer: paper")
        print("you: ",user_answer )
        print("Game over")
        print("paper covers rock")
main()

In the while loop condition you don't compare the user's choice to the program's.

def main():
    global user_answer
    print('lets play paper rock scissors')
    number = comp_answer()
    user_answer = int(input('What do you choose?'))
    while user_answer == number:
        tie(number)
        number = comp_answer()
    paper_rock_scissors(number)

Fix this by comparing user_answer and number instead. You also need to specify that user_answer is global in tie . The fact that comp_answer is recomputed in the while condition will make it so that number has the incorrect value when passed to rock_paper_scissors . Those Three changes should fix the issue.

As for cleanliness, global variables are generally bad practice. You could change this by changing tie(number) to user_answer = tie(number) and adding user_answer as an argument to rock_paper_scissors . The tie function also doesn't use it's argument so it could easily be removed.

The problem in your program lies in

"while number = comp_answer():"

It should be a "==" for comparison. "=" is used for assignment and what we need here is an equal to evaluation. Also,

while number == comp_answer(): 

doesn't really equate to a tie. It just checks whether the stored value number is equal to the output from comp_answer(). You might wanna equate "user_input" with "number" to check for the same. PS the comp_answer() should be called again in tie function

Try this: I've put the print statements to a new function that makes the program a big easier to read and shorter.

import random

def main():
    global user_answer
    print('lets play paper rock scissors')
    number = comp_answer()
    user_answer = int(input('What do you choose?'))  
    while number == user_answer:                        
        tie()                                       
    paper_rock_scissors(number)                          

def comp_answer():
    number = random.randint(1,4)
    return number

def tie():
    global number
    print("its a tie!")
    print ("tie breaker")
    number = comp_answer()
    user_answer = input('What do you choose?')

def print_ans(computer, user, explanation, win):
    print("computer: ", computer)
    print("you: ", user)
    print(explanation)
    if win:
        print("you won!")
    else:
        print("Game over")

def paper_rock_scissors(number):
    if number == 3:
        if user_answer == 1:
            print_ans("scissors", "rock", "rocks smashes scissors", win=True)
        else:
            print_ans("scissors", "paper", "scissors cut paper", win=False)
    elif number == 1:
        if user_answer == 3:
            print_ans("rock", "scissors", "rocks smashes scissors", win=False)
        else:
            print_ans("rock", "paper", "paper covers rock", win=True)
    else:
        if user_answer == 1:
            print_ans("paper", "rock", "paper covers rock", win=False)
        else:
            print_ans("paper", "scissors", "scissors cut paper", win=True)


main()

If you want the user to input string instead of integers, the code will look somewhat like this (mind you I will be using dictionaries as it makes things easier and I think it is important for everyone to know about them, so read up a bit on them):

import random

num_mappings = {"rock":1 , "paper":2 , "scissors":3}

def main():
    global user_answer
    print('lets play paper rock scissors')
    number = comp_answer()
    user = input('What do you choose?') 
    user_answer = num_mappings[user] 
    while number == user_answer:                        
        tie()                                       
    paper_rock_scissors(number)                          

def comp_answer():
    number = random.randint(1,4)
    return number

def tie():
    global number
    print("its a tie!")
    print ("tie breaker")
    number = comp_answer()
    user = input('What do you choose?') 
    user_answer = num_mappings[user]

def print_ans(computer, user, explanation, win):
    print("computer: ", computer)
    print("you: ", user)
    print(explanation)
    if win:
        print("you won!")
    else:
        print("Game over")

def paper_rock_scissors(number):
    if number == 3:
        if user_answer == 1:
            print_ans("scissors", "rock", "rocks smashes scissors", win=True)
        else:
            print_ans("scissors", "paper", "scissors cut paper", win=False)
    elif number == 1:
        if user_answer == 3:
            print_ans("rock", "scissors", "rocks smashes scissors", win=False)
        else:
            print_ans("rock", "paper", "paper covers rock", win=True)
    else:
        if user_answer == 1:
            print_ans("paper", "rock", "paper covers rock", win=False)
        else:
            print_ans("paper", "scissors", "scissors cut paper", win=True)


main()

However, keep in mind, your code will fail if the user types anything other than "rock", "paper" or "scissors". I suggest you look into exception handling to get a good grasp and improve on those aspects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM