Home > OS >  How do i scan each character in a user input and compare it to the second integer they input?
How do i scan each character in a user input and compare it to the second integer they input?

Time:10-21

probably my last post for a while but I've been having some trouble with another one of my codes.

so for context, the program that I want to make is that the user inputs a 3 character integer and a single integer separated by a space.

the code:

a,b = input().split()
if a[0] and a[1] and a[-1] == b:
    print("Jackpot!")
else:
    print("Nah")

example of an input:

777 7

the output it gives if each character in the first input is the same as the second in the same line.

Jackpot!

another example of an input:

177 7

the output if one of the characters in the first input isn't the same as the second input:

Nah

So far so good, the code i have currently reads each character in the input EXCEPT the second character. so if i input '177 7' it returns "Nah" as expected, same as if I input 771 7. But if I input for example:

717 7 

it returns "Jackpot!" when it shouldn't. Any advice on what I could do? How do i let my code read the 2nd character in the integer so that it should return the appropriate response?

CodePudding user response:

This should do the trick:

all([b == int(digit) for digit in str(a)])

This will basically check that all digit are equal to the given digit b.

CodePudding user response:

I am not sure what logic you have used. But to process this you can use sets. For example ->

set(string2) == set(string1)

CodePudding user response:

Due to operator precedence, equality is checked for the last integer character only.

# Equality checked for a[-1] == b only
if a[0] and a[1] and a[-1] == b:
    print("Jackpot!")

For checking all the three integer characters, use:

if (a[0] == b) and (a[1] == b) and (a[-1] == b):
    print("Jackpot!")
  • Related