def函数中的加密代码以python编写 [英] Encryption code in def function to be written in python
问题描述
在以下代码中需要一些帮助,因为它进入了无限循环并且不验证用户输入:get_offset是函数.刚编辑过的需要在定义的函数中完成加密部分的帮助
need some help in the following code as it goes into infinite loop and does not validate user input: the get_offset is the function. Just edited need some help with the encryption part to be done in a function defined
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)**
推荐答案
您必须在内部while循环内分配choice
新值.这样,在一次又一次地迭代之前,将考虑新的输入.
you have to assign choice
new value inside inner while loop. this way, new input is considered before iterating again and again.
这应该可以解决问题:
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
)的攻击.
A random advice: If you want to keep dataset strictly equal to [1,2,3,4,5], you should avoid choice<1
and choice>5
. This makes your program vulnerable to invalid inputs such as 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之间的值.如果用户输入的值超出该范围,则您想一次又一次地提问.下面的代码应满足您的要求:
What I understood from your comments is that, in get_offset()
, you want user to type a value between 1 and 94. If user enters something out of that range, you want to ask question again and again. The code below should do what you want:
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
第二,在main while循环中,您可以像这样调用get_offset()
:
Secondly, inside main while loop, you can call get_offset()
like this:
if choice == 1:
string_input = input("Please enter string to encrypt: ")
input_offset = get_offset()
这篇关于def函数中的加密代码以python编写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!