int positionToInsertRow= 2;// Get the position that you want
dataTable.Rows.InsertAt(drToAdd, positionToInsertRow);
,则退出该程序。drToAdd
并再次询问第一个数字。positionToInsertRow
并询问第二个数字。'q'
作为第二个号码,请退出该程序。"Please enter a number"
并再次询问第二个数字int()
。这就是我所做的:
'q'
答案 0 :(得分:1)
bruno和Matthias指出的最明显的改进是将用户输入逻辑分解为自己的功能。这样的事情可能会这样:
def get_user_input():
while True:
response = input('Please enter a number: ')
if response == 'q':
return False, None
try:
return True, int(response)
except ValueError:
continue
def main():
print('Give me two numbers and I will divide them.')
print('Enter \'q\' to quit.')
continue_program, first_number = get_user_input()
if not continue_program:
return
continue_program, second_number = get_user_input()
if not continue_program:
return
try:
quotient = first_number // second_number
print('{} / {} = {}'.format(first_number, second_number, quotient))
except ZeroDivisionError:
print('You cannot divide by zero')
if __name__ == '__main__':
main()
示例运行(快乐路径)
Give me two numbers and I will divide them.
Enter 'q' to quit.
Please enter a number: 10
Please enter a number: 6
10 / 6 = 1
答案 1 :(得分:0)
有用的东西:sentinel到这种场景的iter()值
import sys
def get_number(display_msg=""):
sys.stdout.write(display_msg) # OR partial function can be used.
for response in iter(input, 'q'): # sentinel
try:
return int(response)
except ValueError:
continue
first_number = get_number(display_msg="Please enter 1st the number: ")
second_number = get_number(display_msg="Please enter 2nd the number: ")
if isinstance(first_number, int) and isinstance(second_number, int):
#..do something with first_number, second_number