美文网首页
Python学习1

Python学习1

作者: 赵东伟同学 | 来源:发表于2017-03-29 15:12 被阅读0次

学习自《编程小白的第一本 Python 入门书》

P61

1.jpg
验证用户登录的函数
def account_login():
    password = input('Password:')
    if password == '12345':
        print('Login success!')
    else:
        print('Wrong password or invalid input!')
        account_login()
account_login()

上面的函数可以改成这样

def account_login():
    password = input('Password:')
    password_correct = password == '12345'
    if password_correct:
        print('Login success')
    else:
        print('Wrong password or invalid input!')
        account_login()
account_login()
2.jpg

接下来使用elif语句给刚才设计的函数增加一个重置密码的功能

password_list = ['*#*#','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:
        new_password = input('Enter a new password:')
        password_list.append(new_password)
        print('Your password has changed successfully!')
        account_login()
    else:
        print('Wrong password or invalid input!')
        account_login()
account_login()

第1行:创建一个列表,用于存储用户的密码、初始密码和其他数据(对实际数据库的简化模拟);

第2行:定义函数;

第3行:使用input获得用户输入的字符串并储存在变量password中;

第4行:当用户输入的密码等于密码列表中最后一个元素的时候(即用户最新设定的密码),登录成功

第5-9行:当用户输入的密码等于密码列表中第一个元素的时候(即重置密码的“口令”)触发密码变量,并将变更后的密码储存至列表的最后一个,成为最新的用户密码;

第10行:反之,一切不等于预设密码的输入结果,全部会执行打印错误提示,并且再次调用函数,让用户再次输入密码;

第11行:调用函数。

for循环

>>> for every_letter in 'Hello world':
    print(every_letter)

    
H
e
l
l
o
 
w
o
r
l
d
  • 说明
3.jpg

加深理解

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

    
1 + 1= 2
2 + 1= 3
3 + 1= 4
4 + 1= 5
5 + 1= 6
6 + 1= 7
7 + 1= 8
8 + 1= 9
9 + 1= 10
10 + 1= 11

while循环

4while.jpg

控制while循环,在循环过程中制造某种可以使循环停下来的条件

>>> while True:
    print('Repeat this line !')
    count = count + 1
    if count == 5:
        break

    
Repeat this line !
Repeat this line !
Repeat this line !
Repeat this line !
Repeat this line !

除此之外,让 While 循环停下来的另一种方法是:改变使循环成立的条件。为了解释这个例子,我们在前面登录函数的基础上来实现,给登录函数增加一个新功能:输入密码错误超过3次就禁止再次输入密码

password_list = ['*#*#','12345']
def account_login():
    tries = 3
    while tries > 0:
        password = input('Password:')
        password_correct = password == password_list[-1]
        password_reset = password == password_list[0]
        if password_correct:
            print('Login success!')
        elif password_reset:
            new_password = input('Enter a new password:')
            password_list.append(new_password)
            print('Your password has changed successfully!')
            account_login()
        else:
            print('Wrong password or invalid input!')
            tries = tries -1
            print( tries, 'times left')
    else:
        print('Your account has been suspended')
        
account_login()

这段代码只有三处与前面的不一样:

第4-5行:增加了 while 循环,如果 tries > 0 这个条件成立,那么便可输入密码,从而执行辨别密码是否正解的逻辑判断;

第20-21行:当密码输入错误时,可尝试的次数 tries 减少1;
第23-24行:while 循环的条件不成立时,就意味着尝试次数用光,通告用户账户被锁。

在这里while可以理解成是 if 循环版,可以使用 while-else结构,而在 while 代码块中又存在着第二层的逻辑判断,这其实构成了嵌套逻辑(NestedCondition)

练习题 P70

1、设计这样一个函数,在桌面的文件夹上创建10个文本,以数字给它们命名。

def text_creation():
    path = 'D:\\'
    for name in range (1,11):
        with open(path + str(name) + '.txt','w') as text:
            text.write(str(name))
            text.close()
            print('Done')
text_creation()

2、复利是一件神奇的事情,正如富兰克林所说:“复利是能够将所有铅块变成金块的石头”。设计一个复利计算 invest(),它包含三个参数: amount (资金), rate (利率),time (投资时间)。输入每个参数后调用函数,应该返回每一年的资金总额。它看起来就应该像这样 (假设利率为5%):

def invest(amount, rate, time):
    print("principal amount:{}".format(amount))
    for t in range(1, time + 1):
        amount = amount * (1 + rate)
        print("year {}: ${}".format(t, amount))
invest(100, .05, 8)
invest(2000, .025, 5)

3、打印1-100内的偶数

不能整除的数就是偶数

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

问题.jpg
import random
def roll_dice(number=3, points=None):
    print('<<<<< ROLL THE DICE! >>>>>')
    if points is None:
        points = []
    while numbers > 0:
        point = random.randrange(1,7)
        points.append(point)
        numbers = numbers - 1
    return points

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

def start_game():
    print('<<<<< GAME STARTS! >>>>>')
    choices = ['Big','Small']
    your_choice = input('Big or Small :')
    if your_choice in choices:
        points = roll_dice()
        total = sum(points)
        youWin = your_choice == roll_result(total)
        if youWin:
            print('The points are',points,'You win !')
        else:
            print('The points are',points,'You lose !')
    else:
        print('Invalid Words')
        start_game()
start_game()

相关文章

网友评论

      本文标题:Python学习1

      本文链接:https://www.haomeiwen.com/subject/gmoeottx.html