r/badcode • • Apr 14 '21

python Helping a friend learn python. He was really proud of this one.

Post image
1.9k Upvotes

159 comments sorted by

354

u/[deleted] Apr 14 '21

Asked about the extra == True-s. He said they were there to make sure "it" checked that the statements are true.

He also didn't belive me when I said that the entire thing could be written as return val%2 == 0.

190

u/grammatiker Apr 14 '21

What do you mean didn't believe you? Lmao he can just prove it to himself in 5 seconds.

54

u/Topikk Apr 15 '21

He was still brainlocked from staring at this for a few hours.

40

u/britreddit Apr 14 '21

Not a python dev, does it have Truthiness?

26

u/Pythagorean_1 Apr 14 '21

Yes

18

u/britreddit Apr 14 '21

Is it possible this would help guard against type coercion errors?

18

u/tongue_depression wicked Apr 15 '21
>>> "Not a bool" == True
False
>>> bool("Not a bool")
True

so, yes but actually no

2

u/Orlando-- Apr 15 '21

Fair to say in an if it would cast it to a bool regardless and effectively be true?

8

u/tongue_depression wicked Apr 15 '21

that’s correct. if x == True: (or the way you probably should write it, if x is True:) will fail if x is anything other than the singleton True.

if x: will fail only if x is one of a few falsy values like False, 0, [], and "", excepting a secret custom __bool__ implementation for x

1

u/[deleted] Apr 15 '21 edited Apr 15 '21

wdym secret custom __bool__ implementation?

5

u/tongue_depression wicked Apr 15 '21

you can override what the bool function does

class BadList(list):
    def __init__(self):
        super().__init__()
    def __bool__(self):
        return True

x, y = list(), BadList()
print(x, bool(x)) # [], False
print(y, bool(y)) # [], True

65

u/darthruneis Apr 14 '21

Time to teach him about unit tests, then!

13

u/R3D3-1 Apr 15 '21

... and don't forget to explain why

def mod(a, b):
    if a == 0: return 0
    elif a == 1: return 1
    elif a == 2: return 2
    elif a == 3: return 0
    elif a == 11: return 2

is not "good enough", even if it passes all test cases.

34

u/sharkbound Apr 14 '21 edited Apr 14 '21

the other way is just to do return not val & 1 and it is faster since it just checks the least significant bit
EDIT: changed first bit to " least significant bit "

15

u/Socialimbad1991 Apr 14 '21

From what I understand most modern compilers will make that optimization automatically

20

u/sharkbound Apr 14 '21

it seems python does not do that itself, i tested using this code:

def MOD(value):
    return not value % 2

resulting bytecode was this:

dis(MOD)

0 LOAD_FAST                0 (value)
2 LOAD_CONST               1 (2)
4 BINARY_MODULO
6 UNARY_NOT
8 RETURN_VALUE

for binary AND it was this:

0 LOAD_FAST                0 (value)
2 LOAD_CONST               1 (1)
4 BINARY_AND
6 UNARY_NOT
8 RETURN_VALUE

17

u/jarfil Apr 14 '21 edited May 12 '21

CENSORED

13

u/sharkbound Apr 14 '21

fixed, i was not familiar with bit terminology in this case, thanks for pointing it out

1

u/Astrokiwi Apr 15 '21

Does it actually shortcut the & though? I would have thought it'd still do a full and across all bits and return a full sized int. Checking ==0 shouldn't be any slower than not x either.

Edit: it should be faster, just because a binary And is faster than a division & remainder calculation - but it's not because it`s only checking the final bit

1

u/sharkbound Apr 15 '21

Doing == 0 vs "not value" is probably more style than anything, any performance lost or gained from doing == or & would be very minimal I imagine.

And I am pretty sure the & 1 will stop when the lower bit count is reached, so it should just check the least significant and that's it, at least in theory

1

u/Astrokiwi Apr 15 '21

It stores 1 as a full sized 32 bit integer (in CPython at least). So it does a full 32 bit And, and dumps out a new 32 integer that's ==1 or ==0. You can confirm this with type(x & 1)

2

u/sharkbound Apr 15 '21

I see what you mean, but that does raise the question if the 1 or 0 from the AND result is the cached version or not.

1

u/Astrokiwi Apr 15 '21

Yeah, it will depend on the optimisations within the particular implementation of Python. You'd really have to do a benchmark and time it.

2

u/sharkbound Apr 15 '21

did timings on it, here is the result:

Python 3.8.5 (default, Sep  3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] on win32

%timeit -n1_000_000 5 % 2 == 0
31.6 ns ± 0.477 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit -n1_000_000 not 5 % 2
9.15 ns ± 0.598 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit -n1_000_000 not 5 & 1
10.2 ns ± 2.18 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit -n1_000_000 5 & 1 == 0
37.3 ns ± 4.96 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

also, the 1 and 0 from the AND result are the cached versions:

id(1) == id(5 & 1)
Out[6]: True

3

u/Astrokiwi Apr 15 '21

... you're saying this isn't intentionally obfuscated? I assumed that (b==False)==True was a joke

2

u/shawmonster Apr 15 '21

Did you tell him to write this isEven function? And if so, did you tell him about the existence of the modulo operator before hand?

1

u/[deleted] Apr 15 '21

I have a bad habit of checking null and for 'null' string and string length and if sting is empty using language method.

do you know why? it Because I am an idiot with 10 years of swe experience. I have worked with legacy code most of my life which make me a bitter developer.

At the end. I bet over checking stuff has to have a limit . ..

rant complete.

50

u/incredible-mee Apr 14 '21

He could have simply used this api https://isevenapi.xyz/. It would be much easier. /s

13

u/[deleted] Apr 14 '21

Oh god, this is incredible. I'm definately going to use this instead of x%2==0 from now on.

9

u/mhdhussein Apr 14 '21

https://isevenapi.xyz/

Holy crap, the Unofficial Python Module on PyPI, on version 0.4.2 with 3 forks on GitHub.

79

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 14 '21

Doesn't even run. Syntax error on line 22.

73

u/[deleted] Apr 14 '21

I must've accidentally thanos snapped a colon on line 22 while stitching the two original screenshots togheter. My bad!

28

u/Ciaranhappy Apr 14 '21

Nah. You made it perfectly balanced, as all things should be.

4

u/Rudxain let let.let = 'let' Apr 16 '21

Errors are red
IDEs are blue
Syntax error
On line 22

646

u/boniqmin Apr 14 '21

This is truly a monstrosity. is_odd as a parameter to calculate whether a number is even, that's a big brain move.

115

u/MyAntichrist Apr 14 '21

At least from the output message it looks like the function should work both ways - tell you if a number is even (isodd = false) or if a number is odd (isodd=true). So an example input of 3 with the flag set to true will yield a true.

Then again, I didn't attempt to decypher the chain of if statements leading there to see whether my assumption is right or not, sooooo...

64

u/[deleted] Apr 14 '21

It does actually work both ways but the isodd flag is completely unnecessary. One could achieve the same effect by passing abc as true.

20

u/TeJay97 Apr 14 '21

This is what happens when you get paid per line of code.

8

u/[deleted] Apr 17 '21

if(isodd!=False)==True:

by character apparently, though the lack of spaces is strange, throwing away money.

9

u/MyAntichrist Apr 14 '21

So, what happens if both are true? Does one negate the other?

1

u/tuckmuck203 Apr 14 '21

Well, like, also, there's 2 options. It's either even or odd (or I guess it could throw an error, but that's another conversation). So if isEven returns bool you can just do if not isEven and not even have to alter the function.

6

u/Kyn21kx Apr 14 '21

Hey, that's an O(1) algorithm right there (I mean, not this one, absolutely not this one, but if they were to use it right...

0

u/[deleted] Apr 15 '21

just get modulo
a % 2

13

u/Blyatman72 Apr 14 '21

How can you make this code better? I'm still a bit of beginner

22

u/LegibleToe762 Apr 14 '21

If

val % 2 == 0

is true then val is even, it essentially checks if it's divisible by 2, similarly

val % 2 == 1

would only be true if val were odd

The % operator returns the remainder after dividing the numbers, eg. 13 % 4 = 1 or 5 % 3 = 2

40

u/[deleted] Apr 14 '21 edited Apr 14 '21

I would do it with modulo 2. Modulo is an operator which returns the rest of an devision. E.g. 15/12 = 1 rest 3. And the modulo would look like 15%12=3. For an uneven number something like: if (number % 2 != 0):

34

u/HakosThao Apr 14 '21

This code can be condensed in 1 line:

print("Even" if number % 2 == 0 else "Odd")

2

u/kkjdroid Apr 15 '21

print(['Even', 'Odd'][number % 2])

8

u/FinalGamer14 Apr 14 '21

Well just using modulo is the simplest way, or you could use bitwise and operator if you want to be fancy.

Modulo:

def is_even(val):
    return val % 2 == 0

With modulo when val is even val % 2 will be 0 and if it's odd it will be 1. So the function returns true or false.

Bitwise "and" operator:

def is_even(val):
    return not(val & 1)

In this case what happens, is if you look at a number in binary, if the least significant (most left) digit is 1 that number is odd, if it's 0 that number is even. So if you do an "and" operation on val with number 1, you'll get 1 if the number is odd and 0 if that number is even. We just invert this to get true when even and false when odd.

9

u/ParanoydAndroid Apr 14 '21 edited Apr 15 '21

... if the least significant (most left) digit ...

I'll point out, only because novices could get tripped up by this, that this is inaccurate.

The internal representation of binary strings can change 'endianness' (i.e. which side the least significant digit of a binary string is located on), so it's something you may need to be aware of for lower-level programming. But in Python, the most significant digit is the leftmost.

e.g.

assert int('01', 2) == int('00000001', 2)

3

u/BinaryFissionGames Apr 14 '21

Just for the benefit of anyone who isn't familiar with the concept of endianness - endianness isn't really about bit-ordering, but about byte-ordering. So if you have a 4 byte (32 bit) integer, the bytes might be arranged like this on a big endian system (where each number is the address of the byte in memory):

MSB | 0x01 0x02 0x03 0x04 | LSB

But on little endian systems, the memory would be laid out like this:

MSB | 0x04 0x03 0x02 0x01 | LSB

In most (all?) systems, specific bits aren't addressable, so there isn't really an "ordering" of bits specifically. Bit-endianness exists, but it's like, a hardware level thing that as a programmer you won't ever have to worry about or really have access to. You'd probably only see it if you designed hardware for a network device.

This means if your integer is just a byte, it's the same representation, regardless of big endian/little endian. It's only relevant for multi-byte data.

Anyways, all that to say that I don't think I've ever seen a textual representation of binary where the left-most binary digit is the least significant. Even if it was little endian, I'd still write each byte from most significant bit to least significant bit:

1 in Big endian (2-bytes): 00000000 00000001 (0x00 0x01)

1 in Little endian (2-bytes): 00000001 00000000 (0x01 0x00)

10

u/sanderd17 Apr 14 '21

I hope this is sarcastic, but in case it isn't, just look at this part:

if(c==False)==True:
    if(b)==True:
        print("nubmer is not odd")
    if(b==False)==True:
        print("number is not even")

What is b or c? Unless you use variables in a very limited context (like in one line of a small loop), don't use single letters for your variables but give them meaningful names.

Never do if variable == True:, that's just if varaible:, perhaps combined with a type check before.

Don't use if x and then if not x, that's what else is for. Otherwise you need to keep the two conditions in sync, and someone reading your code needs to read both conditions to check if it's always one of the two happening.

1

u/Nariztoteles Apr 14 '21

What do you think about using "if not x" and then an "else"? Sometimes I do that to put the focus in the first part, just to make easier to understand the whole code.

3

u/sanderd17 Apr 14 '21

I always switch it around, or try to have an alternative construction so the else can be avoided. Like an early return or an extra function.

-1

u/spock1959 Apr 14 '21

There's nothing wrong with

if(variable==true)

It may be unneeded since its equivalent to

if(variable)

But being overly robust doesn't hurt your code or make it less readable. Some people prefer seeing the full command and that's not "wrong" it's just a preference.

The other issues you mentioned are accurate and the (variable==true)==false is super obtuse and definitely hinders any readability.

3

u/sanderd17 Apr 14 '21

It's indeed the lesser of all crimes committed here, but I've never seen a review where this was approved.

2

u/spock1959 Apr 14 '21

Interesting... We have a bunch of people who put it in and it's never worth adding a comment on. Different strokes

1

u/sanderd17 Apr 14 '21

Maybe it depends on the culture and background a bit?

I programed mainly in JS and Python, and now in Ruby. Ruby is even more extreme in the idiomatic way. Now it isn't even accepted to write if var == nil, but I have to use the built in nil? function.

1

u/detroitmatt Apr 15 '21

In curly brace languages I prefer to write if x == false because when I'm reading my eyes will often fail to notice the single character ! which is sandwiched next to another non alphanumeric character, (. But I don't do it at work because my coworkers don't agree.

1

u/inter-ego Apr 15 '21

i definitely suggest getting a font with text ligatures asd enabling those in your text editor. they help readablity a lot imo :)

4

u/nattrium Apr 14 '21

Everyone already told you about the modulo "trick" but they are other lessons to get out of this mess.

The function is even takes three arguments. It's unusual for what we expect a function named "is even" should do : it needs only 1 argument. If you function has more than its fair share of argument, you're most likely doing something wrong.

It is good practice to name a function <verb>whatever because the function does something. So iseven, isEven or is_even are good names. If you can't do that, it might mean that your code is getting convoluted and parts no longer have clear purposes.

There is no need to check wether it is true that something is false, check wether something is false instead; i.e (x == False) == True should be replaced by x == False. Those little trick are not really important but they really ease up the code.

Unlike what many may tell, it is fine to be a bit more verbose than absolutely necessary.

print("is even" if isEven(x) else "is odd")

Is fine but also is

even = isEven(x)

if (x):

   print("is even")

else:

   print("is odd")

It is fair to ask : why 9999 at the top of the function isEven ? A numbers that appear without clear reason are called magic numbers. They are a menace to the well being of your code : hard coded values are hard to make sens of but also will make debugging a pain if they pop up everywhere.

If you can avoid the heap of indentation we see in the function there, it is recommended to avoid it. If you end up with if with too long expression, it is fine to calculate the value of the condition in multiple steps before the if and give the result to the if.

If (birthdayMoney + christmassMoney + ...)

Can be replaced by

money = birthdayMoney

money += christmassMoney

money -= costOfPS5

... # big calculations

if (money > 0):

...

Counterintuitively it is just as fast as it will most probably gets optimized and will help in extrem cases.

4

u/Blyatman72 Apr 14 '21

Thanks a lot, all of you really helped me.

1

u/detroitmatt Apr 15 '21 edited Apr 15 '21

First problem, I have no idea what these parameters are. I assume val is the value you're checking but having an isodd parameter is very odd indeed and I'm at a TOTAL loss as to what abc is supposed to be. At a bare minimum abc should be named more descriptively.

You're comparing val to 9999 and setting it to -1 if it's larger. Why? Why can I only tell if a number is even provided that it's less than 10000?

The == True stuff has already been discussed enough

Reassigning variables like this in a loop is a bad thing to do, it makes your program flow complicated and you can't step through it in your head anymore. It's 10 times worse when the variables aren't named well.

All the casting of int and bool is confusing because it means you don't know what type your variable is supposed to be, which means I definitely don't know what type it's supposed to be. Casting should be rare in languages without explicit types, and almost never happen, outside of specific situations, in languages with them.

This is a poor choice of algorithm for finding if a number is even. Even assuming you don't know about the existence of better ones, if you're implementing an algorithm (as opposed to following a protocol or definition), then you should comment it heavily.

The line abc=bool(int(1-abc)) is subtracting a bool from 1. Even if this technically runs, you really shouldn't do this, because it means that now I have to look up obscure rules of python to see if this is doing what you mean for it to be doing, which on top of that I have to guess at what you mean for it to be doing.

I'm pretty sure this algorithm doesn't even work, although I haven't tested it

1

u/[deleted] Apr 15 '21

Adressing a few of your concerns:

After a lot of banging my head against a wall, I think I figured out what all the variables mean.

  1. val = the value it's checking

  2. isodd = flag for telling the function if it should check if the number is odd instead of even (even though this could be done with a not)

  3. abc = the bool it flips back and forth until the value it's checking is reached

As for why abc is passed as a parameter, I don't know. It should really be a local variable.

I belive the comparison to 9999 is a clever way to kinda-break the loop, even though a for loop would've worked better. Heck even a break would've worked better. I did teach him about for loops and breaks (and the modulus operator too!) but I guess he forgot.

I think abc=bool(int(1-abc)) was supposed to actually be abc=bool(1-int(abc)), as an attempt to invert abc. That would make more sense, but I guess he forgot about not?

The algorithm does indeed work, even though it only has a range of 0-9999 that could be extended to -9999-9999 with an abs. It's very slow too, and gets even slower when you want a larger range of inputs. This is due to the fact that the loop isn't properly broken, so it always runs to whatever the upper bound is.

2

u/stlenx Apr 14 '21

I'd start by not comparing the conditions in the if statements to true, as it's not necessary. Then a very simple way of checking if a number is even or odd is using the % (modulus) operator. It gives the reminder of dividing 2 numbers, so if you divide an even number by 2 itll give 0, and if it's odd I'll give something else than 0. Some other stuff can be made smaller like instead of checking if ABC is true or false and then returning true or false, you can just return ABC and itll do the same. Also the lines directly on top do nothing, if ABC is true it sets it to true which it already is and same if its false, they serve no purpose. In general it's way more complicated for what it should do, but for a complete beginner it's not that bad

1

u/[deleted] Apr 14 '21

Use modulo. Basically, if x%2=0, then even, else odd. You may also want to verify that x is a number first, but that's optional depending on use and data quality.

1

u/detroitmatt Apr 15 '21

Assuming you don't know about binary math and stuff like modulo, you could do it like this:

if val == 1:
    return False
if val == 0:
    return True
return IsEven(val-2)

0

u/Tunro Apr 14 '21

If for whatever reason you cant use modulo like the others are saying, you can do it recursively instead.

function evenOrOdd( $input ){  
    if( $input > 1 ){
        return evenOrOdd( $input - 2 );
    }
    else if( $input == 1 ){
        return "Number is odd";
    }
    else if( $input == 0 ){
        return "Number is Even";
    }
    else{
        return "Non valid input";
    }
}

0

u/[deleted] Apr 14 '21

[deleted]

0

u/Tunro Apr 14 '21

I dont know what language youre using, but in the ones im using that // will just turn the rest into a comment
and if I have to ask what this does, its too much for a beginner

3

u/Additional_Yogurt_28 Apr 14 '21

Aside from the lowercase true and false, this looks like Python.

In Python // and / are used for division, but // rounds down to an integer and / doesn’t. If x is odd, x//2 will get rid of the .5. so x - (x//2)*2 will be 1.

Otherwise x//2 will be exactly half of x and x - (x//2)*2 will be 0.

1

u/[deleted] Apr 14 '21 edited Apr 14 '21

[removed] — view removed comment

3

u/callmelucky Apr 14 '21
if (val % 2 == 0):
    return True
return False

Even this is pretty amateurish. return val % 2 == 0 would be the way to go.

330

u/Capitalist_Kerbal Apr 14 '21

Genuinely grotesque.

(isodd!=False)==True

Insanity.

75

u/[deleted] Apr 14 '21

That is so beautifully ugly I love it

43

u/[deleted] Apr 14 '21

I’m laughing so hard at this one. There’s so much logic packed into this single relational

30

u/fukitol- Apr 14 '21

Doing

if isOdd:

is a hard thing for new developers to conceptualize at first. I've seen lots of iterations of if thing = True and if thing != False but this is truly a masterpiece.

5

u/oderjunks Apr 15 '21
if (thing not = False)=True

185

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 14 '21 edited Apr 14 '21

Image Transcription: Code


def IsEven(val,isodd,abc):
    print("calculating if number is odd or even...")
    a=0
    while bool(a+1)==True:
        if(a>=9999)==True:
            a=-1
        else:
            a=a+1
            if(isodd!=False)==True:
                if(val-a>0)==True:
                    abc=bool(int(1-abc))
                    if(isodd)==True:
                        isodd=False
                        abc=True
            if(isodd==False)==True:
                if(val-a>0)==True:
                    abc=bool(int(1-abc))
    if(abc)==True:
        abc=True
    if(abc==False)==True:
        abc=False
    if(abc)==True
        return True
    if(abc==False)==True:
        return False

a=int(input("enter number to be checked if even"))
b=bool(int(input("check if odd?")))
c=False
c=IsEven(a,b,c)
if(c)==True:
    if(b)==True:
        print("nubmer is odd")
    if(b==False)==True:
        print("number is even")
if(c==False)==True:
    if(b)==True:
        print("number is not odd")
    if(b==False)==True:
        print("number is not even")
exit()

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

128

u/gavwando Apr 14 '21

I appreciate you kept "nubmer" in your transcript haha

73

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 14 '21

Wouldn't be accurate if I didn't :)

ignoring the fact that I made a typo on one of the other ones, as has been pointed out to me

-30

u/[deleted] Apr 14 '21

[removed] — view removed comment

33

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 14 '21

Additionally, your bot breaches the botiquette on at least 3 fronts; it's not commenting only when specifically called, it isn't adding anything to this conversation, and you haven't listed your username or a dedicated subreddit in the comment.

13

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 14 '21

opt out

5

u/troll_annoyer Apr 14 '21

your bot is shit and annoying. Stop spamming.

I am also a bot, and this was performed automatically

16

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 14 '21

Your bot breaches the botiquette on at least 3 fronts; it's not commenting only when specifically called, it isn't adding anything to this conversation, and you haven't listed your username or a dedicated subreddit in the comment.

-7

u/[deleted] Apr 14 '21

[removed] — view removed comment

10

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 14 '21

Your bot breaches the botiquette on at least 3 fronts; it's not commenting only when specifically called, it isn't adding anything to this conversation, and you haven't listed your username or a dedicated subreddit in the comment.

14

u/Nefrace Apr 14 '21

The second "nubmer" isn't correct

24

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 14 '21

Oh god I've become the typo...

Fixed it, thanks for pointing out!

56

u/bisnark Apr 14 '21

"nubmer". Ha!

59

u/Ciaranhappy Apr 14 '21

While this code isn't great, you can't not be happy that your friend is proud. They made a thing, and maybe its terrible, but its their thing.

33

u/[deleted] Apr 14 '21

Now the OP has to teach his friend how to refractor the code

6

u/fxnn Apr 14 '21

Guess a unit test would be a start

5

u/[deleted] Apr 14 '21

Ah yes TDD

5

u/fxnn Apr 14 '21

Maybe OP should introduce his friend to Extreme Programming

0

u/callmelucky Apr 14 '21

if ((can't!=happy)==friend_is_proud)==True:

19

u/dvof Apr 14 '21

(a==False)==True

Lol'd

7

u/jayhilly Apr 14 '21

if(abc==False)==True:

amazing

43

u/[deleted] Apr 14 '21

we all start somewhere. good for him for trying.

15

u/LeCrushinator Apr 14 '21 edited Apr 14 '21

This code truly disgusted me.

Everything about this:

  • The parameter isOdd being passed into the method, the use of ==True and ==False

  • The single letter variable names that don't give any hint of what they store

  • The 5 levels deep of nesting whiles and if/elses

  • Using ==True after every conditional

  • if(abc==False)==True: abc=False. Like, if it's already false, then why set it to false?

  • The reading input in, casting it to an int, then casting that to a bool: b=bool(int(input("check if odd?"))). What is the user supposed to put here? What if they type "yes", what's the expected result?

  • Declaring a variable by doing c=False and then immediately on the next line reassigning it to c=IsEven(a,b,c)

  • Having a section for "is odd" and "is even" (the only possible two outcomes), and then somehow another section for "is not odd" and "is not even" (the same two cases but worded differently).

  • In fact, the sections at the end, and the b variable are entirely useless. He could've just done something like this: print("number is even? " + c)

  • Going further, the variable c is useless too, just do print("number is even? " + IsEven(a)), and now get rid of the extra parameters being passed to IsEven, and then rewrite that entire mess of a function.

12

u/gsjoy99 Apr 14 '21

This is so bad its kinda cute

6

u/only_bad_comments Apr 14 '21

After reading this code, I cannot even...

6

u/CowboyBoats Apr 14 '21

My favorite part of this symphony is sys.exit() at the end of the function definition

4

u/tailfra Apr 14 '21

You must be proud! This one was good hahah

4

u/iamafraazhussain Apr 14 '21

Where does your friend buy his weed?

1

u/Shinkegeeek Apr 14 '21

II dont get the

if (abc )==True: abc =True

2

u/[deleted] Apr 14 '21

Me neither. It's probably to "make sure the thing is actually true or false". I once thought this stuff too.

1

u/Shinkegeeek Apr 14 '21

Variables name are also terrible... a, b, c and abc it's not the best way to name variables

3

u/hsantefort12 Apr 14 '21

Oh my sweet summer child

2

u/ay88407 Apr 14 '21

Maybe you should have uhh. You should have taught him basic math functions python has. Specifically mod. Had a good laugh though.

2

u/[deleted] Apr 14 '21

Well. He’s taking the time to try and learn.

I wouldn’t bash him for it man. Ofc the code would be bad.

2

u/SMTG_18 Apr 14 '21

What. The. Hell?!?

2

u/deleted1357 Apr 14 '21

I.. I mean, I'm not mad. This is some creative horrendous code.

2

u/callmelucky Apr 14 '21

Seriously, this is the most incredible piece of code I've ever seen. I am actually in love with it.

2

u/AnnualUnderstanding7 Apr 14 '21

Seems like they needs a bit more math and a little less code 😅

2

u/TSReactReduxSASSDev Apr 14 '21

Here we see a disciple who is not one with the boolean. You must find peace and harmony, a "boolean zen" between you and your code.

...this currently is not so

2

u/mplaczek99 Apr 14 '21

Let's not be so harsh, the code style looks like he's new

2

u/Alkyen Apr 14 '21

That's amazing. Tell him I'm proud of him too!

2

u/bitcraft Apr 14 '21

This nicely demonstrates how easy it is to develop a bad idea by powering through errors.

2

u/TheRealCCHD Apr 14 '21

You need to teach him about % man! :D

2

u/using_mirror Apr 25 '21

Just wait until he learns recursion

2

u/[deleted] Apr 14 '21

why people fuck up isEven that often? just (x & 1) == 0

5

u/SamBBMe Apr 14 '21

Ahh yes, I am sure that the average person with no CS degree and 0 experience knows what bitwise operators are.

2

u/aeropl3b Apr 15 '21

I am embarrassed to say I learned about bit ops about 2 years into my first job...but then my world changed and now everything is just bits...

1

u/[deleted] Apr 14 '21

Tmw you’re missing the 5 key.

Also, CS1301 by David Joyner is a godsend (or Joynersend).

1

u/KuchDaddy Apr 14 '21

isOdd parameter. You have to already know the answer to use the method. lol

1

u/klc3rd Apr 14 '21

This simple task, is making my brain hurt

1

u/burritoboy76 depraved Apr 14 '21

Lines 18-25 annoy me the most, but all of this code is horribly formatted overall

1

u/[deleted] Apr 14 '21

JS developers confused why you can’t just import is-even.

1

u/Samuql Apr 14 '21

If (abc == True): abc = True

XD

1

u/[deleted] Apr 14 '21

I punched a whole through my monitor so I wouldn't have to look at this

1

u/campbellm Apr 14 '21

Keep this as an answer to the perennial, "Do I need to be good at maths to be a developer?" question.

Well, maybe not, but you need to have a basic understanding.

1

u/Frennish Apr 14 '21

What the absolute shit

1

u/Socialimbad1991 Apr 14 '21

I refuse to believe this is not parody

1

u/jjman72 Apr 14 '21

Needs more True

1

u/fzammetti Apr 15 '21

Insert Monty Python "Doctor! My brain hurts!" image.

1

u/schlaubi Apr 15 '21

It's beautiful.

1

u/allstreamer_ Apr 15 '21

He tryed, he gave it his best

1

u/usedtoliveonmars Apr 15 '21

Wow this could be one line of code but it's as if they had a minimum word count

1

u/dwightshru Apr 20 '21

when code is long and looks all pretty i’m proud too no matter what it says

1

u/SquigglyHL May 27 '21

print("nubmer is odd")

1

u/Clayrock78 Jan 22 '22

return val % 2 == 0

1

u/thedarklord176 Oct 03 '22

Ah yes, the true here is made of true

1

u/eidron06 Apr 14 '21

Not your brightest friend, i suppose

0

u/[deleted] Apr 14 '21

[deleted]

67

u/[deleted] Apr 14 '21 edited Apr 14 '21

It's only semi legit. After seeing all these memes I challanged him to write an is even function. He only knows the very basics for now and I thought this would be a good way to find what needs improvement. Still it was too good(bad?) not to share.

63

u/ian421 Apr 14 '21

It was too (isBad!=False)==True not to share

20

u/callmelucky Apr 15 '21

Honestly this is a legitimate case of "you can't make that shit up". There is no way this was written by someone who actually knows what they are doing and wanted to write bad code for the sake of humour. No way in the world. It's bona fide, no doubt in my mind.

This is the best worst code I've ever seen, and it's not even close. It should be stickied on this sub to shame all posts that follow it.