我是新來的Python,我不知道爲什麼,但下面的代碼中的if
,elif
不能像我期望的那樣工作。然而,if,elif not working as expected expected
它完美,當我鍵入1至7
它完美的作品,當我鍵入0 8或9(它說: 「重試」)
它不工作如果我輸入10到69,100到任何數量的
當我說這是行不通的我的意思是它打印
my_shape_num = h_m.how_many()
但我不知道爲什麼。它必須停止,如果選擇的是編輯沒有和7
之間1
def main(): # Display the main menu
while True:
print
print " Draw a Shape"
print " ============"
print
print " 1 - Draw a triangle"
print " 2 - Draw a square"
print " 3 - Draw a rectangle"
print " 4 - Draw a pentagon"
print " 5 - Draw a hexagon"
print " 6 - Draw an octagon"
print " 7 - Draw a circle"
print
print " X - Exit"
print
choice = raw_input(' Enter your choice: ')
if (choice == 'x') or (choice == 'X'):
break
elif (choice >= '1' and choice <= '7'):
my_shape_num = h_m.how_many()
if (my_shape_num is None):
continue
d_s.start_point() # start point on screen
if choice == '1':
d_s.draw_triangle(my_shape_num)
elif choice == '2':
d_s.draw_square(my_shape_num)
elif choice == '3':
d_s.draw_rectangle(my_shape_num)
elif choice == '4':
d_s.draw_pentagon(my_shape_num)
elif choice == '5':
d_s.draw_hexagon(my_shape_num)
elif choice == '6':
d_s.draw_octagon(my_shape_num)
elif choice == '7':
d_s.draw_circle(my_shape_num)
else:
print
print ' Try again'
print
:好吧,排序:
choice = raw_input(' Enter your choice: ')
if (choice == 'x') or (choice == 'X'):
break
try:
choice = int(choice)
if (1 <= choice <= 7):
my_shape_num = h_m.how_many()
if (my_shape_num is None):
continue
d_s.start_point() # start point on screen
if choice == 1:
d_s.draw_triangle(my_shape_num)
elif choice == 2:
d_s.draw_square(my_shape_num)
elif choice == 3:
d_s.draw_rectangle(my_shape_num)
elif choice == 4:
d_s.draw_pentagon(my_shape_num)
elif choice == 5:
d_s.draw_hexagon(my_shape_num)
elif choice == 6:
d_s.draw_octagon(my_shape_num)
elif choice == 7:
d_s.draw_circle(my_shape_num)
else:
print
print ' Number must be from 1 to 7!'
print
except ValueError:
print
print ' Try again'
print
謝謝。我無法弄清楚如何處理其他不是數字的輸入。 – emre
我已經做到了這一點:'選擇的raw_input =( '請輸入您的選擇:') 如果(選擇== 'X')或(選擇== 'X'): 突破 嘗試: 選擇= INT (選擇) 如果(1 <=選擇<= 7): 如果選擇== 1: d_s.draw_triangle(my_shape_num) 否則: 打印 打印 '!數量必須是從1到7' 打印 除了ValueError異常: 打印 打印「再試一次」 print' – emre
@ baris22:很難讀粘貼到註釋中的代碼,但你是正確的軌道上:我想嘗試'INT(選擇) '趕上'ValueError'是要走的路。 – NPE