我正在研究必须将“for”循环转换为“while”循环的示例,而这个让我很困惑。对我来说,问题是'for'循环被完美地设计为迭代字符串中的每个字符,然后可以轻松地将那个字符转换为'ord'以获得它的ASCII码。但是,当我尝试检索其中的“ord”部分时,将其转换为“while”循环会给我带来问题。我已经尝试使用 split() 并尝试使用索引查找每个字母,但到目前为止它还没有工作。
请注意,代码本身只是垃圾代码,不会产生任何有用的东西——它纯粹是为了练习“while”循环。谢谢!
提供的要转换为“while”循环的问题:
def convert(string):
"""take string and return an int that is the unicode version"""
num = 0
for char in string:
if ord(char) > 20:
num = ord(char) - 10
else:
num = ord(char) * 2
return num
print(convert('Test this string'))
我对“while”循环版本的尝试:
def convert(string):
"""take string and return an int that is the unicode version"""
char_value = string.split()
num = 0
char_index = 0
while char_index < len(string):
if ord(char_value[char_index]) > 20:
num = char_value - 10
else:
num = char_value * 2
char_index += 1
return num
print(convert('Test this string'))
编辑:这是根据 NPE 的建议改编的工作解决方案(以防万一初学者想看到完整的解决方案):
def convert(string):
"""take string and return an int that is the unicode version"""
num = 0
char_index = 0
while char_index < len(string):
char = string[char_index]
if ord(char) > 20:
num = ord(char) - 10
else:
num = ord(char) * 2
char_index += 1
return num
print(convert('Test this string'))