首页 > 编程语言 > 详细

Python3条件判断

时间:2019-08-26 18:45:32      阅读:141      评论:0      收藏:0      [点我收藏+]

if语句:

Python中if语句的一般形式如下:

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

if语句关键词: if – elif – else

注意:

  1. 每个条件后面要使用冒号:
  2. 使用缩进来划分语句块,相同缩进的语句在一起组成一个语句块
  3. 在Python中没有switch-case语句

 

实例:x为0-99取一个数,y为0-199取一个数,若x>y则输出x,x等于y,输出x+y,否则输出y

#if.py
import random

x = random.choice(range(100))
y = random.choice(range(200))

if x > y:
    print(x :, x)
elif x == y:
    print(x + y : ,x+y)
else:
    print(y : , y)

choice函数

choice()方法返回一个列表,元组,或字符串的随机数

它不能直接访问,需要导入random模块,通过random静态对象调用该方法。

#choice.py
import random
print ("choice[(1,2,3,4,5,9)] : ",random.choice([1,2,3,4,5,9]))
print ("choice (‘A String‘) : ",random.choice(A String))

如果if语句中的条件太长,可以使用接续符\l 来换行

Python3条件判断

原文:https://www.cnblogs.com/wanghao-boke/p/11414062.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!