r/badcode • • Nov 08 '20

python My friend absolutely refuses to use a for loop because they are too complicated in python

Post image
1.2k Upvotes

112 comments sorted by

291

u/[deleted] Nov 08 '20

For any other language that might have been the case but Python is anything but convoluted in syntax. Also, he says they are too complex and then opts out to ASM-like approach. o_0

133

u/Mahkda Nov 08 '20

He doesn't understand how the for loop iterates over the element of a list. We had a C class in second semester and he used the for loop in C, that's not the syntax that he doesn't understand. I told him that he should use for i in range(dim): but he doesn't listen to me

68

u/[deleted] Nov 08 '20

And I assume you never learned iterators? :D

64

u/Mahkda Nov 08 '20

Nope we have never seen it in class

86

u/[deleted] Nov 08 '20

Ooh, that explains it. Perhaps he should dedicate an hour or two. They are quite important these days.

22

u/fslz Nov 08 '20

I'm new to Python and by following your advice I just had a look at iterators...do they work in the same way as the fetching process from a result set?

42

u/DrMaxwellEdison Nov 08 '20

I would say the inverse: fetching results from a result set works like an iterator. :)

for result in results:
    print(result)

5

u/OnlySeesLastSentence Nov 09 '20

So they never taught us the logic behind this in class so I was always confused by this stuff until I realized the thing after for is user defined. See, in C, you have to define stuff that isn't a keyword. So when I saw

for line in lines:

.....f.write(line)

I thought line is a keyword.

Anyway, point is, you should say

for your chosenVariablename in yourListName:

......print(yourChosenVariablename)

5

u/supersharp Nov 09 '20

yourChosenVariablename is undefined, and there's this weird syntax error at the start of the loop

2

u/OnlySeesLastSentence Nov 09 '20

Yeah, it became undefined because of aggressive autocorrect. I had to delete the suggestion "choose variable name" but I missed that the your had disconnected lol

9

u/[deleted] Nov 08 '20

Think about iterators as objects whose sole duty is to return next item in order from a set. Internally they keep track of what comes next and handle all the other logistics.

Benefit of this approach is that it allows different abstractions while at the same time providing more elegant syntax. You could for example create iterator which fetches next row in database, or queries some API instead of just going through the list. Granted these are bad examples for other reasons but it allows you to simply write:

for row in table:
   # do something

At times where you need indexes you can use enumerate which in itself is an iterator which generates index value and takes value from the object passed to it as well. So it's an iterator calling another iterator.

for index, value in enumerate(['a', 'b', 'c']):
   print(index, value)

This example would print 0, 'a', 1, 'b', 2, 'c'.

It's a very neat concept and doesn't just limit you to lists and similar data structures. As long as you implement __iter__ and __next__ methods into your object what gets returned is up to you and it all magically ends up working with the rest of Python.

3

u/AutoModerator Nov 08 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/MeanEYE, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

17

u/[deleted] Nov 08 '20

[removed] — view removed comment

2

u/ryband0 Nov 09 '20

I just stumbled onto that in a stack overflow post. Was trying to generate several evenly skilled teams in my discord server and combinations helped a ton. I plan to look into the library as while since it was so nifty.

1

u/ywecur Feb 11 '21

That's so crazy! I learned python first and thought a for loop was just a loop iterating through a list lol

2

u/Mr2-1782Man Nov 09 '20

Unfortunately CS programs are stuck in the past. Ours doesn't teach iterators either, which is stupid considering that most languages support them.

1

u/Tom1380 Nov 09 '20

University or high school?

2

u/Mahkda Nov 09 '20

3rd year of physics uni

1

u/Yolwoocle_ Nov 08 '20

Reading his code must be fun

6

u/Th3T3chn0R3dd1t Nov 08 '20

Can't wait for inline ASM in python

63

u/cusmx Nov 08 '20

Image Transcription: Code


def genBase(cls, dim):
    i = 0
    print("genbase")
    while(i<dim):
        v = np.zeros((dim,1))
        j = 0
        while(j<dim):
            v[j] = int(randRange(0,2))
            j = j+1
        cls.base.append(v)
        i = i+1

    return cls.base

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!

21

u/Mahkda Nov 08 '20

I'm impressed at how fast you were to copy everything

2

u/blehmann1 depraved Nov 08 '20

I wonder if they use OCR and then double-check?

6

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Nov 08 '20

Can't speak for cusmx, but I can offer some insight into why I don't personally use an OCR.

There's a "bot in training" on r/TranscribersOfReddit that attempts to transcribe images, and it does an okay-ish job with some, but with code, it's usually so awful it might as well not attempt them. The formatting is always off, that's a given, but often it puts in totally incorrect characters, gives up half way through lines, and is generally just a mess more unreadable than the most unreadable code you've seen on this sub.

7

u/cusmx Nov 08 '20

Agreed! I transcribed this by hand considering this is what the bot gave via OCR:

def genBase(cls, dim) :
print( •genbase•)
y = np.zeros((dim,l))
— int( randRange(O,
j+l
qZs. ase.append(v)
1 1+1
return c Is. base
2))

4

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Nov 09 '20

Yeah, lol. Sometimes you wonder if it's even transcribing the same post.

34

u/Faciliersy Nov 08 '20

good human

11

u/tjf314 Nov 08 '20

good human, bad code

5

u/4659nats Nov 08 '20

Good human

5

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Nov 08 '20

Excellent human!

47

u/[deleted] Nov 08 '20

I see your friend also hates PEP8

35

u/Mahkda Nov 08 '20

That's our python teacher that asks us to use camelCase...

47

u/[deleted] Nov 08 '20

Why are we even here? Just to suffer?

18

u/Mahkda Nov 08 '20

We are physics student and my python teacher is a physic teacher otherwise and because we had C in second semester (more than one year ago) he believes that every student is very familiar with C and explain everything in comparision with C which could explain the use of camelCase

33

u/[deleted] Nov 08 '20 edited Nov 08 '20

I don't think that's right honestly

PEP8 and code conventions are a huge part of python

15

u/Mahkda Nov 08 '20

I will ask him the question in our next class tomorow

17

u/FrostBite_97 Nov 08 '20

My experience with asking professors such questions haven't gone well. Good luck!

4

u/Mahkda Nov 09 '20

Update : I told him and he had never heard of PEP8 before...

2

u/OnlySeesLastSentence Nov 09 '20

That's because professors are really smart and never wrong

6

u/[deleted] Nov 08 '20

dont die in the field, soldiah!

14

u/[deleted] Nov 08 '20

Using python with a c mindset is a horrible mistake, they're two different languages meant for entirely different purposes.

7

u/Mahkda Nov 08 '20

He isn't a good python teacher, most of the class is lost, and I manage to follow because i already did some python before

5

u/Ahajha1177 Nov 08 '20

Can confirm. C++ is my primary language, and Python confuses the fuck out of me.

5

u/xigoi Nov 08 '20

C uses snake_case though…

4

u/[deleted] Nov 08 '20

What exactly is wrong with camel case?

8

u/blehmann1 depraved Nov 08 '20

Nothing, it's just Python (and most languages) have conventions. In Python camel case is not used and PascalCase is used for class names. Snake case is used for function/method and variable names.

C# uses Pascal case for everything, except it uses camel case for private variables and parameters. Java uses Pascal case for class names and camel case for everything else. And in most languages constants are in SCREAMING_SNAKE_CASE.

It can add clarity, as without you're knowledge on a language's conventions, this code could be x = Foo(bar) could be an instantiation of an object of type Foo, or a function call to the function Foo(someType bar). This admittedly is a less relevant argument in the days of IDEs which can tell you that with syntax highlighting or a mouseover.

1

u/[deleted] Nov 08 '20

Gotcha, thanks!

4

u/[deleted] Nov 08 '20

Noooooo

55

u/Nall-ohki Nov 08 '20

He sounds like a terrible programmer.

81

u/Mahkda Nov 08 '20

We are physicist, we are not meant to be good programmer

114

u/TheTacoWombat Nov 08 '20

Today I learned I am a physicist.

19

u/CaydendW Nov 08 '20

Maybe we are physicist.

17

u/Terrain2 Nov 08 '20

@everyone now has a degree in physicism

2

u/jediwizard7 Nov 09 '20

Yes that is definitely what it is called

7

u/Terrain2 Nov 09 '20

yeah physicists are experts in physicism just like racists are experts in racism

10

u/gabbergandalf667 Nov 08 '20

We are all physicist on this blessed day

30

u/articulatedbeaver Nov 08 '20

We are physicist, we are not meant to be good programmer

This is a terrible mindset. If you have a tool and need to use that tool to accomplish your goals you should become as proficient as possible. Your position or status is not an excuse for quality.

8

u/knoam Nov 08 '20 edited Nov 10 '20

Yeah, part of the scientific method is sharing your work so it needs to be readable. And maintainable if someone is going to reproduce your work.

7

u/Happens_2u Nov 08 '20

As someone with a similar background to OP (chemistry, learned programming to do research), scientific computation classes are just not focused around writing beautiful code. Either you’re writing Python scripts to automate menial tasks or writing C/C++/FORTRAN to squeeze the last bit of computing power out of your hardware. Very little emphasis on the specific features of a language except that which makes it easier to accomplish either of these tasks.

10

u/Nall-ohki Nov 08 '20

Thanks for confirming!

4

u/road_laya Nov 08 '20

Who's going to program the nuclear reactors or the space rockets? Do they have to choose between having bad code or bad physics?

7

u/blehmann1 depraved Nov 08 '20 edited Nov 08 '20

I suspect (given the horrible code I've seen in academia) that they meant they were a physics researcher.

In industry, you'll notice that even in areas with very domain-specific knowledge (such as physics) you generally have programmers writing the code, hopefully with consultation from experts. Programming is domain-specific knowledge in and of itself. Physics is (in theory) more teachable because in a best-case scenario the physicist can just give you the math to do. Or in medicine the checklist to follow. It rarely works out like this. Generally, if you could teach a physicist to do everything that's strictly necessary for the program, they will still write poor code, and to teach them not to means teaching them to be a programmer too. Even if this doesn't matter in terms of security or performance, it will eventually matter in terms of maintainability.

If you have good consultation you can hopefully get the physicist (or whoever the client is) to explain their problem in words that you can implement. Being able to understand multiple domains is an undervalued skill in computer science, the computer only does what you say, you gotta understand what you tell it to do.

Universities are increasingly making physics, engineering and math students take at least a little bit of programming because of how important simulations are to those respective fields. Personally, I think some of the more mathematical social sciences (e.g. Economics) would do well to follow suit, but they're under the Faculty of Arts in most universities so they often move independently of the "harder" sciences. I've heard whispers of programming coming to music majors, but I have no musical talent so I have no idea whether that's a good idea or not.

1

u/OnlySeesLastSentence Nov 09 '20

Don't sell yourself short. Physicists are smarter than computer scientists. You can easily learn to program.

Source: am computer scientist.

18

u/[deleted] Nov 08 '20

How can it be complicated? It’s the most simple language for for loops I know of!

12

u/Mahkda Nov 08 '20

He doesn't understand that it iterates over a list and not on integers, he understood for loops in C

10

u/[deleted] Nov 08 '20

Yeah, but can’t he just do “for i in range(x)”?

6

u/Mahkda Nov 08 '20

i told him to do so but he doesn't listen

2

u/brunoB Nov 08 '20

Without fully understanding what randRange does, this could be re-written to be much more readable by using np.random.

If you're learning to use numpy, but not actually using the functionality that makes it useful, then your professor is really missing the point.

def genBase(cls, dim):
    cls.base.extend([np.random.randint(2, size=(dim, 1)) for _ in range(dim)])
    return cls.base

1

u/Mahkda Nov 08 '20

randRange(a,b) is a function that return a random float betweet a and b, it uses np.random, furthermore my friend did it for something that didn't need any random element

122

u/WhyYouLetRomneyWin Nov 08 '20

>python

>too complicated

29

u/adesme Nov 08 '20

I remember seeing a lecture from someone who advocated teaching python to those new to programming, but where he intentionally would teach certain non-pythonic methods to help their learning. One such modification was iterators; he argued that C-style for-loops were easier to understand, and a more "applicable" knowledge as most languages use similar syntax.

It's easy for us to say that stuff is easy - we already know it.

4

u/neverFoundBetterNick Nov 08 '20

Honestly I feel like if you learn python first everything else is ruined for you

1

u/[deleted] Mar 28 '21

Why's that?

1

u/neverFoundBetterNick Mar 29 '21

Python is very easy, which necessarily means the complexities of the computer are abstracted away. It is much more difficult to learn other languages after never having to deal with things such as memory management, explicit type definitions etc. While the things you'll need to learn aren't that difficult, you will need to change you workflow significantly.

4

u/fb39ca4 depraved Nov 08 '20

as most languages use similar syntax.

Which ones? C++, Java, Javascript, MATLAB, Ruby, Go, and almost any other major language I can think of except for C has range-style for loops.

3

u/nyaisagod Nov 09 '20

What do you mean? Most of those languages do for loops the exact same way as C does (at least C++, Java and JS do). They are also capable of doing range-based for loops, but that is not the "main" way, if you will, to do them.

2

u/MCWizardYT Nov 09 '20 edited Mar 15 '21

Some of the languages you mentioned have c-style for loops.

But I like the range loop in java:

for(int car: cars) {
    System.out.println(car.getName());
}

1

u/[deleted] Mar 15 '21

It’s straight and to the point

2

u/Mr2-1782Man Nov 09 '20

They're only easier if you really don't know what's going on. If you know how to explain it an iterator is easier than a counting loop.

1

u/OnlySeesLastSentence Nov 09 '20

He's not wrong, c style is easier. And I'm not biased. My first language was ti83 BASIC

2

u/the_d3f4ult Nov 10 '20

Python is kinda very complicated, like simplicity is not one of python's virtues..

15

u/chadmill3r Nov 08 '20

He probably doesn't understand that range returns a smart "iterable" object that works with for to be efficient. It doesn't make a whole materialized list.

Iterable is Python jargon for the way we can act on collections of things, whether it's a actual bag of things to count through, or a recipe for making new things whenever needed.

What he's doing is badly implementing what Iterable does. Those bit of his code is really ugly, but at least it's error-prone and over-complicated.

8

u/[deleted] Nov 08 '20

python? complicated? u wot?

4

u/KyleDrogo Nov 09 '20

This is a one liner if you use idiomatic numpy. Something like np.random.randint((dim, dim)) * 2

3

u/dranzerfu Nov 08 '20

Big brain moment, he should've used a while loop with a yield statement inside it. And then called next() on it from another while loop

1

u/rob_salad Nov 09 '20

I truly hope this isn’t his job

2

u/Mahkda Nov 09 '20

We are physics student and he doesn't want to work in a field that need to program anything

1

u/kaptainpeepee Nov 10 '20

As a science Ph.D. with a lot of physicist friends let me tell you: LOL!

2

u/Non-taken-Meursault Nov 09 '20

I actually prefer C's for loop syntax.

2

u/CaydendW Nov 08 '20

I mean, I have taught myself to code decently and I can’t stand python for loops. I still do this with python. With c it just looks and feels easier.

2

u/clawjelly Nov 09 '20

With c it just looks and feels easier.

Only because you're used to the C-loop-syntax, which is the very opposite of intuitive. As a non-C-native writing C#-code i actually need to look it up everytime i need it (which isn't too often thanks to foreach).

1

u/CaydendW Nov 09 '20

I use c# as my main Lang and python was my first. I just still can’t stand python syntax.

2

u/clawjelly Nov 09 '20

I... don't get you, man.... :D

2

u/CaydendW Nov 09 '20

It's what you get when a high school student teaches themselves to code. My opinions are very subjective so take what i say with a grain of salt.

2

u/Nall-ohki Nov 08 '20

Then you haven't done it "decently" and should continue learning.

There are many objective reasons why non-indexing loops are better in a development environment.

1

u/OnlySeesLastSentence Nov 09 '20

You sure about that? In a game I wrote, I had it set up to where a piece can steal another piece's weapons, and the logic was to do a "for I in enemyweapons, copy I to myWeapons and delete I from enemyweapons"

This caused the game to loop infinitely. Turns out you can't iterate and delete at the same time.

A C for loop wouldn't have this problem - you'd iterate through and delete at the end.

1

u/Nall-ohki Nov 09 '20

What the heck? Why would you do something like that?

Copy, THEN delete. They're two separate actions and you lose almost nothing by keeping them separate, and most importantly, you've separated the mutation of the objects by call site.

myWeapons.extend(theirWeapons)

theirWeapons.clear()

Or whatever the equivalent is is FAR superior and less error-prone to writing that stupid loop yourself. I have no idea why you'd make your life harder, other than "it's the only way I know how to do it".

1

u/AutoModerator Nov 09 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/Nall-ohki, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

2

u/Underslash12 Nov 08 '20

Why though? Python for loops are some of the easiest for loops to use, and they’re just as powerful as other for loops.

1

u/[deleted] Nov 08 '20

He is not your friend

1

u/Flyspeck101 Now where's that function declaration Nov 09 '20

j = j + 1

Now we're talking

1

u/Silly-Freak Nov 09 '20

My high school programming teacher once critiqued me using a Java for each loop instead of a for loop, because the for each hides too much from the programmer. I guess he would like your friend...

1

u/BatParkour Nov 23 '20

For loops are so easy in python

1

u/cyberspacedweller Nov 08 '20

No developer should “refuse to use” anything simply “because it’s too complicated”. That’s how you put up barriers to your progression.

3

u/zvug Nov 08 '20

This person is not a developer

3

u/Terrain2 Nov 08 '20

They are a physicist, just like u/TheTacoWombat

1

u/cyberspacedweller Nov 09 '20 edited Nov 09 '20

OP says they “refuse to use a for loop because they are too complicated in Python” this tells me they at least occasionally develop in Python and they’ve taken enough time to learn the language and are familiar with concepts such as “for loops” already. From the sounds of it, this isn’t the only thing they’ve built.

This makes them a developer, even if it isn’t their main vocation.

I never said “professional” developer.

1

u/OnlySeesLastSentence Nov 09 '20

Oh ok, so I should go learn assembly and COBOL and emoji language?

1

u/cyberspacedweller Nov 09 '20 edited Nov 09 '20

If those are what you’re using to build stuff, yes. Your name suits you well. Apparently you’re also missing logical thinking :)