Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
BigRedDot
Mar 6, 2008

Better make sure it is callable, too:

Python code:
if x is not None and hasattr(x, '__len__') and hasattr(x.__len__,'__call__') and len(x) > 0:
    pass

Adbot
ADBOT LOVES YOU

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

NtotheTC posted:

I'm not going to get into a community best practice slap fight. I just view this in a similar light to:

code:
x = None

if x:
    pass

# vs

if x is None:
    pass
(the bottom one is more pythonic)

You're more than welcome to overrule me on this as I imagine you're more experienced with python than I am. I don't think verboseness is a bad thing to learn when it enhances readability though.
If all you cared about was whether x was None than yes, the second option is more explicit and better by some definition of the word better.

As the last two posts point out, it's not that simple.

Yes, it's more explicit to verbosely test every possible thing x might be, or you could just use Python's rules for boolean types and do if x:.

It's not as simple as a black and white readability and explicitness versus how verbose you are. If you can cut the amount of verboseness by 50% while damaging explicitness by 5%, is it worth it? Most python programmers have some inate ratio in that question that they're willing to accept, and most python programmers have accepted that using if x: and the simple rules for boolean coercion are a fine tradeoff.

If your sensitivities on that ratio are such that you don't want to do it, that's fine, but just be aware of the tradeoffs you're making when you make these kinds of decisions.

(I have no idea if I'm right when I say "most", I can just go by the small percentage of existing python code that I have read and assume that my sample size is large and representative enough)

QuarkJets
Sep 8, 2008

NtotheTC posted:

I'd avoid doing this. Using the plain if statement on variables that aren't a bool strikes me as a hideous pattern despite it being perfectly legal for strings/dicts/lists/etc. You'll occasionally get nasty unexpected behaviour, not to mention it's very un-pythonic in terms of explicity. I dislike the "if len()" one too, however you'll never convince people not take shortcuts like this with dynamic-typed languages.

Apparently pep8 suggests using the fact that sequences are False if their length is 0 rather than explicitly checking for 0 length. I know that pep8 is not the end-all for Python style and you should do whatever the gently caress you want, but this seems like a good feature with no consequences aside from subjective differences in readability.

Brushing up, apparently
code:
if somebool is True
is 'worse' than
code:
if somebool == True
? Why is this? Obviously you should just use the fact that somebool is a bool and not compare to True at all, I'm just wondering why they they decided that using 'is' was worse than '==' in this case

QuarkJets fucked around with this message at 19:06 on Aug 8, 2013

Dren
Jan 5, 2001

Pillbug
The way I read the requirements the program only needs to care about the first character of the word.

quote:

The program is supposed to ask for a word and if it start with a vowel it should print vowel. If the word doesn't start with a vowel it should print consonant. The problem I'm having is no matter what word I put in it, it print 'consonant'.

Also, raw_input always returns a string unless there's an EOF character (and I don't care to worry about that) so no need to check for None.

Here's a version of the program that takes care to make sure the user enters something but only cares about the first letter of the input.

Python code:
import sys
import string
import time
import random
import itertools

word_prompt = lambda: raw_input('Please enter a word: ')

word = word_prompt()

while len(word) == 0:
    print >> sys.stderr, 'ERROR: word has no length'
    word = word_prompt()

if word[0] in 'aeiou':
    print 'vowel'
elif word[0] in string.letters:
    print 'consonant'
else:
    print >> sys.stderr, 'FATAL ERROR',
    for x in (y if y else iter([]).next() for y in (random.randint(*(0x0, 0xFF)) for n in itertools.count())):
        sys.stderr.write(chr(x))
        time.sleep(0.1 / x)
    sys.stderr.write('\n')
Don't enter a non-letter.

Dren fucked around with this message at 19:07 on Aug 8, 2013

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

QuarkJets posted:

Brushing up, apparently
code:
if somebool is True
is 'worse' than
code:
if somebool == True
? Why is this? Obviously you should just use the fact that somebool is a bool and not compare to True at all, I'm just wondering why they they decided that using 'is' was worse than '==' in this case

is tests identity. It tests if two things are the same thing.
== tests equality. It tests if two things evaluate to the same value.

code:
In [1]: a = 'nerds'

In [2]: b = ''.join(['n', 'e', 'r', 'd', 's'])

In [3]: c = a

In [4]: a is b
Out[4]: False

In [5]: a is c
Out[5]: True

In [6]: a == b
Out[6]: True

In [7]: a == c
Out[7]: True
So, to start with == is more explicit about the actual thing you are trying to do. You don't care about if a is the same object as the boolean literal True, you care about whether they evaluate to the same thing.

Secondly, and I'm not as sure about myself here, I think the fact that a == True and a is True both give you the same result is implementation-specific. In other words, I think, that the next version of CPython could change that, or another implementation, like IronPython for example, might return False when you ask it to evaluate a is True, because conceptually a with the value True is a different object from True.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What do you guys typically use for a production stack? apache2? gunicorn? nginx out in front of those? How do you handle deployments to a production environment?

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

fletcher posted:

What do you guys typically use for a production stack? apache2? gunicorn? nginx out in front of those? How do you handle deployments to a production environment?

@jesseenoller (the OP iirc) asked exactly this on twitter today, general answer seems to be:

varnish -> nginx -> gunicorn/uwsgi -> pypy if possible -> pgbouncer -> postgres

All being automated by Chef/Puppet/Salt/Ansible/Shell Scripts/Trained Monkeys.


Or to just use a PaaS provider (Heroku).


edit: It just struck me how many giants of Python have actually posted in this thread.

deimos fucked around with this message at 19:50 on Aug 8, 2013

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Thermopyle posted:

Secondly, and I'm not as sure about myself here, I think the fact that a == True and a is True both give you the same result is implementation-specific. In other words, I think, that the next version of CPython could change that, or another implementation, like IronPython for example, might return False when you ask it to evaluate a is True, because conceptually a with the value True is a different object from True.

IronPython does have single global True and False objects which surprises me a bit because it doesn't do that with strings and numbers like CPython will. I do think you're right about it being platform specific, though, because I can easily imagine an interpreter with a braindead-simple bool class that doesn't memoize itself.

SYSV Fanfic
Sep 9, 2003

by Pragmatica

Thermopyle posted:


Secondly, and I'm not as sure about myself here, I think the fact that a == True and a is True both give you the same result is implementation-specific. In other words, I think, that the next version of CPython could change that, or another implementation, like IronPython for example, might return False when you ask it to evaluate a is True, because conceptually a with the value True is a different object from True.

I always just thought that True and False were immutable. So if you assign a to five and then ask if a is 5, the result should be true, because 5 is an immutable object. Same with strings.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

keyvin posted:

I always just thought that True and False were immutable. So if you assign a to five and then ask if a is 5, the result should be true, because 5 is an immutable object. Same with strings.

5 might be immutable but it doesn't make it a reference to the same object, you can have many ints with the same value, this is strictly implementation dependent..

This is only true for -5 to 256 in CPython btw, try it with anything above and is will fail.


ej.
code:
>>> x = 257
>>> x is 257
False
>>>

deimos fucked around with this message at 22:03 on Aug 8, 2013

Haystack
Jan 23, 2005





keyvin posted:

I always just thought that True and False were immutable. So if you assign a to five and then ask if a is 5, the result should be true, because 5 is an immutable object. Same with strings.

Under that logic, 0 would always equal True (0 is immutable!) and lists would always equal false.

duck monster
Dec 15, 2004

Thermopyle posted:

Or just do it the way the whole Python community does.

I'd argue that
code:
if x not in ['', None]:
is technically more correct then measuring the length of something that might not exist.

If len(None) = 0 , thats a convenience but its not necessarily coherent (It SHOULD raise an exception).

SYSV Fanfic
Sep 9, 2003

by Pragmatica

Haystack posted:

Under that logic, 0 would always equal True (0 is immutable!) and lists would always equal false.

well, no. I didn't realize larger numbers didn't work, but I thought python just created one of an immutable object and tried to not make duplicates in memory, because if an object can't change then why would you create multiple string objects that all contained the same data. But now I see it doesn't work with tuples at all so I learned something neat!

How does python recognize that two string objects are the same with the is operator? Does it actually compare the address (sorry don't know the right term as I was a C programmer) or does it just do like a strcmp for equality?

Edit: Using ID on different string objects show that they do have the same address. Is this also implementation specific?

Edit: The above should say that assigning two different variables to the same string at different points of execution results in them pointing to the same string object

SYSV Fanfic fucked around with this message at 02:04 on Aug 9, 2013

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

keyvin posted:

I always just thought that True and False were immutable. So if you assign a to five and then ask if a is 5, the result should be true, because 5 is an immutable object. Same with strings.

True and False are immutable in sane versions of Python.
Python code:
Python 2.7.4 (default, Apr 19 2013, 18:28:01) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True = False
>>> True
False
>>> False = not True
>>> False
True
Python code:
Python 3.3.1 (default, Apr 17 2013, 22:30:32) 
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> True = 0
  File "<stdin>", line 1
SyntaxError: assignment to keyword
(maybe stealth) EDIT:

keyvin posted:

How does python recognize that two string objects are the same with the is operator? Does it actually compare the address (sorry don't know the right term as I was a C programmer) or does it just do like a strcmp for equality?

Edit: Using ID on different string objects show that they do have the same address. Is this also implementation specific?

If they have the same ID, they aren't different string objects. Where did these strings come from? Note that the Python interpreter interns string literals and reuses objects if possible, even in the interactive interpreter.

Python code:
# strings.py
str1 = 'beep'
str2 = 'boop'
str3 = 'beep'
Python code:
>>> import strings
>>> strings.str1 is strings.str3
True
>>> beep = 'beep'
>>> beep is strings.str1
True
>>> beep[:] is strings.str1
True
>>> b2 = beep[0] + beep[1:]
>>> b2
'beep'
>>> b2 is strings.str1
False

Lysidas fucked around with this message at 02:04 on Aug 9, 2013

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

deimos posted:

@jesseenoller (the OP iirc) asked exactly this on twitter today, general answer seems to be:

varnish -> nginx -> gunicorn/uwsgi -> pypy if possible -> pgbouncer -> postgres

All being automated by Chef/Puppet/Salt/Ansible/Shell Scripts/Trained Monkeys.


Or to just use a PaaS provider (Heroku).


edit: It just struck me how many giants of Python have actually posted in this thread.

I've been meaning to learn how to use chef. Been playing around with it for the past couple hours and it is really neat. One question though, and this may not be the right thread for it, but how do I get the code for my app onto the server using chef? The code is in a remote git repo...should I use git to download the code in my chef recipe? I'm sure there's a million different ways this could be answered, just looking for something basic and sensible for now.

edit: This sounds like the answer to my question: http://docs.opscode.com/resource_deploy.html

fletcher fucked around with this message at 06:37 on Aug 9, 2013

Omnomnomnivore
Nov 14, 2010

I'm swiftly moving toward a solution which pleases nobody! YEAGGH!
Taking advantage of "empty sequences are false" goes right out the door if you use numpy:

code:
>>> import numpy
>>> a = numpy.arange(10)
>>> if a:
...     print "a is not empty"
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Rather than using different idioms for code that uses arrays and code that uses lists, (or, occasionally, works with both), I just always write 'if len(x)' or 'if len(x) > 0'.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
For a personal project I need to be able to do some basic linear algebra (like solving systems of linear equations), but it needs to be symbolic, at least up to a point. So for example, it can't require that everything is a floating point number, or anything like that. I might need to write a class whose members act like elements of the field \mathbb{Q}[\sqrt{2}] (the set of all numbers of the form p + q√2 where p and q are rational numbers) and apply it to that.

I started writing my own basic Matrix class. Is there a significantly better way of doing things I should be looking at? If the alternatives are all large and ponderous systems that I'd have to learn then I'll probably just finish my own Matrix class (it is quite fun) but I thought I would check.

QuarkJets posted:

Brushing up, apparently
code:
if somebool is True
is 'worse' than
code:
if somebool == True
? Why is this? Obviously you should just use the fact that somebool is a bool and not compare to True at all, I'm just wondering why they they decided that using 'is' was worse than '==' in this case

You shouldn't use if somebool == True: because that has the same effect as if somebool: which is more straightforward and idiomatic.

There is a case for if somebool is True because True and False, like None, are singleton objects and you might sometimes want to use True as a special value (e.g. for function arguments) (there are good arguments against doing this too though)

accipter
Sep 12, 2003

Hammerite posted:

For a personal project I need to be able to do some basic linear algebra (like solving systems of linear equations), but it needs to be symbolic, at least up to a point. So for example, it can't require that everything is a floating point number, or anything like that. I might need to write a class whose members act like elements of the field \mathbb{Q}[\sqrt{2}] (the set of all numbers of the form p + q√2 where p and q are rational numbers) and apply it to that.

I started writing my own basic Matrix class. Is there a significantly better way of doing things I should be looking at? If the alternatives are all large and ponderous systems that I'd have to learn then I'll probably just finish my own Matrix class (it is quite fun) but I thought I would check.

Have you considered using SymPy?

http://docs.sympy.org/0.6.7/tutorial.html#linear-algebra
http://docs.sympy.org/0.6.7/modules/mpmath/matrices.html

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

duck monster posted:

I'd argue that
code:
if x not in ['', None]:
is technically more correct then measuring the length of something that might not exist.

If len(None) = 0 , thats a convenience but its not necessarily coherent (It SHOULD raise an exception).

I agree.

I was saying to do if x:, which while also not completely coherent, is not completely incoherent and is also less verbose and it's widely used.

Really, though, the whole issue is a molehill that is already worth less than the amount of words I've typed about it.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Trying to set up a new machine but I'm running into an error when I try to run the south migration. It seems to work fine on my dev machine running Mint, but when my chef recipe gets to this step on Ubuntu Server 12.04 it hits an error. Any ideas?

code:
$ PYTHONPATH=/var/www/myapp; DJANGO_SETTINGS_MODULE=myapp.settings /path/to/venv/bin/python /var/www/myapp/manage.py migrate
Running migrations for myapp:
 - Migrating forwards to 0001_initial.
 > myapp:0001_initial
TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK
edit: Fixed it - it was a database permissions issue

fletcher fucked around with this message at 20:46 on Aug 9, 2013

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

fletcher posted:

Trying to set up a new machine but I'm running into an error when I try to run the south migration. It seems to work fine on my dev machine running Mint, but when my chef recipe gets to this step on Ubuntu Server 12.04 it hits an error. Any ideas?

code:
$ PYTHONPATH=/var/www/myapp; DJANGO_SETTINGS_MODULE=myapp.settings /path/to/venv/bin/python /var/www/myapp/manage.py migrate
Running migrations for myapp:
 - Migrating forwards to 0001_initial.
 > myapp:0001_initial
TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK
edit: Fixed it - it was a database permissions issue

For future reference, there's a Django thread.

QuarkJets
Sep 8, 2008

Omnomnomnivore posted:

Taking advantage of "empty sequences are false" goes right out the door if you use numpy:


Rather than using different idioms for code that uses arrays and code that uses lists, (or, occasionally, works with both), I just always write 'if len(x)' or 'if len(x) > 0'.

Arrays support broadcasting, so it really is ambiguous. Whether an array is True is ambiguous; you might be asking whether the array has some nonzero length or you might be asking for the operation to return an array of True/False values. You also might be asking whether any of the elements are true, or all of them, as the suggestion in the exception implies. This kind of thing isn't a problem for strings or lists, since they don't support broadcasting.

Hammerite posted:

You shouldn't use if somebool == True: because that has the same effect as if somebool: which is more straightforward and idiomatic.

I'm aware of that, and it's irrelevant to my question of why PEP8 says that 'is' is worse than '==' if you compare a bool to True. PEP8 also suggests that you should always just do if somebool, but that's for obvious reasons.

QuarkJets fucked around with this message at 09:42 on Aug 10, 2013

Crosscontaminant
Jan 18, 2007

The other reason to use is rather than == when testing against None is operator overloading.

Python code:
class PerverseExample(int):
    def __eq__(self, other):
        return True

foo = PerverseExample(3) # definitely not None
if foo == None:
    print("oh no what is happening")
Something similar might well apply for True and False - None is a singleton object, but I don't know offhand how those work since they weren't keywords until Python 3.

e: woops this was so last page

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I want to write a thing which will do a thing when a remote server tells it to do it. Probably over HTTP.

Nothing complex. One server telling another server "take this string and The Thing with it".

What's my options for something light weight and simple and secure (so not just anyone can say "hey, do The Thing")?

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

Thermopyle posted:

I want to write a thing which will do a thing when a remote server tells it to do it. Probably over HTTP.

Nothing complex. One server telling another server "take this string and The Thing with it".

What's my options for something light weight and simple and secure (so not just anyone can say "hey, do The Thing")?

Try using a simple web server framework, like web.py or Flask.

More info at http://stackoverflow.com/questions/713847/recommendations-of-python-rest-web-services-framework

QuarkJets
Sep 8, 2008

Crosscontaminant posted:

The other reason to use is rather than == when testing against None is operator overloading.

Python code:
class PerverseExample(int):
    def __eq__(self, other):
        return True

foo = PerverseExample(3) # definitely not None
if foo == None:
    print("oh no what is happening")
Something similar might well apply for True and False - None is a singleton object, but I don't know offhand how those work since they weren't keywords until Python 3.

e: woops this was so last page

Is it possible to overload 'is'?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
No.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

BeefofAges posted:

Try using a simple web server framework, like web.py or Flask.

More info at http://stackoverflow.com/questions/713847/recommendations-of-python-rest-web-services-framework

Yeah, I'll just do that if there's nothing more purpose-built for this.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


xmlrpclib is built in and standard and easy as gently caress to use. You can even use it inside apache if you don't want to write your own daemon.

deedee megadoodoo fucked around with this message at 21:34 on Aug 10, 2013

digitalcamo
Jul 11, 2013
Doing some more lessons and I have run into another problem.

code:
def shut_down(s):
    if s == ('Yes') or ('YES') or ('yes'):
	print "Shutting down."
        return "Shutting down."
    elif s == ('NO') or ('no') or ('No'):
        return "Shutdown aborted!"
    else:
        return "Sorry, I didn't understand you."
shut_down('YES')
I keep getting IndentionError: unident does not match any outer indentation level. This does not seem to make sense to me as I indented the exact same for print and return. However when I take the return line out it works just fine. Can you not print and return in the same if/else condition?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

digitalcamo posted:

Doing some more lessons and I have run into another problem.

code:
def shut_down(s):
    if s == ('Yes') or ('YES') or ('yes'):
	print "Shutting down."
        return "Shutting down."
    elif s == ('NO') or ('no') or ('No'):
        return "Shutdown aborted!"
    else:
        return "Sorry, I didn't understand you."
shut_down('YES')
I keep getting IndentionError: unident does not match any outer indentation level. This does not seem to make sense to me as I indented the exact same for print and return. However when I take the return line out it works just fine. Can you not print and return in the same if/else condition?

I copy/pasted what you have there and it worked fine. I forget, what text editor are you using?

PS: A better way of testing for different capitalization is to do it like:

Python code:
if s.lower() == 'yes':
    blahblahblah

FoiledAgain
May 6, 2007

digitalcamo posted:

Doing some more lessons and I have run into another problem.

code:
def shut_down(s):
    if s == ('Yes') or ('YES') or ('yes'):
	print "Shutting down."
        return "Shutting down."
    elif s == ('NO') or ('no') or ('No'):
        return "Shutdown aborted!"
    else:
        return "Sorry, I didn't understand you."
shut_down('YES')
I keep getting IndentionError: unident does not match any outer indentation level. This does not seem to make sense to me as I indented the exact same for print and return. However when I take the return line out it works just fine. Can you not print and return in the same if/else condition?

I don't know about that error, but this code won't do what you are expecting. For example:

code:
s = 'Quack'
if s == 'Yes' or 'YES':
    print 1
This will print out 1, because the bit after the or is a string, and non-empty strings evaluate to True. What you need to do is this: if s == 'YES' or s == 'yes' or s == 'Yes'. But really if would be shorted to do s = s.lower() and then just check the lowercase versions.

Dominoes
Sep 20, 2007

digitalcamo posted:

Doing some more lessons and I have run into another problem.

code:
def shut_down(s):
    if s == ('Yes') or ('YES') or ('yes'):
	print "Shutting down."
        return "Shutting down."
    elif s == ('NO') or ('no') or ('No'):
        return "Shutdown aborted!"
    else:
        return "Sorry, I didn't understand you."
shut_down('YES')
I keep getting IndentionError: unident does not match any outer indentation level. This does not seem to make sense to me as I indented the exact same for print and return. However when I take the return line out it works just fine. Can you not print and return in the same if/else condition?
Are you using a mix of tabs and spaces? It looks like the print line use a tab, while the other lines use spaces for indentation. It copy/pasted for me with a single tab on the print line. When I replaced it with 8 spaces, the code worked. (although with the improper if logic described by Foiled.)

Dominoes fucked around with this message at 22:03 on Aug 10, 2013

digitalcamo
Jul 11, 2013
I've found the solution to a lot of my problems is using Codecademy. I can put in the exact code they are looking for but I get some kind of error. When I use my own text editor it works just fine. So a lot of times once I KNOW my code is correct I have to search online to find out what the problem is. Oh and I'm using Notepad++.

salisbury shake
Dec 27, 2011

digitalcamo posted:

I've found the solution to a lot of my problems is using Codecademy. I can put in the exact code they are looking for but I get some kind of error. When I use my own text editor it works just fine. So a lot of times once I KNOW my code is correct I have to search online to find out what the problem is. Oh and I'm using Notepad++.

Codeacademy is probably testing different strings for your function. As someone posted above, your function will return 'Shutting down.' no matter what the passed string contains. So if it is passing 'no', it will still return 'Shutting down.'.

The problem is the test in your if/elif block. Python's or keyword is a boolean operator, meaning it checks whether or not one or more of the objects being tested is true, then returns either True or False returns the value that is evaluated as True. If the first value evaluates to False, it returns the second value.

In Python, non-empty strings will return True when doing boolean operation.

With that in mind, what is going on here is in your if condition:
code:
if s == ('Yes') or ('YES') or ('yes'):
For this example, s will equal 'YES'

You are not making a single test here. You are testing the equivalency of s and 'Yes', which will return False. Equivalent code:
code:
if False or ('YES') or ('yes'):
Since the first comparison evaluated to False, the or operation then returns the value of the second object (I had to play with the interactive console with this one, it actually returns the value and not False). In this case it is the string 'YES', and as we discussed above, a non-empty string is True:
code:
if False or True or ('yes'):
Turns out that the second comparison is True, so the second chained or boolean operation also evaluates to True. You can see that no matter the value of s, that the statement being tested in the if condition will always be True.

To translate what you were trying to do in a single test, you could either do:
code:
if s == 'Yes' or s == 'YES' or s == 'yes'
Assuming s is 'YES', the first test after the if keyword is False, followed by a True statement after the or keyword. Since the statement is True the second or condition will evaluate to True as well, and it will correctly return 'Shutting down.'

As said above, the other solution to this test is to use the 'lower()' method string objects have. Keep in mind, the method does not assign the lowercase string to the variable s. It creates an instance for that test, and discards it. So for every test you need to remember to use the 'lower()' method.

What you could do is:
code:
def shutdown(s):
  s = s.lower()
  if s == 'yes':
    hurf()
  elif s == 'no':
    derf()
edit: fukkin bbcode strike tag & terminology
double edit: heres a quick reference for what I'm talking about. Pretty much the basic python cheat sheet, tis invaluable when learning: http://docs.python.org/2/library/stdtypes.html (scroll down to boolean operations and comparisons)

Are you using any other resources than Codeacademy?

Two space indent supremacy~~

salisbury shake fucked around with this message at 01:21 on Aug 11, 2013

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

digitalcamo posted:

I've found the solution to a lot of my problems is using Codecademy. I can put in the exact code they are looking for but I get some kind of error. When I use my own text editor it works just fine. So a lot of times once I KNOW my code is correct I have to search online to find out what the problem is. Oh and I'm using Notepad++.

Do not ever, ever mix tabs and spaces for indentation.

code:
$ python2 -tt shutdown.py
  File "shutdown.py", line 3
    print "Shutting down."
                         ^
TabError: inconsistent use of tabs and spaces in indentation

Crosscontaminant
Jan 18, 2007

What version of Python emits IndentationError here? Both Python 2.7.5 with the -tt flag and Python 3.3.2 emit TabError when given your code sample, and I don't have other versions on hand to test.

QuarkJets
Sep 8, 2008

I'm having issues with scipy.optimize.curve_fit. Sometimes instead of returning a covariance matrix, it just returns inf (I guess if you're giving it data that is really really hard to fit to). Obviously this fucks everything up if I'm treating the returned variable as a 2D array when it's actually a float sometimes. I could use isinstance to make sure that it's not a float, but common wisdom seems to be to avoid isinstance. I could use a try/except block, but that seems sloppy.

(basically curve_fit should have been designed to return a matrix of infs instead of just inf when it has trouble fitting to data, but since that's not the case what should I do to compensate?)

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Thanks for this pointer. This looks like it might at least have most of what I need, I'll have to decide whether to use this or go on with my own thing.

Adbot
ADBOT LOVES YOU

Dominoes
Sep 20, 2007

PYQT signals/slots question:

I'm getting crashes with QT threads. After troubleshooting and internet searching, it appears that the crashes are caused by updating the GUI from a thread other than its own. The solution I've read is to be to never 'update' the GUI directly, but use signals/slots instead.

I think I'm misunderstanding signals/slots, and what the difference is between using them and the 'updating GUI' behavior that causes crashes.

I've been using commands such as:
Python code:
self.ui.actionAbout.triggered.connect(self.about)
self.ui.btn_download.clicked.connect(download)
timer.timeout.connect(play_beat)
for signals. Ie: Pushing a button or clicking a menu item runs a function.

I've been using slots the following way:
code:
ident = main.ui.le_ident.text()
timer.setInterval(1000)
main.ui.statusbar.showMessage("HI")
Examples of GUI calls that appear to be causing the crashes:
Python code:
main.ui.progressBar.show()
main.ui.progressBar.setMaximum(len(files))
main.ui.progressBar.setValue(progress)
if main.ui.actionCombine.isChecked():
main.ui.statusbar.showMessage("Internet connection error")
How do I convert these to signals/slots? My understanding is that code such as '.showMessage()' and 'setValue()' are slots.

I found some examples that uses formats such as:
Python code:
    newText = QtCore.pyqtSignal(QtCore.QString)
    newText.connect(main.ui.statusbar.showMessage)
    newText.emit("my message")
but have no idea how to use it. (attribute errors on QString. If I leave that argument blank or use 'str', I get an attribute error on 'connect'. "'PyQt5.QtCore.pyqtSignal' object has no attribute 'connect'") This PYQT docs article has some info. I've read that this may have to do with bound/unbound signals, but I've tried running these commands on object instances, and received the same attribute error, or when following the above article's examples, modified to use arguments, 'SystemError: error return without exception set'.

Dominoes fucked around with this message at 16:42 on Aug 12, 2013

  • Locked thread