用户输入
- python3中单引号和双引号不做区分;
- 用户输入:input,例如:
1
2
3
4name = input("name:")
age = input("age:")
job = input("job:")
salary = input("salary:")
python3中的 “input” 等同于python2 中的 “raw_input”,在 python2中也不要用 “input”
三引号(’’’)的作用
- 多行文本输入时需用到 3 引号,3 引号之间输入的内容将被原样保留,如:
1
2
3
4
5
6
7
8
9
10
11
12msg = '''
If crosswords are too easy and Sudoku a touch boring, why not go and climb a tree?
A study found that childish pastimes such as climbing trees, running barefoot and crawling dramatically boost memory.
Working memory - the type of memory we use every day to remember phone numbers, follow directions and use a shopping list - improved by 50 per cent.
The University of North Florida researchers put 72 men and women aged between 18 and 59 through a test of working memory, in which they had to remember lists of numbers in reverse order.
Some then spent two hours doing a range of obstacle course-like activities.
These included climbing trees, running barefoot and crawling along a narrow beam.
Others listened to a lecture or did a yoga class, before working memory was tested again.
Only those who had done the obstacle course did better.
Climbing a tree and balancing on a beam hone ‘proprioceptive’ skills – the brain’s ability to sense where the legs, arms, hands and feet are in space without looking.
'''
print(msg)
1 | msg1 = ''' |
字符串格式化
1、%d、%s、%f: 强制定义数据类型的一种方式
2、帮助检测数据类型是否正确
3、默认输入输出都是字符串类型
4、type() 显示数据类型
格式化输出方法一之字符串拼接法(每一次拼接占用一块内存,所以一定不要用):
1 | info = ''' |
格式化输出方法二之百分号占位符法,需要注意数据类型(重要):
1 | name = input("name:") |
格式化输出方法二之”Format1”(官方建议):
1 | info = ''' |
格式化输出方法二之”Format2”:
1 | info = ''' |
缩进
- 强制缩进的好处:节省代码、结构清晰;
- 出现 IndentationError就是缩进错误;
- 所有代码自身是顶级,就必须是顶格写;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Date: 2017/6/11
import getpass
#getpass 模块在 Pycharm 中不起作用
_username = 'xiaolin'
_password = 'abc123'
username = input("username:")
#password = getpass.getpass("password:")
password = input("password:")
print(username,password)
if _username == username and _password == password:
print("Welcome user {name} login...". format(name = username))
#PRINT 是 IF 语句的子代码,上下级关系,下级需要缩进
else:
#IF 不成立则执行 ELSE,两者是同级关系,不需要缩进
print("Invaild username or password!")