0
Turning a letter input into integer
Hello; I've been trying to make a very simple rock, paper, scissors game and to get the user's choice and convert it to a number, I did this: r=1 p=2 s=3 user=int(input("r, p or s?") And I realized that's impossible to do. So while it's important for me to have the user input a letter rather than a number, how can I convert it? *Update!* I've managed to make it work using a bunch of ifs, but is there any other more efficient ways of doing this? Here's the new code: user=input("R, P or S?") if user=="r": user=1 elif user=="p": user=2 elif user=="s": user=3
3 Respuestas
+ 2
You could just keep the char value.
if(user == 'r')
// chose rock
else if (user == 'p')
// chose paper
else
// chose scissors
I'm not sure what you found "impossible to do", you did it in your example.
+ 2
In regards to your update.
You may be able to use a dictionary.
Where you make r the key for 1.
p the key for 2.
etc..
I don't use python though, so I'm not sure how the syntax is.
Tutorial:
https://www.tutorialspoint.com/python/python_dictionary.htm
Once you have the dictionary you can use the input directly to set the value of the 'user' variable.
+ 1
What I was finding impossible to do, was making Python switch between two sides of an equation. If r is 1 then I thought it had to consider the integer value of r to be 1 and use it when it was told to.
It seems to me like the dictionary kinda makes sense but I started learning programming like yesterday and it's going to take me some time to figure out how to use the dictionary. Thank you for sharing. :)