2015-06-24 75 views
-1

我的目標是確保用戶在userName輸入中鍵入數字時,它不應該接受它並讓它們再次嘗試。如何讓我的代碼在Python中正確循環?

與userNumber相同的東西。當用戶輸入字母時,應該用另一行提示他們再次嘗試。

問題是,當他們輸入正確的輸入時,程序將繼續循環並無限期地列出數字。

我是新來的編碼,我試圖找出我做錯了什麼。先謝謝你!

userName = input('Hello there, civilian! What is your name? ') 

while True: 
    if userName.isalpha() == True: 
     print('It is nice to meet you, ' + userName + "! ") 
    else: 
     print('Choose a valid name!') 


userNumber = input('Please pick any number between 3-100. ') 

while True: 
    if userNumber.isnumeric() == True: 
     for i in range(0,int(userNumber) + 1,2): 
      print(i) 
    else: 
     print('Choose a number please! ') 
     userNumber = input('Please pick any number between 3-100. ') 
+1

你應該瞭解break語句:https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops –

+0

您不需要將布爾值與「True」進行比較。它已經評估爲「真」或「假」。 – TigerhawkT3

回答

0

備選方法:在您的while循環中使用條件。

userName = '' 
userNumber = '' 

while not userName.isalpha(): 
    if userName: print('Choose a valid name!') 
    userName = input('Hello there, civilian! What is your name? ') 

print('It is nice to meet you, ' + userName + "! ") 

while not userNumber.isnumeric(): 
    if userNumber: print('Choose a number please! ') 
    userNumber = input('Please pick any number between 3-100. ') 

for i in range(0,int(userNumber) + 1,2): 
    print(i) 
+0

'string.isalpha()'在空字符串上的行爲如何?大概就好了,但是這不是很清晰。代碼 – slezica

+0

'str.isalpha()'/'isnumeric()'/'isalnum()'/'isdecimal()'它們都在空字符串上返回False。 – fferri

+0

謝謝!這有助於解決我的問題! – Kelvin

4

你永遠不會停止循環。有兩種方法可以做到這一點:或者改變循環條件(永遠爲while true循環),或者從內部改變break

在這種情況下,它與break簡單:

while True: 
    # The input() call should be inside the loop: 
    userName = input('Hello there, civilian! What is your name? ') 

    if userName.isalpha(): # you don't need `== True` 
     print('It is nice to meet you, ' + userName + "! ") 
     break # this stops the loop 
    else: 
     print('Choose a valid name!') 

第二循環有同樣的問題,同樣的解決方案和額外的修正。

相關問題