我試圖學習如何編程,我遇到了問題....如何使用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
您可能希望如避免使用比較'如果麻木!= STR()'因爲你是比較空字符串的輸入。另外,請記住'raw_input()'會將您的輸入轉換爲字符串。 – 2012-07-31 03:39:16