簡體   English   中英

Python 中的 raw_input 函數

[英]raw_input function in Python

raw_input函數是什么? 它是一個用戶界面嗎? 我們什么時候使用它?

它向用戶顯示提示(raw_input([ arg raw_input([arg])的可選參數),從用戶那里獲取輸入並以字符串形式返回用戶輸入的數據。 請參閱raw_input()的文檔。

例子:

name = raw_input("What is your name? ")
print "Hello, %s." % name

這與input()的不同之處在於后者試圖解釋用戶給出的輸入; 通常最好避免使用input()並堅持使用raw_input()和自定義解析/轉換代碼。

注意:這是針對 Python 2.x 的

raw_input是一種輸入形式,它采用字符串形式的參數,而輸入函數采用的值取決於您的輸入。 比方說, a=input(5)將 a 作為值為 5 的整數返回,而a=raw_input(5)將 a 作為字符串“5”返回

“輸入”函數將您輸入的輸入轉換為 python 代碼。 “raw_input”不轉換輸入並接受給定的輸入。 建議對所有內容都使用 raw_input。 用法:

>>a = raw_input()
>>5
>>a
>>'5'

raw_input() 函數從輸入(即用戶)中讀取一行並返回一個字符串

作為 raw_input() 的 Python v3.x 已重命名為 input()

PEP 3111:raw_input() 已重命名為 input()。 也就是說,新的 input() 函數從 sys.stdin 讀取一行並返回它,並去除尾隨換行符。 如果輸入過早終止,它會引發 EOFError。 要獲得 input() 的舊行為,請使用 eval(input())。

參考:文檔 Python 3

另一個示例方法,如果您需要使代碼更簡單,則可以使用 print 混合提示。

格式:-

x = raw_input () -- 這將以字符串形式返回用戶輸入

x= int(raw_input()) -- 從 raw_input() 獲取輸入數字作為字符串,然后使用 int() 將其轉換為整數。

print '\nWhat\'s your name ?', 
name = raw_input('--> ')
print '\nHow old are you, %s?' % name,
age = int(raw_input())
print '\nHow tall are you (in cms), %s?' % name,
height = int(raw_input())
print '\nHow much do you weigh (in kgs), %s?' % name,
weight = int(raw_input())

print '\nSo, %s is %d years old, %d cms tall and weighs %d kgs.\n' %(
name, age, height, weight)

如果我讓 raw_input 那樣,沒有 Josh 或其他任何東西。 It's a variable,I think,但我不明白她的名字:-(

raw_input 函數提示您輸入並將其作為字符串返回。 這當然對我有用。 你不需要閑着。 只需打開“DOS 提示符”並運行該程序。

這就是我的樣子:

C:\temp>type test.py
print "Halt!"
s = raw_input("Who Goes there? ")
print "You may pass,", s

C:\temp>python test.py
Halt!
Who Goes there? Magnus
You may pass, Magnus

我輸入我的名字並在程序打印出“Who Goes there?”后按下[Enter ]。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM