几周前,我刚上过Python的一门课。我现在正在写一个程序,它的设计是取一个四位数的整数,取每个数的绝对差,然后求和。也就是说,输入一个四位数的管脚,程序获取(数字1-数字2),(2-3)和(3-4)的绝对值,然后对它们求和并打印总和。
我应该写一个for循环,以便在将整数转换为字符串之后执行此操作。
有人告诉我使用for char in value构造循环:但是我不知道如何设置它。我了解基本的切片,我想我需要在我的答案中使用它。
这就是我目前为止的代码:def main():
print("This program is designed to determine the weight of a four-digit PIN by calculating the sum of the absolute difference between each digit.")
# Prompt user for PIN
x = input("Enter your PIN: ")
# Call the weight function providing the four digit pin as an argument
weight(x)
# Weight function
def weight(x):
# Convert integer to string
str(x)
# Initialize variables
a, b, c, d = x
# Setup for a loop that uses digits as sequence, sum differences between each digit in integer
# Print sum
循环是把我搞糊涂的部分。我知道有其他方法可以不用循环来解决这个问题,但是对于我的作业我应该这样做。