简体   繁体   English

你如何输入一个字符串然后给它分配一个数字

[英]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.您好,我正在做一些个人 python 学习,我有一个练习问题,我正在努力解决。 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.您应该输入“paper”“rock”或“Scissors”作为用户答案,计算机将随机生成一个 1-3 的数字,对应于特定的选择。 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.如果用户输入 1-3 的数字,我可以让程序正常工作,但这不是问题所要问的。 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.我觉得我已经尝试了所有方法,例如将每个名称分配给相应的数字,创建一个 if then 语句,然后将选择重新分配给数值,但它总是在输入提示后卡住并且不会继续使用代码. I know the issue lies most likely in the line 6 because thats the last spot it executes.. not sure how to fix it.我知道问题很可能出在第 6 行,因为那是它执行的最后一个位置。不知道如何解决它。 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.在 while 循环条件中,您不会将用户的选择与程序的选择进行比较。

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.通过比较user_answernumber来解决此问题。 You also need to specify that user_answer is global in tie .您还需要在tie中指定user_answer是全局的。 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 .在 while 条件下重新计算comp_answer的事实将使得number在传递给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 .您可以通过将tie(number)更改为user_answer = tie(number)并将user_answer作为参数添加到rock_paper_scissors来更改此设置。 The tie function also doesn't use it's argument so it could easily be removed. tie function 也没有使用它的参数,因此很容易将其删除。

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().它只是检查存储的值编号是否等于来自 comp_answer() 的 output。 You might wanna equate "user_input" with "number" to check for the same.您可能想将“user_input”等同于“number”来检查是否相同。 PS the comp_answer() should be called again in tie function PS comp_answer() 应该在 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.试试这个:我已经把打印语句放到一个新的 function 中,这使得程序更容易阅读和更短。

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".但是,请记住,如果用户键入“rock”、“paper”或“scissors”以外的任何内容,您的代码将失败。 I suggest you look into exception handling to get a good grasp and improve on those aspects.我建议您研究异常处理以更好地掌握和改进这些方面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 你怎么问你的字符串中是否有数字? - How do you ask if there is a number in your string? 如何使用输入数字提取 dataframe 中的行? - How do you use an input number to extract rows in a dataframe? 如果您不知道日期输入的格式,如何格式化日期字符串? - How to format a date string if you do not know the format of date input? 如何将变量打印为字符串形式的输入长度? - How do you print a variable as a string for the length of an input? 如何有条件地将值分配给列? - How do you conditionally assign the values to a column? 如何在 pycord 中为用户分配角色? - How do you assign a role to a user in pycord? 由于字符串替换不利于形成 SQL 查询,您如何动态分配表名? - Being that string substitution is frowned upon with forming SQL queries, how do you assign the table name dynamically? 如何将数字转换为与python中输入格式相同的字符串? - How do I convert a number to a string in the same format as the input in python? 您如何让用户输入一个数字并让该数字从列表中提取该数据单元格值? - How do you have a user input a number and have that number pull that data cell value from a list? 你如何限制 python 的 input() 函数的输入参数的数量? - How do you limit the number of input arguments for python's input() function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM