Python—循环与判断

逻辑控制与循环

album = ['Black Star','David Bowie',25,True]
album.append('new song')    #列表增加元素
print(album[4])
print('Black Star' in album)  #in 判断是否在列表中,返回bool值

注意:浮点和整数虽然是不同类型,但是不影响到比较运算

 

条件控制

#帐号登录
def account_login():
	password = input('Password:')
	if password == '12345':
		print('Login success!')
	else:
		print('Wrong password or invaild input!')
		account_login()
account_login()

 

#帐号登录+重置登录密码
password_list = ['00000','12345']
def account_login():
	password = input('Password:')
	password_correct = password == password_list[-1]
	password_reset = password == password_list[0]
	if password_correct:
		print('Login success!')
	elif password_reset:
		password = input('Enter a new password:')
		password_list.append(password)
		print('Your password has been changed successfully!')
		account_login()
	else:
		print('Wrong password or invaild input!')
		account_login()
account_login()

 

循环

for循环

# 简单的例子1:
for every_letter in 'Hello world':
	print(every_letter)


# 简单的例子2:
#1 + 1 = 2
#2 + 1 = 3......

for num in range(1,11):
	print(str(num)+' + 1 = ',num+1)


# 简单的例子3:
songlist = ['Holy Diver','Thunderstruck','Rebel Rebel']
for song in songlist:
	if song == 'Holy Diver':
		print(song + ' - Dio')
	elif song =='Thunderstruck':
		print(song + ' - AD/DC')
	elif song == 'Rebel Rebel':
		print(song + ' - David Bowie')
# 九九乘法表
for i in range(1, 10):
	for j in range(1, i+1):
		print(' {} X {} = {}\t'.format(j,i, i * j),end='')  #end=''是保证不换行
	print()

 

while循环

# 帐号登录+重置登录密码+限制密码错误次数
password_list = ['00000','12345']
def account_login():
	tries = 3
	while tries >= 1:
		password = input('Password:')
		password_correct = password == password_list[-1]
		password_reset = password == password_list[0]
		if password_correct:
			print('Login success!')
			break
		elif password_reset:
			password = input('Enter a new password:')
			password_list.append(password)
			print('Your password has been changed successfully!')
			account_login()
		else:
			print('Wrong password or invaild input!')
			tries -= 1
			print(tries,'times left')
	else:  #这里的while可以理解成是if循环版,可以使用while-else结构(嵌套逻辑)
		print('The time of input password has been run out!')
account_login()

 

练习题

1.设计一个在桌面上是创建10个文本,并以数字命名的函数

def text_create():
	path = 'C:/Users/ASUS/Desktop/'
	for num in range(1,11):
		with open(path + str(num)+'.txt','w') as text:
			text.write(str(num))
			text.close()
	print('Done!')
text_create()

with as 用法

open 用法

open(file,op):打开指定文件file,若文件不存在则创建。其中file为文件名,file的路径默认为程序所在的位置,也可指定file的路径。

 参数op:(1)“r”或无:若省略参数op,则只是简单打开文件,若文件不存在则会报错,写文件操作也会报错;

     (2)“w”:打开并可写文件。若文件已存在,则以前的内容将被清除。

     (3)“a”:向文件中追加文本。向已存在的文件中追加内容。

    如没有参数“w”则只是简单打开文件,如文件不存在则会报错。    如:a = open("test.txt","w"),a为test.txt的一个文件对象

注:使用open函数打开并写文件时文件时,就算文件存在,Python也会先删除原有文件然后创建新文件,也即文件的内容也随之删除!

2.计算复利 

def invest(amount,rate,time):
	print('principal amount:{}'.format(amount))
	for i in range(1,time+1):
		amount = amount * (1 + rate)
		print('year {}: ${}'.format(i,amount))
invest(100,0.05,8)

3.打印1-100以内的偶数 

for i in range(1,101):
	if i % 2 == 0:
		print(i)

 

 

 

综合练习

摇骰子,猜大小(3>= && <=10 为小  11>= && <= 18 为大)

import random
def roll_dice(cnt = 3):
	points = []
	while cnt > 0:
		point = random.randrange(1,7)
		points.append(point)
		cnt -= 1
	return points

def roll_result(total):
	isBig = 11 <= total <= 18
	isSmall = 3 <= total <= 10
	if  isBig:
		return 'Big'
	elif isSmall:
		return 'Small'

def dice_game():
	print('<<<<<<<<< GAME STRATS! >>>>>>>>>')
	choices = ['Big','Small']
	your_choices = input('Big or Small:')
	if your_choices in choices:
		print('<<<<<<<<< ROLL THE DICE! >>>>>>>>>')
		points = roll_dice()
		you_win = your_choices == roll_result(sum(points))
		print('The points are ',points)
		if you_win:
			print('You win!')
		else :
			print('You lose!')
	else:
		print('Invalid Words!')
	dice_game()
dice_game()

 

练习题 

1.在摇骰子游戏增加新的功能:

  ①设定本金为1000元

  ②本金为0结束游戏

  ③默认赔率为1,压多少,赢多少也输多少

import random
def roll_dice(cnt = 3):
	points = []
	while cnt > 0:
		point = random.randrange(1,7)
		points.append(point)
		cnt -= 1
	return points

def roll_result(total):
	isBig = 11 <= total <= 18
	isSmall = 3 <= total <= 10
	if  isBig:
		return 'Big'
	elif isSmall:
		return 'Small'

def dice_game():
	choices = ['Big','Small']
	total_money = 1000
	while total_money > 0:
		print('<<<<<<<<< GAME STRATS! >>>>>>>>>')
		your_choices = input('Big or Small:')
		if your_choices in choices:
			money = int(input('How much do you wanna bet :'))
			print('<<<<<<<<< ROLL THE DICE! >>>>>>>>>')
			points = roll_dice()
			you_win = your_choices == roll_result(sum(points))
			if you_win:
				print('The points are ', points,'You win!')
				total_money = total_money  + money
				print('You gained {},you are have {} now'.format(money,total_money))
			else :
				print('The points are ', points, 'You lose!')
				total_money = total_money - money
				print('You lost {},you are have {} now'.format(money, total_money))
		else:
			print('Invalid Words!')
	else:
		print('GAME OVER!')
dice_game()

2.手机号验证,发送验证码

  ①长度不少于11位

  ②是移动、联通、电信号码段中的一个电话号码;

  ③因为是输入号码界面,输入除号码外其他字符的可能性可以忽略;

  ④移动号段,联通号段,电信号段

def send_code():
	CN_mobile = [134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,
	             187,188,147,178,1705]
	CN_union = [130,131,132,155,156,185,186,145,176,1709]
	CN_telecom = [133,153,180,181,189,177,1700]
        #以上是各运营商的号码段

	while True:
		number = input('Enter Your number :')
		first_three = int(number[0:3])
		first_four = int(number[0:4])
		if len(number) == 11:
			if first_three in CN_mobile or first_four in CN_mobile:
				print('Operator : China Mobile')
				break
			elif first_three in CN_union or first_four in CN_union:
				print('Operator : China Union')
				break
			elif first_three in CN_telecom or first_four in CN_telecom:
				print('Operator : China Telecom')
				break
			else:
				print('No such a operator!')
		else:
			print('Invalid length,your number should be in 11 digits')
	print('We\'re sending verification code via text to your phone:'+ number)
send_code()

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值