py基础重要小知识点及 第一周 练习题

1、定义变量:

当变量值为数字时,一定要加  score= int(score)  --score为变量名

布尔值 bool 使用不是空的字符串只会得到True

#bool值:所有数据类型都自带布尔值
#布尔值为假的情况:0,空,None
x=0
print(bool(x))
#只有x=0,则是False

2、基本运算符

a = 10
b = 3
print(a/b)#真正的除法,有零有整

a = 10
b = 3
print(a//b)#取整除,返回商的整数部分

a = 10
b = 3
print(a%b)# 取模,返回除法的余数

a = 10
b = 3
print(a**b) #10的三次方 取幂

比较运算符:

===  的区分】 =  是赋值;   == 是比较对象是否相等

不等于:!= 

 

3、流程判断 if  else

age = 73
age_of_boy = input('我的年龄是:')
age_of_boy=int(age_of_boy)
if age_of_boy > age:
    print('太大了')
elif age_of_boy < age:
    print('太小了')
else:
    print('猜对了')

4、while + else

count= 0
while count<10:
    print('loop',count)
    if count == 3:
        break
    count+=1
else:
    print('while 正常结束,没有被break打断,才会执行这里的代码')
#没有循环完所以不会打印最后

练习题:
#1. 使用while循环输出1 2 3 4 5 6     8 9 10
count= 0
while count < 11:
if count ==7:
count+=1
continue
print(count)
count +=1
#2. 求1-100的所有数的和
res=0
count = 1
while count <=100:
res=res+count
count+=1
print(res)
#3. 输出 1-100 内的所有奇数
count =1
while count<=100:
if count%2 !=0:
print(count)
count+=1
#4. 输出 1-100 内的所有偶数
count =1
while count<=100:
if count%2 !=1:
print(count)
count+=1
#5. 求1-2+3-4+5 ... 99的所有数的和
res=0
count=1
while count <= 99:
if count%2 == 0:
res-=count
else:
res+=count
count+=1
print(res)
#5. 求1-2+3-4+5 ... 99的所有数的和
sec = 0
count=1
while count <= 5:
if count%2 == 0:
sec -= count
else:
sec += count
count += 1
print(sec)
#6. 用户登陆(三次机会重试)
count = 0
name = 'alex'
passwd ='123.com'
while count <3:
username = input('请输入用户名:')
password = input('请输入密码:')
if username == name and password == passwd:
print('success login')
break
else:
print('用户名或密码错误请重新输入')
count+=1
#8:猜年龄游戏升级版
# 要求:
# 允许用户最多尝试3次
# 每尝试3次后,如果还没猜对,就问用户是否还想继续玩,
# 如果回答Y或y, 就继续让其猜3次,以此往复,
# 如果回答N或n,就退出程序
# 如何猜对了,就直接退出 
count = 0
age =18
while True:
if count ==3:
yes = input('是否继续尝试?')
if yes == 'Y' or yes == 'y':
count=0
else:
break

age_of_boy = int(input('请输入你的年龄:'))
if age_of_boy == age:
print('success')
break
count+=1

#### for 循环
为什么有for 循环 减少重复代码
for i in range(10):print(i)
p=['a','b','c','d','e']
for i in range(len(p)):
print(i,p[i])


posted @ 2017-09-05 16:51  美美的黑天鹅  阅读(148)  评论(0)    收藏  举报