Home > Backend Development > Python Tutorial > Python中random模块用法实例分析

Python中random模块用法实例分析

WBOY
Release: 2016-06-06 11:16:50
Original
1586 people have browsed it

本文实例讲述了Python中random模块用法。分享给大家供大家参考。具体如下:

import random
x = random.randint(1,4);
y = random.choice(['appale','banana','cherry','durian']);
print(x,y);

Copy after login

运行结果如下:
(2, 'cherry')

不管学哪个语言,我总喜欢弄个随机数玩玩。农历十一月初六,Let's Python!!!

l=[ ]
while True:
  name=input("请输入一个名字:")
  if name!='':
    l.append(name)
  else:
    break
print(l);

Copy after login

'''求1到100直接所有整数的和'''
x=range(1,101,1)
sumi=0
for i in x:
  sumi+=i
print(sumi)

Copy after login

运行结果如下:
5050

u1='''求阶乘的一般方法'''
print(u1)
def jc(n):
  s=1
  for i in range(1,n+1):
    s*=i
  return s
n = input("n! usage:<number>:")
h = jc(int(n))
print(h)

Copy after login

运行结果如下:

求阶乘的一般方法
n! usage:<number>:5
120

Copy after login

u2='''通过递归实现阶乘'''
print(u2)
def jch(n):
  if(n==1):
    return 1
  else:
    return n*jch(n-1)
un=input("input n:")
s=jch(int(un))
print("n! is ",s)

Copy after login

运行结果如下:

通过递归实现阶乘
input n:5
('n! is ', 120)

Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template