python基礎4 使用者互動

2022-09-03 12:36:10 字數 3410 閱讀 8319

本節主要內容:

使用者使用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

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 "", line 1, in

input_a = input("input: ")

file "", line 1, in

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)

'str'>

>>> input_b = input("input: ")

input: 123

>>> type(input_b)

'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:

age:

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 ----

name:

age:

salary:

'''.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)

python使用者互動

python定義字串一般用單引號或雙引號,把要表示的內容括起來,如 name linjunjie address taiwan 如果要定義的字串有多行的情況,用三個單引號 person name jj job geshou age 30 print person 列印使用者輸入的內容 name in...

Python使用者互動

類似銀行的atm機 就是一台計算機 使用者要取錢就需要我們為其編寫程式來執行,需要使用者輸入密碼金額等資訊與atm機互動 完美的分割線 使用下面這幾行 就可以實現上面的功能 username input username password input password print username,...

python使用者互動

賦值.把等號右邊的內容賦值給左邊 s input 這裡是input input輸入.讓使用者輸入一些內容.程式會停在這句話.阻塞.input結束的時候.會自動的收集到使用者輸入的內容.把內容返回給前面的變數 print 使用者輸入的內容是 s print可以一次性列印多個內容 a input 請輸入...