我是Python的新手,我不知道为什么,但是if,elif在下面的代码中,我没有按照预期的那样工作.然而,
当我输入1到7时它完美地工作
当我输入0 8或9时它完美地工作(它说"再试一次")
如果我输入10到69,100到任何数字,它不起作用
当我说它不起作用我的意思是打印
my_shape_num = h_m.how_many()
Run Code Online (Sandbox Code Playgroud)
但我不知道为什么.如果选择不在1到7之间,它必须停止
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
Run Code Online (Sandbox Code Playgroud)
编辑:好的,排序:
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
Run Code Online (Sandbox Code Playgroud)
字符串按字典顺序进行比较:'10'大于'1'但小于'7'.现在考虑这段代码:
elif (choice >= '1' and choice <= '7'):
Run Code Online (Sandbox Code Playgroud)
除了接受'7',这将接受任何字符串开头1,2,3,4,5或6.
要修复,choice请在测试后立即转换为整数'x',然后使用整数比较.
| 归档时间: |
|
| 查看次数: |
2585 次 |
| 最近记录: |