Python Forum
is it ok to post ...
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
is it ok to post ...
#1
... coding tips like this?

if you have ever coded something like this:
    if n==1:
        s = ''
    else:
        s = 's'
    ...
    print('we found',n,'thing'+s)
or the shorter way many people hate:
    s = '' if n==1 else 's'
    ...
    print('we found',n,'thing'+s)
then you might want to consider doing it like this:
    s = ('s','')[n==1]
    ...
    print('we found',n,'thing'+s)
this works because booleans False and True can be used anywhere a number can be used:
Output:
>>> complex(False) 0j >>> complex(True) (1+0j) >>> True/2 0.5 >>>
note that the last one will give a different result in Python2.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Messages In This Thread
is it ok to post ... - by Skaperen - Sep-19-2018, 03:00 AM
RE: is it ok to post ... - by ichabod801 - Sep-19-2018, 03:09 AM
RE: is it ok to post ... - by Skaperen - Sep-19-2018, 07:29 PM
RE: is it ok to post ... - by Mekire - Sep-19-2018, 03:43 AM
RE: is it ok to post ... - by micseydel - Sep-19-2018, 04:06 AM
RE: is it ok to post ... - by micseydel - Sep-19-2018, 07:37 PM
RE: is it ok to post ... - by Skaperen - Sep-21-2018, 08:03 PM
RE: is it ok to post ... - by ichabod801 - Sep-20-2018, 01:42 AM
RE: is it ok to post ... - by Skaperen - Sep-21-2018, 01:00 AM
RE: is it ok to post ... - by ichabod801 - Sep-21-2018, 02:37 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020