2017-07-06 44 views
-2

我創建了一個程序,您可以在其中擲骰子或查找數字的平方根。這些選項可以用數字1和2來切換。無論何時,只要我想找到數字的平方根,它就會給出我想要的數字的平方根和2的平方根。我該如何解決這個問題?代碼如下: 請忽略縮進錯誤,堆棧溢出是給我一個艱難的時間把代碼Python中數字的平方根

from random import randint 
import math 

UserInput = int(input("To Roll A Dice, Type One. To Find The Square Root Of A 
Number, Press 2 ")) 
    while True: 
     if UserInput == 1: 
      print (randint(1, 6)) 

     if UserInput == 2: 
      print(math.sqrt(int(input("What Number Would You Like To Find The Square Root Of? ")))) 

,這是我的結果時,我想找到16的平方根:

To Roll A Dice, Type One. To Find The Square Root Of A Number, Press 2 2 
What Number Would You Like To Find The Square Root Of? 16 
4.0 
1.4142135623730951 
+0

解決您的壓痕。 – Barmar

+1

我無法重現此行爲。你有沒有檢查你的密碼? –

+1

我跑的腳本,它看起來很好,所以它可能是縮進問題。確保兩個if語句彼此一致,並考慮將格式更改爲if/elif/else – ginginsha

回答

2

您的代碼的主要問題是評論中所述的縮進問題。另外,我認爲沒有必要進行無限循環,因爲它會重複滾動並重復平方根,除非這是您的目標。 這裏是我的代碼:

from random import randint 
import math 

UserInput = int(input("To Roll A Dice, Type One. To Find The Square Root Of A Number, Press 2 ")) 
if UserInput == 1: 
    print (randint(1, 6)) 

elif UserInput == 2: 
    print(math.sqrt(int(input("What Number Would You Like To Find The Square Root Of? ")))) 

也就是說,除非你要反覆詢問用戶輸入在這種情況下,把while循環創建用戶輸入變量的上面。

編輯:如果你確實想重新使用性,然後使用def使這一功能,並具有以下代碼

while True: 
    play = input("Do you want to play? y/n") 
    if play == "y": 
     function_name() 
    elif play == "n": 
     break 
+1

非常感謝!這絕對有幫助 –