5

条件控制语句以及案例

 3 years ago
source link: https://blog.csdn.net/h123456789999999/article/details/113177488
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

条件控制语句以及案例

红糖番薯 2021-01-26 12:44:31 925
文章标签: python
  • if语句的基本用法
if 表达式:
      语句块

表达式中可以是一个单纯的布尔值或者变量,也可以是比较表达式或逻辑表达式(例如:a>b and a!=c),如果表达式为真,则执行语句块:如果表达式为假,就跳过语句块,继续执行后面的语句。

a=1
b=2
if(a<b)
   print(a+b)

and表示并且or表示或者
if…else 语句的基本用法如下:

if 表达式: 
	 语句块 1 
else: 
	语句块 2

使用 if…else 语句时,表达式可以是一个单纯的布尔值或变量,也可以是比较表达式或 逻辑表达式,如果满足条件,则执行 if 后面的语句块,否则,执行 else 后面的语句块。在 使用 else 语句时,else 一定不可以单独使用,它必须和保留字 if 一起使用。
if…elif…else语句

  • if…elif…else 语句的基本用法如下:
if 表达式 1: 
	语句块 1 
elif表达式 2: 
	语句块 2 
elif表达式 3: 
	语句块 3
else: 
	语句块 n 

使用 if…elif…else 语句时,表达式可以是一个单纯的布尔值或变量,也可以是比较表达 式或逻辑表达式,如果表达式为真,执行语句;而如果表达式为假,则跳过该语句,进行下 一个 elif 的判断,只有在所有表达式都为假的情况下,才会执行 else 中的语句。
While 循环

while循环,只要条件为真,会一直执行。
示例
只要i小于10,打印i:

i = 1
while i < 10:
  print(i)
  i += 1

注意: 记住增加i,否则循环将永远执行。

接下来是示例代码

  • 第一个游戏石头剪子布,这个是if elif else 的示范代码
import random
print('请输入石头剪子布')
print('石头为0 剪子为1 布为2')
user=int(input('enter: '))
computer=random.randint(0,2)
if(user == 0 and computer == 0):
	print("平局")
elif(user == 0 and computer == 1):
	print("人获胜")
elif(user == 0 and computer == 2):
	print("计算机获胜")
elif(user == 1 and computer == 0):
	print("计算机获胜")
elif(user == 1 and computer == 1):
	print("平局")
elif(user == 1 and computer == 2):
	print("人获胜")
elif(user == 2 and computer == 0):
	print("人获胜")
elif(user == 2 and computer == 1):
	print("计算机获胜")
elif(user == 2 and computer == 2):
	print("平局")

a=int(input('enter:'))
for i in range(2,a):
    if a%i==0:
        print('不是质数')
        break
    else:
        print('a是质数')
        break

一定要加break否则输进去大的数字会一直循环

  • 输出1000以内的水仙花数
i = 100
a = 0 
b = 0 
c = 0 
number =0
print('1000的以内水仙花数:')
while i < 1000:
    a = i //100  
    b = (i - a *100 ) // 10 
    c = (i % 10)  
    if i == a ** 3 + b ** 3 + c ** 3 :
        print(i) 
    i += 1

如果觉得写的不错给个关注球球了!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK