2015-01-26 651 views
-2
print ("Enter the object you are tyring to find.") 
print ("1 = Radius") 
print ("2 = Arch Length") 
print ("3 = Degree") 
print ("4 = Area") 
x = int(input("(1,2,3,4):")) 
if x == 1: 
    print ("You are finding the Radius.") 
    ra = int(input("Enter the arch length: ")) 
    rd = int(input("Enter the degree: ")) 
    rr = ra/math.radians(rd) 
    print ("The Radius is:",rr) 
if x == 2: 
    print ("You are finding the Arch Length.") 
    sr = int(input("Enter the radius: ")) 
    sd = int(input("Enter the degree: ")) 
    ss = math.radians(sd)*sr 
    print ("The Arch Length is:",ss) 

我正在做一個基本的數學程序,但我希望它可以無限重複。這不是完整的代碼,但我想爲其餘的「if」語句做同樣的事情。我希望它在每個功能完成後結束並重復回到第一行。謝謝!我如何讓我的python程序重新啓動到某一行?

+0

似乎工作爲一個循環 – aberna 2015-01-26 21:20:40

回答

2

將一個

while True: 

你想從重新啓動點;縮進所有以下每行四個空格。

在其中你想從剛過while重新啓動,添加語句的每一點:

continue 

正確縮進當然也。

如果您還希望爲用戶提供一個乾淨地結束程序的機會(例如,除了您現在提供的4之外的另一個選項),那麼在那個地方有一個條件語句(再次正確縮進):

if whateverexitcondition: 
    break 
+0

,而不是繼續它可能更好地使用elif結構 – 2015-01-26 21:24:00

+0

@DoodyP,「flat比嵌套更好」(在Python解釋器提示符處「import this」) - continue,break和return可以使代碼變平坦與嵌套測試相比,可以改進它。 – 2015-01-26 22:39:36

2

您將需要添加一種方法讓用戶退出並打破循環,但只要您願意,True將循環。

while True: 
    # let user decide if they want to continue or quit 
    x = input("Pick a number from (1,2,3,4) or enter 'q' to quit:") 
    if x == "q": 
     print("Goodbye") 
     break 
    x = int(x) 
    if x == 1: 
     print ("You are finding the Radius.") 
     ra = int(input("Enter the arch length: ")) 
     rd = int(input("Enter the degree: ")) 
     rr = ra/math.radians(rd) 
     print ("The Radius is:",rr) 
    elif x == 2: # use elif, x cannot be 1 and 2 
     print ("You are finding the Arch Length.") 
     sr = int(input("Enter the radius: ")) 
     sd = int(input("Enter the degree: ")) 
     ss = math.radians(sd)*sr 
     print ("The Arch Length is:",ss) 
    elif x == 3: 
     ..... 
    elif x == 4: 
     ..... 

如果你要使用一個循環中,您還可以驗證使用用戶輸入的唯一有效輸入一個try /除外:

while True: 
    try: 
     x = int(input("(1,2,3,4):")) 
    except ValueError: 
     print("not a number") 
     continue 
相關問題