r/badcode • u/[deleted] • Apr 14 '21
python Helping a friend learn python. He was really proud of this one.
50
u/incredible-mee Apr 14 '21
He could have simply used this api https://isevenapi.xyz/. It would be much easier. /s
13
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
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
Apr 14 '21
I must've accidentally thanos snapped a colon on line 22 while stitching the two original screenshots togheter. My bad!
28
4
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
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
Apr 17 '21
if(isodd!=False)==True:by character apparently, though the lack of spaces is strange, throwing away money.
9
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
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
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
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 == 0With 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
borc? 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 justif varaible:, perhaps combined with a type check before.Don't use
if xand thenif not x, that's whatelseis 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 innil?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 eventakes 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) == Trueshould be replaced byx == 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
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
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.
val= the value it's checking
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 anot)
abc= the bool it flips back and forth until the value it's checking is reachedAs 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 beabc=bool(1-int(abc)), as an attempt to invert abc. That would make more sense, but I guess he forgot aboutnot?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
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
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 beginner3
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
Apr 14 '21 edited Apr 14 '21
[removed] — view removed comment
3
u/callmelucky Apr 14 '21
if (val % 2 == 0):return True return FalseEven this is pretty amateurish.
return val % 2 == 0would be the way to go.
330
u/Capitalist_Kerbal Apr 14 '21
Genuinely grotesque.
(isodd!=False)==True
Insanity.
75
43
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 = Trueandif thing != Falsebut this is truly a masterpiece.5
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
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
3
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
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.
18
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
24
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
Apr 14 '21
Now the OP has to teach his friend how to refractor the code
6
0
19
43
15
u/LeCrushinator Apr 14 '21 edited Apr 14 '21
Everything about this:
The parameter
isOddbeing passed into the method, the use of==Trueand==FalseThe 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
==Trueafter every conditionalif(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=Falseand then immediately on the next line reassigning it toc=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
bvariable are entirely useless. He could've just done something like this:print("number is even? " + c)Going further, the variable
cis useless too, just doprint("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
6
6
u/CowboyBoats Apr 14 '21
My favorite part of this symphony is sys.exit() at the end of the function definition
4
4
1
u/Shinkegeeek Apr 14 '21
II dont get the
if (abc )==True: abc =True
2
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
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
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
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
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
2
2
u/bitcraft Apr 14 '21
This nicely demonstrates how easy it is to develop a bad idea by powering through errors.
2
2
2
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
1
1
1
1
1
1
u/burritoboy76 depraved Apr 14 '21
Lines 18-25 annoy me the most, but all of this code is horribly formatted overall
1
1
1
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
1
1
1
1
1
1
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
1
1
1
1
0
Apr 14 '21
[deleted]
67
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
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.
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.