choice() in PythonIn this tutorial, we will discuss the usage of the choice() method in Python. To use this in our program, we need to first import the random module. The function of choice() is to pick or generate a random element that can be anything a number or a string from a given collection. SyntaxThe syntax for using choice() is Let us have a look at some programs that will make it’s application clear. Program 1:Consider the following program- Output: Java Explanation: It’s time to have a look at the explanation of the program given above-
Program 2:In the second program, we will see how it can be used to take a random character from the string. Output: y Explanation: Let’s understand what happened here-
Program 3:Now, let’s have a look at one more program and discuss another approach of writing this method. Output: The random element from(1,2,3,4,5) is 5 The random element from(a,b,c,d,e,f) is f Explanation: Let’s see what we have done in this program-
Program 4:In the next program, we shall see how we can choose a definite number of values to be displayed in the output. Output: [2,2,3,2] Explanation: It’s time to have a look at the explanation of the program given above-
Program 5:Now, we will see how a for loop can be used to meet the same objective. The following program illustrates the same- Output: 1 3 1 3 1 4 Program 6:In the next program, we will see how a random value from a given range of numbers can be taken. Output: A random number from the given range is 31. Explanation: Let’s see what we have done in this program-
Now, we will learn how to get the Boolean values using choice(). Displaying Boolean ResultThe following program shows how we can obtain the Boolean values. Output: The boolean value is False Explanation: It’s time to have a look at the explanation of the program given above-
Program 7:Finally, the last program illustrates how random.getrandbits() can be used for the same purpose. Output: False The procedure of the above program is similar to the previous program, the only difference is here we have used random.getrandbits(). ConclusionIn this tutorial, we learned the different ways of using choice() in our Python program. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263390.html