首页 > 代码库 > 几个简单的语句
几个简单的语句
“#”,写在代码前面表示这段代码注释掉,不运行
“#”,写在代码后面,表示代码的解释
""" """ 可以注释多行
input接受的所有数据都是字符串(str),即使输入的是数字,但依然会被当成字符串处理
int integer=整数 把字符串转成int
str string=字符串
字符串和整数不能拼接需转换类型
if elif else
3个数字比较最大值
num1=int(input("Num1:"))
num2=int(input("Num2:"))
num3=int(input("Num3:"))
max_num=0
if num1>num2:
max_num=num1
if max_num>num3:
print("MAX NUM is","num1")
else:
print("MAX NUM is","num3")
else:
max_num=num2
if max_num>num3:
print("MAX NUM is", "num2")
else:
print("MAX NUM is","num3")
While循环
输出1--100的偶数
num = 1
while num<100:
if num % 2 == 0:
print(num)
num +=1 #注意循环的层次
猜年龄,age=50
if input_age == age:
print("yes")
elif input_age < age:
print("smaller")
else:
print("bigger")
print("end")
缺点:只进行一次猜测,不能多次猜测,改进版:使用while语句
age = 50
#input_age = int(input("Age is:"))
flag = True
while flag:# 当 flag= True时,执行下面的if else循环语句
input_age = int(input("Age is:")) #如果这句话写在前面,则会陷入无限循环
if input_age == age:
print("yes")
flag = False #当 用户输入等于50时,flag是false,不在执行whlie循环,end(或
者该句可换成break,终止循环)
elif input_age < age:
print("smaller")
else:
print("bigger")
print("end")
break: 终止循环
continue: 跳出当次循环
区别如:
num = 1
while num <=10:
num +=1
if num == 3:
break
print(num)
输出结果: 2
num = 1
while num <=10:
num +=1
if num == 3:
continue
print(num)
输出结果 2 4567891011
while:
……
else:
……
当while语句执行过程中如果执行了break,则else不会被执行,如果执行了continue,则会执行else
num = 1
while num <=10:
num +=1
if num == 3:
continue
print(num)
else:
print("Else test")
输出结果: 2 4 5 6 7 8 9 10 11 Else test
num = 1
while num <=10:
num +=1
if num == 3:
break
print(num)
else:
print("Else test")
输出结果: 2
命令: end=" " 不换行
print()#等价于 print(end = "\n") 换行
height 高度
weidth 宽度
输出固定的长款字符
height = int(input("H is:"))
width = int(input("W is:"))
num_height = 1
while num_height <= height:
num_width = 1
while num_width <= width: (注意使用嵌套循环)
print("#", end=(""))
num_width +=1
print()
num_height +=1
嵌套循环: 输出类似三角的图案
*
**
***
……
line = 5
flag = 1
while line > 0:
num = flag
while num - 1>=0:
print("*",end=(""))
num -=1
print()
flag +=1
line -=1
改进版:少用一个变量
line = 1
while line <=5:
num = line
while num >0:
print("*",end=(""))
num -=1
print()
line +=1
99乘法表
方法一:
num = 1
while num<= 9:
first = 1
secoend = num
while first <= secoend:
production = secoend * first
print(str(secoend) + "*" + str(first) + "=" +str(production), end=(" "))
first +=1
print()
num +=1
简化: 可以不用first变量
num = 1
while num<= 9:
first = 1
while first <= num:
production = num * first
print(str(num) + "*" + str(first) + "=" +str(production), end=(" "))
first +=1
print()
num +=1
几个简单的语句