날짜() 의 내장 기능입니다 무작위 모듈 Python3에서. 무작위 모듈은 난수를 생성할 수 있는 다양한 유용한 기능에 대한 액세스를 제공합니다. 날짜() . 이번 글에서는 randint에 대해 알아보겠습니다. 파이썬 .
Python randint() 메서드 구문
통사론 : randint(시작, 끝)
매개변수:
(시작, 끝) : 둘 다 정수 유형 값이어야 합니다.
반품 :
안드로이드에서 유튜브 광고 차단하기끝점을 포함하는 [시작, 끝] 범위의 임의의 정수입니다.
오류 및 예외:
값오류: 부동 소수점 값이 매개변수로 전달되면 ValueError를 반환합니다.
유형오류: 숫자 값 이외의 값이 매개변수로 전달되면 TypeError를 반환합니다.
Python의 randint()는 어떻게 작동하나요?
이 예에서는 Python의 randint() 메서드를 사용하여 주어진 범위에서 난수를 찾습니다.
파이썬3
# 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() 메서드를 여러 번 호출합니다.
파이썬3
선택 정렬 자바
import> random> beg,end>=>1>,>1000> for> i>in> range>(>5>):> >print>(random.randint(beg, end))> |
카잘 아가르왈
>
>산출
94 550 236 145 747>
ValueError를 보여주는 프로그램
이 예에서는 부동 소수점 값을 randint() 함수의 매개 변수로 전달하면 ValueError가 발생하는 것을 볼 수 있습니다.
파이썬3
# 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가 발생하는 것을 볼 수 있습니다.
파이썬3
내 모니터 화면 크기는 얼마야
# 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
jframe
# 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.>