![](/img/trans.png)
[英]How can I make sure that the error i created is only given when letters are typed but not deciamls?
[英]How do I provide error checking to ensure user input only allows letters and provides a looping error message if numbers are typed?
我試圖為userName輸入提供一個循環錯誤消息,以便用戶在鍵入除字母aA-zZ以外的任何內容時收到錯誤消息,(我不想讓用戶專門輸入數字) 。 我希望它的操作類似於我用於customerAge輸入的那個(我作為示例提供)。 但我似乎無法找出完成此任務的正確代碼。 誰能提供一些見解?
customerName = input('Enter your name: ')
customerAge = int(input('Enter your age: '))
while customerAge <= 15 or customerAge >= 106:
print('Invalid entry')
customerAge = int(input('Enter your age: '))
在回顧了我收到的所有答案后(感謝所有人的幫助)。 我這樣編碼它似乎運行正常。
customer_name = input('Please enter your name: ')
while not customer_name.isalpha():
print('invalid Entry')
customer_name = input('Please enter your name: ')
讓我們從您的程序需要做的開始:
循環直到輸入有效
這將是以下形式的各種驗證:
1)用戶插入一些東西
2)出了點問題
3)程序通知用戶並再次詢問輸入
所以,在python中:
valid = False
while not valid:
valid = True
customer_name = input('Enter your name: ')
customer_age = int(input('Enter your age: '))
if customer_age <= 15 or customer_age >= 106:
print 'Enter a valid age'
valid = False
if not customer_name.isalpha():
print 'Enter a valid name'
valid = False
我們在這里做了什么:
1)將valid
設置為True
,這樣快樂的情況就會讓我們走出循環
2)獲得兩個值
3)如果它們中的任何一個無效,則將valid
設置為False
並通知情況
您甚至可以使用2個循環來單獨驗證。
有關isalpha()方法的注釋 :您可以在此處找到文檔,並在此問題中找到有關它的一些好信息
另外,作為底線建議:永遠不要在python變量中使用camel case。
該表示法保留給Class
名。 對於變量,使用小寫和_
正則表達式應該做你想要的
import re
while 1:
name = raw_input("Enter your name: ")
if re.search(r'(?i)[^a-z]', name):
print("Invalid name")
else:
break
檢查type
與每個字符的type()
函數。
u_input = raw_input()
valid = ""
for char in u_input:
if str(type(char)) == "<type 'int'>":
valid = "False"
break
else:
pass
if valid == 'False':
print 'This string has a number! Gosh darn it!"
將它放在一個函數/ while
循環中,你就有了循環錯誤信息。 您可以添加其他循環以確保任何其他參數。
這是最簡單,也可能是最有效的方式。
有關type()
更多信息,請訪問: https : //docs.python.org/2/library/functions.html#type
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.