You might also like this article on python trees. To learn more about Python programming, you can read this article on rolling the dice game in Python. In this article, we discussed three ways to implement the magic 8-ball game in Python. When the user asks for an answer, we directly select a random answer from the list using the choice() function and print it. In this example, we have stored all the possible answers in a list. import randomĪsk the magic 8 ball a question: (press enter to quit) PFB is greatĪsk the magic 8 ball a question: (press enter to quit) PFB is awesome.Īsk the magic 8 ball a question: (press enter to quit) PFB is good. After this, whenever the user asks a question, we will select a value from the list using the choice function and print it as shown in the following example. To implement the game, we will put all 20 answers in a list. The choice() function takes a list as its input argument and returns a random element from the list. Instead of the randint() function, we can also use the choice() function defined in the random module to implement the magic 8-ball game. As we have already defined the dictionary with numbers as keys and the possible answers as their values, we use the indexing operator to get the string value associated with the random number and print it. In this example, we first generate a random number between 1 to 20 using the randint() function to predict the answer. Output: Ask the magic 8 ball a question: (press enter to quit) Python is awesome. For this, we will use the numbers as the keys and the answers for each number as the corresponding values.Īfter predicting a number using the randint() method, we can get the answer from the dictionary and print it as shown below. Hence, we can use a Python dictionary to imitate the functionality of the if-else blocks. You can observe that the if-else blocks made the code redundantly large. In the above code, we have used 20 if-else blocks to implement the answers. Output: Ask the magic 8 ball a question: (press enter to quit) Python is awesomeĪsk the magic 8 ball a question: (press enter to quit) PFB is great.Īsk the magic 8 ball a question: (press enter to quit) Question=input("Ask the magic 8 ball a question: (press enter to quit) ") You can observe the above process in the following example. If the user doesn’t input any questions, we will terminate the loop using the break statement.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |