Python の randint() 関数
日付() の組み込み関数です ランダムモジュール Python3では。ランダム モジュールを使用すると、さまざまな便利な関数にアクセスできます。そのうちの 1 つは乱数を生成する機能です。 日付() 。この記事では、randint について学びます。 パイソン 。
Python randint() メソッドの構文
構文 : randint(開始、終了)
パラメーター :
(始まりと終わり) : どちらも整数型の値である必要があります。
戻り値 :
終点を含む範囲 [開始、終了] 内のランダムな整数。
エラーと例外:
値エラー: 浮動小数点値がパラメータとして渡されると、ValueError を返します。
タイプエラー: 数値以外の値がパラメータとして渡された場合は、TypeError を返します。
Python の randint() はどのように機能するのでしょうか?
この例では、Python の randint() メソッドを使用して、指定された範囲内の乱数を見つけます。
Python3
# Python3 program explaining work> # of randint() function> # imports random module> import> random> # Generates a random number between> # a given positive range> r1> => random.randint(> 0> ,> 10> )> print> (> 'Random number between 0 and 10 is % s'> %> (r1))> # Generates a random number between> # two given negative range> r2> => random.randint(> -> 10> ,> -> 1> )> print> (> 'Random number between -10 and -1 is % d'> %> (r2))> # Generates a random number between> # a positive and a negative range> r3> => random.randint(> -> 5> ,> 5> )> print> (> 'Random number between -5 and 5 is % d'> %> (r3))> |
出力
Random number between 0 and 10 is 2 Random number between -10 and -1 is -7 Random number between -5 and 5 is -3
randint() メソッドの例
複数の Randint Python メソッド呼び出し
この例では、Python で複数のrandom.randint() メソッド呼び出しを行っています。
Python3
import> random> beg,end> => 1> ,> 1000> for> i> in> range> (> 5> ):> > print> (random.randint(beg, end))> |
出力
94 550 236 145 747
ValueError をデモするプログラム
この例では、randint() 関数のパラメータとして浮動小数点値を渡すと、ValueError が発生することがわかります。
Python3
# imports random module> import> random> '''If we pass floating point values as> parameters in the randint() function'''> r1> => random.randint(> 1.23> ,> 9.34> )> print> (r1)> |
出力:
Traceback (most recent call last): File '/home/f813370b9ea61dd5d55d7dadc8ed5171.py', line 6, in r1=random.randint(1.23, 9.34) File '/usr/lib/python3.5/random.py', line 218, in randint return self.randrange(a, b+1) File '/usr/lib/python3.5/random.py', line 182, in randrange raise ValueError('non-integer arg 1 for randrange()') ValueError: non-integer arg 1 for randrange() TypeError をデモするプログラム
この例では、randint() 関数のパラメーターとして文字列または文字リテラルを渡すと、TypeError が発生することがわかります。
Python3
# imports random> import> random> '''If we pass string or character literals as> parameters in the randint() function'''> r2> => random.randint(> 'a'> ,> 'z'> )> print> (r2)> |
出力:
Traceback (most recent call last): File '/home/fb805b21fea0e29c6a65f62b99998953.py', line 5, in r2=random.randint('a', 'z') File '/usr/lib/python3.5/random.py', line 218, in randint return self.randrange(a, b+1) TypeError: Can't convert 'int' object to str implicitly アプリケーション: randint() 関数を使用すると、抽選の状況をシミュレートできます。ユーザーが抽選会に参加したとします。ユーザーには、1 から 10 までの数字を推測するチャンスが 3 回与えられます。推測が正しければユーザーが勝ち、そうでなければ競争に負けます。
Python3
# importing randint function> # from random module> from> random> import> randint> # Function which generates a new> # random number everytime it executes> def> generator():> > return> randint(> 1> ,> 10> )> > # Function takes user input and returns> # true or false depending whether the> # user wins the lucky draw!> def> rand_guess():> > # calls generator() which returns a> > # random integer between 1 and 10> > random_number> => generator()> > > # defining the number of> > # guesses the user gets> > guess_left> => 3> > # Setting a flag variable to check> > # the win-condition for user> > flag> => 0> > # looping the number of times> > # the user gets chances> > while> guess_left>>> 0> :> > # Taking a input from the user> > guess> => int> (> input> (> 'Pick your number to '> > 'enter the lucky draw
'> ))> > # checking whether user's guess> > # matches the generated win-condition> > if> guess> => => random_number:> > # setting flag as 1 if user guesses> > # correctly and then loop is broken> > flag> => 1> > break> > > else> :> > > # If user's choice doesn't match> > # win-condition then it is printed> > print> (> 'Wrong Guess!!'> )> > # Decrementing number of> > # guesses left by 1> > guess_left> -> => 1> > # If win-condition is satisfied then,> > # the function rand_guess returns True> > if> flag> is> 1> :> > return> True> > # Else the function returns False> > else> :> > return> False> # Driver code> if> __name__> => => '__main__'> :> > if> rand_guess()> is> True> :> > print> (> 'Congrats!! You Win.'> )> > else> :> > print> (> 'Sorry, You Lost!'> )> |
出力
Pick your number to enter the lucky draw 8 Wrong Guess!! Pick your number to enter the lucky draw 9 Wrong Guess!! Pick your number to enter the lucky draw 0 Congrats!! You Win.