Python的交互和注释介绍

in 互联网技术 with 0 comment  访问: 3,298 次

程序交互

如何能让Python识别读取用户的输入,就像windows安装程序那样傻瓜式的交互呢,下面我们简单介绍一下Python的交互输入输出。

实例代码如下:

#!/usr/bin/env python3
# encoding: utf-8
username = input("Please enter your username:")
password = input("Please enter your password:")
print("Your name is %s, Your Password is %s" % (username, password))

代码执行结果为:

$ python3 py_input.py 
Please enter your username:nock
Please enter your password:fashengba.com
Your name is nock, Your Password is fashengba.com

执行脚本的时候你会发现,程序在等待你输入用户名和密码后才会继续往下走。

说明: Python的交互式输入使用的是内置函数input()实现的,但是在Python2.7.x版本的时候可以同时使用raw_input()input()函数,但是在Python3.5.x版本就没有raw_input()函数了,只能够使用input()

inputraw_input有什么区别呢,我们这里简单说明一下:

#!/usr/bin/env python2
# encoding: utf-8

username = raw_input("Please enter your username: ")
password = input("Please enter your password: ")
print("username type is:", type(username), "password type is:", type(password))

结果如下:

$ python py_raw_input.py 
Please enter your username: nock
Please enter your password: 123456
('username type is:', <type 'str'>, 'password type is:', <type 'int'>)

$ python py_raw_input.py 
Please enter your username: 123
Please enter your password: fashengba
Traceback (most recent call last):
  File "py_raw_input.py", line 5, in <module>
    password = input("Please enter your password: ")
  File "<string>", line 1, in <module>
NameError: name 'fashengba' is not defined

从上面结果我们可以看到在Python2.7.x版本下raw_input会把接受的任何内容都当做字符串处理而input只能接受int类型的输入,否则就会把用户输入当做一个变量来处理,从而就会报NameError: name 'xxx' is not defined的错误。Python3为了简洁统一,在Python3中已经不存在了raw_input函数,input一个函数完全可以做到所有使用,而且默认input接受任何输入都当做str类型处理。

平常如果我们用针对密码、密码串之类的交互的话,一般用户的输入时隐藏或者*****的,输入密码时,在Python下如果你需要你输入的东西不可见,可以利用getpass 模块中的 getpass方法来处理,示例如下:

#!/usr/bin/env python3
# Author: nock.chen
# _*_coding:utf-8_*_

#导入getpass模块
import getpass

# 将用户输入的内容赋值给 name 变量
pwd = getpass.getpass("请输入密码:")

# 打印输入的内容
print("Password is",pwd,"***print end")

#比如我输入110119,执行过程和结果如下:
请输入密码:
Password is 110119 ***print end

Python代码的注释

随着学习的深入,当你利用Python写复杂程序的时候有上千上万行代码,有些代码你花了很久写出来,过了些天再回去看,发现竟然看不懂了,哈哈,这太正常了。 另外,你以后在工作中会发现,一个项目多是由几个甚至几十个开发人员一起做,你要调用别人写的代码,别人也要用你的,如果代码不加注释,你自己都看不懂,更别说别人了,这样写会挨打的。所以为了避免这种尴尬的事情发生,一定要增加你代码的可读性。

而注释就能很大程度减少这一麻烦,写代码养成标注注释这是一个非常好的习惯。

单行注释:# 开头就好,跟shell一样
多行注释:成对的三个单引号 ''' 注释内容 ''' 或者 成对的三个双引号 """ 注释内容 """ , 养成一致习惯,多行统一用""" """就好

下面给大家看一段标准代码的注释,忽略代码意思

try:
    # OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA
    from _hashlib import pbkdf2_hmac
except ImportError:
    _trans_5C = bytes((x ^ 0x5C) for x in range(256))
    _trans_36 = bytes((x ^ 0x36) for x in range(256))

    def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None):
        """
        Password based key derivation function 2 (PKCS #5 v2.0)

        This Python implementations based on the hmac module about as fast
        as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster
        for long passwords.
        """
        if not isinstance(hash_name, str):
            raise TypeError(hash_name)

        if not isinstance(password, (bytes, bytearray)):
            password = bytes(memoryview(password))
        if not isinstance(salt, (bytes, bytearray)):
            salt = bytes(memoryview(salt))

        # Fast inline HMAC implementation
        inner = new(hash_name)
        outer = new(hash_name)
        blocksize = getattr(inner, 'block_size', 64)
        if len(password) > blocksize:
            password = new(hash_name, password).digest()
        password = password + b'\x00' * (blocksize - len(password))
        inner.update(password.translate(_trans_36))
        outer.update(password.translate(_trans_5C))

代码注释原则:

  1. 不用全部加注释,只需要在自己觉得重要或不好理解的部分加注释即可
  2. 注释可以用中文或英文,但绝对不要拼音噢,最好也不要英中文交叉
WeZan