python基礎4 用戶交互
阿新 • • 發佈:2017-07-20
接受 symbol string cal 自己 efi 類型 int file
本節主要內容:
- 例一 input()
- 例二字符拼接
- 例三 %占位符
- 例四 raw_input()和 input()
- 例五 格式化用戶交互
- 例六 數組格式化
- 參考網頁
用戶使用input函數實現交互,本節通過示例來學習此節內容:
例一 input()
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Cathy Wu
username =input("username")
password =input("password")
print(username,password)
運行後,提示輸入“username”和“password”, 輸入後打印“username”和“password”。
例二字符拼接
name = input("name")
age = input("age")
salary = input("salary")
info = ‘‘‘
------info of ‘‘‘ + name+‘‘‘---
age:‘‘‘ + age + ‘‘‘
salary:‘‘‘+ salary
print(info)
運行結果:
namecathy
age25
salary5000
------info of cathy---
age:25
salary:5000
例三 %占位符
%s或者%d %對應一個占位符號,要一一對應。s代表string,d代表數字,%f代表浮點數。默認所有的輸入都是string。
name = input("name")
age = input("age")
salary = input("salary")
info =‘‘‘---info of %s ----
name: %s
age:%s
salary: %s
‘‘‘ % (name,name,age,salary)
print(info)
運行結果:
namecathy
age12
salary12
---info of cathy ----
name: cathy
age:12
salary: 12
例四 raw_input() 和 input()
python3裏面沒有raw_input. raw_input在python2裏面有使用, input() 本質上還是使用 raw_input() 來實現的,只是調用完 raw_input() 之後再調用 eval() 函數。
>>> raw_input_A = raw_input("raw_input: ")
raw_input: abc
>>> input_A = input("Input: ")
Input: abc
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
input_A = input("Input: ")
File "<string>", line 1, in <module>
NameError: name ‘abc‘ is not defined
>>> input_A = input("Input: ")
Input: "abc"
>>>
上面的代碼可以看到:這兩個函數均能接收 字符串 ,但 raw_input() 直接讀取控制臺的輸入(任何類型的輸入它都可以接收)。而對於 input() ,它希望能夠讀取一個合法的 python 表達式,即你輸入字符串的時候必須使用引號將它括起來,否則它會引發一個 SyntaxError 。
>>> raw_input_B = raw_input("raw_input: ")
raw_input: 123
>>> type(raw_input_B)
<type ‘str‘>
>>> input_B = input("input: ")
input: 123
>>> type(input_B)
<type ‘int‘>
>>>
上面的代碼可以看到:raw_input() 將所有輸入作為字符串看待,返回字符串類型。而 input() 在對待純數字輸入時具有自己的特性,它返回所輸入的數字的類型( int, float );同時在前一段代碼 知道,input() 可接受合法的 python 表達式,舉例:input( 1 + 3 ) 會返回 int 型的 4 。
例五 格式化用戶交互
官方建議的用戶使用方法。
name = input("name")
age = input("age")
salary = input("salary")
info3 = ‘‘‘
---info3 of {_name} ----
name: {_name}
age: {_age}
salary: {_salary}
‘‘‘.format(_name=name,
_age=age,
_salary=salary)
print(info3)
運行結果如下:
namecathy
age25
salary10000
---info3 of cathy ----
name: cathy
age: 25
salary: 10000
例六 數組格式化
name = input("name")
age = input("age")
salary = input("salary")
info4 = ‘‘‘
---info4 of {0} ----
name: {0}
age: {1}
salary: {2}
‘‘‘.format(name, age, salary)
print(info4)
運行結果如下:
namecathy
age25
salary15000
---info4 of cathy ----
name: cathy
age: 25
salary: 15000
其他
上訴例子,密碼是可見的,怎麽讓密碼不可見了,有個模塊getpass
import getpass
username = input("username:")
password = getpass.getpass("password")
print(username, password)
參考網頁
http://www.cnblogs.com/way_testlife/archive/2011/03/29/1999283.html
python基礎4 用戶交互