2012-07-31 25 views
3

我試圖學習如何編程,我遇到了問題....如何使用python驗證輸入中的數字?

我想弄清楚如何確保有人輸入一個數字而不是字符串。我發現一些相關的答案令人困惑,一些代碼對我來說不起作用。我認爲有人發佈了try:函數,但它不起作用,所以也許我需要導入一個庫?

這裏就是我想現在:

代碼:

print "Hi there! Please enter a number :)" 
numb = raw_input("> ") 

if numb != str() 
    not_a_string = int(next) 
else: 
    print "i said a number, not a string!!!" 

if not_a_string > 1000: 
    print "You typed in a large number!" 

else: 
    print "You typed in a smaller number!" 

此外,我還有一個問題,而我問。我怎樣才能讓它接受大寫和小寫拼寫?在下面我的代碼,如果我輸入「去商場」,但以小寫摹它不會運行if語句,因爲它只接受資本G.

print "What would you like to do: \n Go to the mall \n Get lunch \n Go to sleep" 
answer = raw_input("> ") 

if answer == "Go to the mall": 
    print "Awesome! Let's go!" 
elif answer == "Get lunch": 
    print "Great, let's eat!" 
elif answer == "Go to sleep": 
    print "Time to nap!" 
else: 
    print "Not what I had in mind...." 

感謝。 ^^

編輯:我也使用Python 2.7沒有3.0

+0

您可能希望如避免使用比較'如果麻木!= STR()'因爲你是比較空字符串的輸入。另外,請記住'raw_input()'會將您的輸入轉換爲字符串。 – 2012-07-31 03:39:16

回答

4

你可以做這樣的事情:

while True: #infinite loop 
    ipt = raw_input(' Enter a number: ') 
    try: 
     ipt = int(ipt) 
     break #got an integer -- break from this infinite loop. 
    except ValueError: #uh-oh, didn't get an integer, better try again. 
     print ("integers are numbers ... didn't you know? Try again ...") 

要回答你的第二個問題,使用.lower()字符串的方法:

if answer.lower() == "this is a lower case string": 
    #do something 

如果您想要,您可以使您的字符串比較真正健壯:

if answer.lower().split() == "this is a lower case string".split(): 

在這種情況下,您甚至會匹配「ThIs IS A lower Case \ tString」等字符串。爲了讓你接受更自由的東西,你需要使用正則表達式。

(並且所有這些代碼都可以在python2.x或3.x上正常工作 - 我通常將括號內的打印語句放在括號內以使其適用於任一版本)。

編輯

此代碼將不太工作對python3.x - 在python3,您需要更改raw_inputinput,使其工作。 (對不起,忘了那個)。

+0

太棒了,它效果很好!我有個問題。當您寫入ValueError之外:爲什麼您在括號(「String here」)中編寫打印字符串而不是引號?這只是偏好嗎?我只是試了一下,它在兩個方面都有效。 編輯:噢,謝謝! – Danielle 2012-07-31 03:12:19

+0

@Danielle:在Python 2中,兩種方式意味着同樣的事情。在Python 3中,使用'print'時需要括號。許多人現在用括號寫'print()',這樣它就可以在兩種情況下工作。 – 2012-07-31 03:14:16

+0

@Danielle - Greg Hewgill是對的。請注意,雖然print(「foo」)和print「foo」在python2中是相同的,但print(「foo」,「bar」)與print不同。一個創建了一個元組,而另一個創建了一個元組,而另一個則沒有) – mgilson 2012-07-31 03:25:00

0

首先,你應該只問每個帖子一個問題。

Q1:使用內置.isdigit()

if(numb.isdigit()): 
    #do the digit staff 

Q2:你可以使用string.lower(S)以解決資金問題。

+0

's.isdigit()'不適用於像「-100」這樣的字符串(我前幾天指出了這一點)。這真是一個很好的例子,爲什麼EAFP在Python中與LBYL相比很好地工作。 – mgilson 2012-07-31 03:32:10

0

,你可以嘗試

 

    numb = numb.strip() 
    if numb.isdigit() or (numb[0] in ('+', '-') and numb[1:].isdigit(): 
     # process numb