elfresno
Posts: 37
Joined: Sun May 21, 2017 5:19 pm

very absurd problem with if

Mon Jan 29, 2018 3:34 pm

Hello everyone, I have a problem that I can not solve, I have the following part of code:

Code: Select all

       
        if data1[0] == "LOOPSYNC":


                try:
                        sync()
                        print usb
                        if usb == "2":
                                print "in"
the console shows 2, so usb is equal to 2. but does not equal usb to 2 in the if. so it never returns "in".

thanks

User avatar
piglet
Posts: 902
Joined: Sat Aug 27, 2011 1:16 pm

Re: very absurd problem with if

Mon Jan 29, 2018 3:57 pm

Try print ">"+usb+"<" to see if there's anything else in there. I've been stung with leading or trailing spaces in the past...

edit: is usb a number or a string? You're comparing it to "2" which is a string...

shadetree01010100
Posts: 29
Joined: Thu Oct 12, 2017 9:19 pm
Location: CO, USA
Contact: Website

Re: very absurd problem with if

Mon Jan 29, 2018 4:09 pm

I think piglet nailed it, since it's printing 2 but not evaluating to "2", what's probably happening is you're comparing a string to an integer.

Code: Select all

>>> 2 == 2
True
>>> 2 == "2"
False
Remove the quotes around "2" and try again.

rant:
for any new projects, you should really be using Python3. https://www.dataquest.io/blog/python-2-or-3/
Why you should learn Python 2:
You shouldn't. Very soon there will be no future security or bug fixes for Python 2.x, and your time is better spent learning 3.x.
/rant

elfresno
Posts: 37
Joined: Sun May 21, 2017 5:19 pm

Re: very absurd problem with if

Mon Jan 29, 2018 4:17 pm

ok. i try with

Code: Select all

       if data1[0] == "LOOPSYNC":


                try:
                        sync()
                        print ">"+usb+"<"
                        if usb == 2:
                                print "in"

and return

Code: Select all

>2
<

elfresno
Posts: 37
Joined: Sun May 21, 2017 5:19 pm

Re: very absurd problem with if

Mon Jan 29, 2018 4:39 pm

no , i want print in,

User avatar
Paeryn
Posts: 2632
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: very absurd problem with if

Mon Jan 29, 2018 4:42 pm

That looks like usb is a string of 2 (or more) characters where the first character is 2 and the last character is the newline (with possibly any number of spaces/tabs between them), e.g. "2\n"

You can strip whitespace from the front and end of a string with usb.strip() (strip() returns a string with the leading and trailing whitespace removed, it doesn't alter the original string).

Code: Select all

if usb.strip() == "2":
  print("in")
She who travels light — forgot something.

elfresno
Posts: 37
Joined: Sun May 21, 2017 5:19 pm

Re: very absurd problem with if

Mon Jan 29, 2018 5:23 pm

yes!! usb.strip work perfect thanks

Return to “Python”