条件分支语句: if +条件 :
条件为真(true)执行的操作
else:
条件为假执行的操作。
temp = input('please input a number:')
guess = int(temp)
if guess == 8:
print('you are right!')
else:
print('you are wrong!')
print('game over!')
[如上图代码所示]
while循环:
while + 条件:
条件为真(true)的执行操作
temp = input('please input a number:')
guess = int(temp)
if guess == 8:
print('you are right')
while guess != 8:
temp = input('please input a number again:')
guess = int(temp)
if guess == 8:
print('right')
else:
if guess > 8:
print('too big!')
else:
print('too small!')
print('game over!')
and 操作符:将任意表达式连接在一起,得到一个布尔类型的值(true/false)
引入外援:random模块
random.randint() 返回一个随机数值(整数)
import random
secret = random.randint(1,10)
temp = input("please input a number:")
guess = int(temp)
if guess == secret:
print("true!")
while guess != secret:
temp = input("please input a number again:")
guess = int(temp)
if guess == secret:
print("ture!")
else:
if guess > secret:
print("too bigger!")
else:
print("too small!")
print("game over!")
类型转换:浮点(float)、整数(int)、字符串(str)之间的互换。
>>> a = 8
>>> str(a)
'8'
>>> float(a)
8.0
>>> b = 'love'
>>> int(b)
>>> b = '8'
>>> float(b)
8.0
>>> int(b)
8
获取数据类型
1.type() 作为函数
2.isinstance( ,)比较两个数据类型是否相等
>>> type(a)
<class 'int'>
>>> type('a')
<class 'str'>
>>> type(2.5)
<class 'float'>
>>> isinstance(a,int)
True
>>> isinstance(a,str)
False
>>> isinstance(5.0,str)
False
算术操作符(必要情况加括号)
一级:幂指(**),左侧优先级别
二级:+、-、*、/、%(求余数)
三级:比较操作符
四级:逻辑运算符(and<or<not)
断言assert
assert + 条件
若条件为假时,程序崩溃,并弹出AssertinError,适用于不确定语句是否为真的情况,用于检查点,以确保条件一定为真。
for循环
for 目标 in 表达式:
循环体
t = 'i love u'
for i in t:
print('hello')
**range()**的使用:
range(star,stop[,step])
name = 'allen iverson'
for i in range(len(name)):
print(name[i])
break/continue函数
break:跳出循环
continue:终止本轮循环,开始下一轮的循环,同时还会先进行真假判断再执行。