Python: creating a loop with an integer converted to a string

12,951

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

The way you are assigning x with x = input("Enter your PIN: "), x is already a string. The for loop should be used to convert each character to an integer before returning the weighted sum. Here is one way using a list to store the integers:

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))
Share:
12,951
Erica
Author by

Erica

Updated on June 04, 2022

Comments

  • Erica
    Erica almost 2 years

    I'm brand new to Python as of a few weeks ago for a class I am taking. I am currently writing a program that is designed to take a four digit integer, take the absolute differences of each number, and then sum them. Meaning, you enter a four digit PIN, the program takes the absolute values of (number 1- number 2), (2-3), and (3-4) and then sums them and prints the sum.

    I am supposed to write a for loop in order to do this after converting the integer to a string.

    I was told to structure the loop using for char in value: but I am confused as to how to set this up. I understand basic slicing, and I assume I need to use that in my answer. This is what I have so far for my code:

    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
    

    The loop is the part that is messing me up. I know there’s other ways to solve this without using a loop, but for my assignment I am supposed to.

    • thatrockbottomprogrammer
      thatrockbottomprogrammer over 6 years
      You're converting the variable x to string, but you're not storing it back into x. Try x = str(x)
    • MooingRawr
      MooingRawr over 6 years
      a,b,c,d=str(x) no need to store x again if you aren't using it