在以下代码中需要一些帮助,因为它进入无限循环并且不验证用户输入:get_offset是函数。刚编辑需要一些帮助,加密部分要在定义的函数中完成
def get_offset(offset):
while True:
value = (offset)
if value < 1:
print("")
if value > 94:
print("")
return offset
my_details = display_details()
get_choice = get_menu_choice()
print(my_details)
print(get_choice)
count = 10
while count > 0:
count -=1
encrypted = ""
choice = int(input("What would you like to do [1,2,3,4,5]: "))
while choice <1 and choice > 5:
print("Invalid choice, please enter either 1, 2, 3, 4 or 5.")
if choice == 1:
string_input = input("Please enter string to encrypt: ")
input_offset = get_offset(int(input("Please enter offset value (1 to 94): ")))
**for letter in string_input:
x = ord(letter)
encrypted += chr(x + input_offset)
if x < 32:
x += 94
if x > 126:
x -= 94
print(encrypted)**
答案 0 :(得分:0)
你必须在内部while循环中分配choice
个新值。这样,在反复迭代之前会考虑新的输入。
这应该可以解决问题:
while choice < 1 and choice > 5:
choice = int(input("Invalid choice, please enter either 1, 2, 3, 4 or 5."))
随机建议:如果您希望数据集严格等于[1,2,3,4,5],则应避免使用choice<1
和choice>5
。这使您的程序容易受到3.5
等无效输入的攻击。
相反,你应该这样做:
valid_inputs = [1, 2, 3, 4, 5]
choice = int(input("Pick a number from [1, 2, 3, 4, 5]:"))
while choice not in valid_inputs:
choice = int(input("Invalid choice, please enter either 1, 2, 3, 4 or 5."))
<rest of stuff here>
我从您的评论中了解到,在get_offset()
中,您希望用户输入介于1到94之间的值。如果用户输入的内容超出该范围,您需要一次又一次地提问。下面的代码应该做你想要的:
def get_offset():
# first, ask for a value.
offset = int(input("Enter a value between 1 and 94:"))
while offset < 1 and offset > 94:
# if the value is invalid, trap user inside this while loop.
# user will be stuck here (while loop will return true)
# until a valid input is received.
offset = int(input("Invalid input. Please enter a value between 1 and 94:"))
# if we proceed down here, it means we are over while loop
# and it implies that user has given us valid input. return value.
return offset
其次,在主要的while循环中,您可以像这样调用get_offset()
:
if choice == 1:
string_input = input("Please enter string to encrypt: ")
input_offset = get_offset()