user1978826
user1978826

Reputation: 203

Coverting int to string and checking postion to see if it matches a value

I am trying to do some simple Python, which allows the user to enter a 6 digit number into the command line; my code then needs to check the values of the first and sixth digit of the number entered.

The value entered is stored in a variable named uinumber, I then check using an if statement to check if the values at these locations match. As shown below:

 if uinumber[1] == 5 and uinumber[6] == 0:

This doesn't seem to do anything. I have also tried converting the number entered to a string and then doing the check as show below, but this causes the same issue.

 uinumber_string = str(uinumber)
  if uinumber_string[1] == 5 and uinumber[6] == 0:

This seems to cause the same issue; what is the right way to do this?

Thanks!

Upvotes: 0

Views: 90

Answers (1)

ashastral
ashastral

Reputation: 2848

You're right about needing to cast the inputted number to a string, but you then need to compare it to a string as well.

Additionally, since you mentioned a 6-digit number, the correct indices are probably [0] and [5] and not [1] and [6], as sequences in Python (and most other programming languages) are zero-indexed.

And on one last note, you wrote uinumber[6] by accident instead of uinumber_string[6].

uinumber_string = str(uinumber)
if uinumber_string[0] == "5" and uinumber_string[5] == "0":
    # Do something

Upvotes: 4

Related Questions