Python:创建一个将整数转换为字符串的循环

标签 python for-loop

几周前我参加的类(class)对 Python 来说还是个新手。我目前正在编写一个程序,旨在获取一个四位整数,获取每个数字的绝对差,然后将它们相加。意思是,您输入一个四位数的 PIN,程序会取(数字 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

循环是让我困惑的部分。我知道还有其他方法可以在不使用循环的情况下解决这个问题,但对于我的作业,我应该这样做。

最佳答案

I was told to structure the loop using for char in value: but I am confused as to how to set this up.

您使用 x = input("Enter your PIN: ") 分配 x 的方式,x 已经是一个字符串。在返回加权和之前,应使用 for 循环将每个字符转换为整数。这是使用列表存储整数的一种方法:

def weight(value):
    int_values = []  # Create an empty list to store the integers.
    for char in value:
        int_values.append(int(char))  # Converts char to int and adds to list.
    return abs(int_values[0] - int_values[1]) + abs(int_values[1] - int_values[2]) + abs(int_values[2] - int_values[3])


pin = ''
while len(pin) != 4 or not pin.isdigit():  # Make sure PIN is 4 digits.
    pin = input("Enter your PIN: ")
pin_weight = weight(pin)
print('Weight of {} is {}'.format(pin, pin_weight))

关于Python:创建一个将整数转换为字符串的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48525119/

相关文章:

python - 将图像从 [-1; 1]到[0; 255]

python - sqlite 属性execute是只读的

python - 与 uWSGI 一起使用时,模块级变量是否安全?

python - 绘制 groupby pandas 的 groupby

python - 提交表单,并在python中使用mechanise获取结果

python - 如何制作碰撞 mask ?

javascript数组和循环

javascript - 如何使用javascript在选择列表中创建从1到100的选项?

c - 如何在 C 中使用嵌套 for 循环获得以下输出?

java - 有没有办法在java中从末尾开始增强的for循环