For a beginner learning python, this will be a very simple and interesting content;
The code is very simple, mainly: random function-a simple and practical that needs to import random modules and conditional statements;
Below, a brief introduction to random functions in python:
random.random() is used to generate a 0 to 1 random decimal number: 0 <= n <1.0
random.random() # Random float x,
The function prototype of andom.uniform is: random.uniform(a, b), which is used to generate a random number of points within a specified range. One of the two parameters is the upper limit and the other is the lower limit. If ab, the generated random number n: a <= n <= b. If a <b, 则 b <= n <= a。
random.uniform(1,10) # Random float x,
The function prototype of andom.randint() is: random.randint(a, b), which is used to generate an integer in the specified range. Among them, the parameter a is the lower limit, and the parameter b is the upper limit. The generated random number n: a <= n <= b
random.randint(10,100)
Of course, there are other usages, you need to explore by yourself!
As for conditional statements, they are more different from other languages in usage;
Code of guessing game:
#! /usr/bin/env python3
# - *- coding:utf-8-*-
u'''
Created on March 7, 2019
@ author: wuluo
'''
__ author__ ='wuluo'
__ version__ ='1.0.0'
__ company__ = u'Chongqing Jiaotong University'
__ updated__ ='2019-03-07'import random
classcaiquan():print('Welcome to the guessing game')print('enter the game--8')print('exit the game--9')
b =input("please enter:")print("Your choice is: ", b)print("\n")while b =='8':print('Please guess the punch:')print('stone--0')print('cloth--1')print('scissors--2')print('exit the game--9')
# If the number entered is not 0,1,2; can be set to re-enter, or set to fail
a = random.randint(0,2)
b =int(input("What you choose is:")) #Integer,
print("The computer chooses:", a)if(a ==0 and b ==1)or(a ==1 and b ==2)or(a == 2and b ==0):print("you win!\n")
elif a == b:print("draw!\n")else:print("you lose!\n")print('Continue the game--8')print('exit the game--9')
b =input("Please select again:")print("Your choice is: ", b +"\n")if __name__ =="__main__":caiquan()print('game over!')
pass
The game can continue to be optimized!
This is mainly to understand the usage of random functions in python, and a simple usage of multi-conditional if statement!
operation result:
In guessing
If the player's choice is not: 0; 1; 2. What I set up is to directly judge the loss!
Of course, it can also be set to one:
The input is wrong! Please re-enter, (multiple calls of if statement)
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts