python basics 5 - generating random numbers

random number

  • In Python, to use random numbers, you first need to import the random number module - "toolkit"
import random

  

  • After importing the module, you can directly type a name after the module name. Then press the Tab key, it will prompt all functions contained in the module
  • random.randint(a, b) , returns an integer between [a, b], including a and b
  • E.g:
1 random.randint(12, 20) #Generated   random number n: 12 <= n <= 20    
2 random.randint(20, 20)   #The result is always 20    
3 random.randint(20, 10) #The   statement is false, the lower bound must be less than the upper bound

case

#Enter the punch to be punched from the console - rock (1) / scissors (2) / cloth (3) 
player = int(input( " Please punch rock (1) / scissors (2) / cloth (3): " ))

#Computer randomly throws punches - assuming the computer always throws stones 
computer =random.randint(1, 3)

#Compare wins and losses 
# If the content of the conditional judgment is too long, you can add a pair of braces to the outermost condition 
# Then between each condition, use Enter, PyCharm can automatically add 8 spaces 
if ((player == 1 and computer == 2) or 
        (player == 2 and computer == 3) or 
        (player == 3 and computer == 1 )):

    print ( " Oh yeah!!! The computer is weak!!! " )
 elif player == computer:
     print ( " I have a good heart, let's have another game! " )
 else :
     print ( " No, I will fight with you until dawn! " )

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325215263&siteId=291194637