w1:python_ if_for_while 基本用法

w1_if_for_while

5.Python3.5-开课介绍2

擅长领域

7、第07章节-Python3.5-变量

pycharm设置

变量定义规则:

1.变量只能是字母、数据或下划线的任意组合
2.变量名的第一个字符不能是数字
3.以下关键字不能声明为变量名

and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield

9、第09章节-Python3.5-字符编码的区别与介绍

10、第10章节-Python3.5-用户交互程序

关于注释

单行注释:#code
多行注释:‘’’ code '''

多行输出

打印多行:
msg='''
line 1
line 2
line 3
...

line n
'''
print(msg)

占位格式输出

name = input("name:")
age = input("age:")
job = input("job:")

info='''
------info %s-----
name:%s
age:%d
job:%s
'''% (name,name,age,job)
print(info)
%s 代表 string
%d 代表 digital

19:57

拼接格式输出

info='''
------info '''+  name + '''-----
name:''' + name +'''
age:''' + age + '''
job:''' + job
print(info)

变量赋值格式输出

info='''
------info {NAME}-----
name:{NAME}
age:{AGE}
job:{Job}
'''.format (NAME=name,AGE=age,Job=job)

print(info)

11、第11章节-Python3.5-if else流程判断

密码以密文显示

import getpass
password = getpass.getpass("password:")
print(password)

用户名密码判断

_username="testuser"
_password="p123"
username = input("username:")
password = input("password:")
if username == _username and password == _password :
    print("welcome user {user_name}".format(user_name=username))
else:
    print("invalid password or username")

12、第12章节-Python3.5-while 循环

13、第13章节-Python3.5-while 循环优化版本

猜年龄

real_age = 18
count = 0
while count < 3:
    input_age = int(input("age:"))
    if input_age > real_age :
        print("you think bigger than real age!")
    elif input_age == real_age:
        print("yes,you got it")
        break
    else:
        print("you think smaller than real age!")
    count = count + 1
else:
    print("you have tried too many times!")

for循环

for i in range(0,10)
    print(i)

for循环,使用步长

for i in range(0,10,3)
    print(i)
```10:16
```

while循环3次后询问是否继续

real_age = 18
count = 0
while count < 3:
    input_age = int(input("age:"))
    if input_age > real_age :
        print("you think bigger than real age!")
    elif input_age == real_age:
        print("yes,you got it")
        break
    else:
        print("you think smaller than real age!")
    count += 1
    if count == 3:
        continue_confirm = input("do you need to continue?")
        if continue_confirm == "n":
            break
        else:
            count = 0

14、第14章节-Python3.5-for 循环及作业要求

continue 跳出本次循环,继续下一次循环

for i in range(0,10):
    if i < 5:
        print("loop",i)
    else:
        continue
    print("hehe...")

W1-Practice

BLOG

编写登陆接口

输入用户名密码
认证成功后显示欢迎信息
输错三次后锁定

多级菜单

三级菜单
可依次选择进入各子菜单
所需新知识点:列表,字典

练习要求

1,博客
2.流程图
3.README
4.code

W1完成作品1:登陆接口

登陆接口流程图

README

1.python environment required:
python 3.5
2.how to start program:
python login_code.py

code:login_code.py

W1完成作品2:多级菜单

流程图

README

1.python environment required:
python 3.5
2.how to start program:
python multiple_menu.py

code:multiple_menu.py

#!/usr/bin/env python
#-*-coding: utf-8 -*-
#author: Mr.Wu

import os

dict_demo_file_name = "dict_demo.txt"
dict_demo = {'华为': {'A系': {'A1': [1000, 1100, 1200, ], 'A2': [2000, 2100, 2200, ], 'A3': [3000, 3100, 3200, ], },
                    'B系': {'B1': [4000, 4200, 4400, ], 'B2': [5000, 5200, 5400, ], 'B3': [6000, 6200, 6400, ], },
                    'C系': {'C1': [7000, 7300, 7600, ], 'C2': [8000, 8300, 8600, ], 'C3': [9000, 9300, 9600, ], }, },
             '小米': {'M系': {'M1': [610, 630, 650, ], 'M2': [710, 730, 750, ], 'M3': [810, 830, 850, ], },
                    'N系': {'N1': [920, 950, 980, ], 'N2': [1020, 1050, 1080, ], 'N3': [1120, 1150, 1180], },
                    'L系': {'L1': [1230, 1270, 1300, ], 'L2': [1430, 1470, 1500, ], 'L3': [1630, 1670, 1700, ], }, },
             '魅族': {'X系': {'X1': [599, 699, 799, ], 'X2': [699, 799, 899, ], 'X3': [799, 899, 999, ], },
                    'Y系': {'Y1': [1099, 1199, 1299, ], 'Y2': [1299, 1399, 1499, ], 'Y3': [1499, 1599, 1699, ], },
                    'Z系': {'Z1': [2099, 2199, 2299, ], 'Z2': [2399, 2499, 2599, ], 'Z3': [2699, 2799, 2899, ], }, }, }

if os.path.exists(dict_demo_file_name) and os.path.getsize(dict_demo_file_name) != 0:
    with open(dict_demo_file_name,'r') as f:
        dict_data = eval(f.read())
    f.close()
    # print(dict_data.keys())
else:
    with open(dict_demo_file_name,'w') as f:
        f.write(str(dict_demo))
    f.close()
    dict_data = dict_demo

def show(data):
    data = data
    items = []
    if isinstance(data,list):
        for item in data:
            print(data.index(item)+1,item)
        print("menu ended, please press 'b' to return or press 'q' to quit")
        return data
    elif isinstance(data,dict):
        for index,item in enumerate(data,1):
            print(index,item)
            items.append(item)
        return items
    else:
        print("Invalid data!")

data = dict_data      #原始字典
menu_list = show(data) #展示用户的菜单列表
last_menu = [data]    #为展示上一级菜单而使用的原始数据
end_flag = False      #遍列到列表时,表示已到了菜单的末尾则标记为True

while True:
    user_choose = input("choose:").strip()

    if not end_flag and user_choose.isdigit():
        user_choose = int(user_choose)
        if user_choose in range(1, len(data.keys()) + 1, 1):
            # print(last_menu[-1]) #获取上一级菜单的原始数据
            # print([menu_list[user_choose-1]])  #获取用户选取的菜单的字典的键
            data = last_menu[-1][menu_list[user_choose - 1]]  # 从原始数据中找到用户选取的字典键对应的值
            menu_list = show(data)  # 将值传入show函数以展示
            if isinstance(data, list): #判断取出的值是否为列表
                end_flag = True   #如果是列表,则表明已经到菜单末尾,把菜单末尾标记置为True
                data = last_menu[-1]  #并把data换回成上一次取出的值,类型为(字典)
            else:
                last_menu.append(data)
        else:
            print("out of menu options!")
            continue

    elif user_choose == 'b':

        if len(last_menu) > 1:
            menu_list = show(last_menu[-2])
            last_menu.pop(-1)
        else:
            menu_list = show(dict_data)
            print("You already at Top Menu")
        end_flag = False

    elif user_choose == 'q':
        exit()
    else:
        print("Invalid input!")

心得:

1.画流程图,然后根据流程图写出代码初步结构;
2.涉及到循环,如这次的多级菜单,就需要在程序中表明菜单的边界,作出判断,边界最上面是顶级菜单,最后是末尾菜单项。

原文地址:https://www.cnblogs.com/rootid/p/9315542.html