Don't ever write Python code like this

Поделиться
HTML-код
  • Опубликовано: 28 сен 2024
  • My FREE guide on how to become a data engineer:
    karolinasowins...
    I've spent a lot of time refactoring other people's code, and here's the summary: 6 Python mistakes to avoid!
    Why you should never write your Python code like that? There are a few reasons:
    -it looks unprofessional
    -it makes your code hard to read
    -your colleagues are secretly going to hate you
    -messy code will bite you later, when it starts failing and you have no idea why!
    So, join me on this Python code refactoring journey, and don't ever write Python code like this ever again! :) Don't worry if anything from this video looks overwhleming to you - these are not even Python beginners' mistakes, they are made by beginners and more advanced users of Python alike. But it's time to learn Python best practices if you want to rock! :)
    pep8 style guide: www.python.org...
    Find me on instagram:
    @karo_sowinska
    And if you'd like to buy me a cup of coffee... :)
    ko-fi.com/karo...

Комментарии • 1,2 тыс.

  • @martijn3151
    @martijn3151 3 года назад +134

    04:05 in all fairness, replace is not the same as changing the first letter of a string to some other letter. It replaces all occurrences in a string and requires prior knowledge of the value you want to change (in this case 'C'). The proper way to do this, unfortunately very convoluted in Python, is: changedstring = oldstring[:index] + newcharacter + oldstring[index + 1:].

    • @jeroenvermunt3372
      @jeroenvermunt3372 3 года назад +1

      it's not convoluted if you just add it to a function with the index and new_characters as arguments :)

    • @adityad7602
      @adityad7602 2 года назад

      True but the string only has one capital letter.
      Which doesn't affect anything else in this specific use case.

    • @daveit1337
      @daveit1337 2 года назад +23

      Simple as that:
      my_name = 'K' + my_name[1:]

    • @legrinu
      @legrinu 2 года назад +2

      @@adityad7602 you don't know. And If you know what String your changing the changing is Not neccessary

    • @elmiguel1982
      @elmiguel1982 2 года назад +2

      Late to the party, but replace isn't convoluted as the documentation is pretty clear. You can pass a third argument to replace which occurrences you wish to replace: 0-N occurrence.
      str.replace(old, new[, count])
      Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
      The issue arrises when trying to replace an occurrence at a particular index. Then you would have to implement a method around the issue at hand.
      - Happy Coding.

  • @apmcd47
    @apmcd47 2 года назад +42

    The only addition I'd make to your improvements is add a main() function. You mention the variable myAge being a global where it was originally defined, but my_name and my_age are both global variables while they are inside the if block. Also using the 'for ... in' construct isn't so much Pythonic as good programming practice in any scripting language that supports it, as it is easier to read. The only reason to use an index in that way would be to access multiple lists, but Python has the zip() function for such a case.

    • @MasterHigure
      @MasterHigure 2 года назад +4

      You could also need more explicit access to the index. For those uses, you have the enumerate() function.

  • @alisterware8062
    @alisterware8062 3 года назад +65

    Pep 8 is a style GUIDE, it is not set in stone although is is a very good guide & one of the 1st things is says is "A Foolish Consistency is the Hobgoblin of Little Minds" if working on your own you can set your own guide for what works best. if you are working as part of a team then you should use the standards of your team.

    • @chaosordeal294
      @chaosordeal294 3 года назад +3

      A foolish little mind has the consistency of a hobgoblin.

    • @apmcd47
      @apmcd47 2 года назад

      True, but I suspect that many new projects will use PEP-8 as their style guide rather than use an internal style because they will be using tools like PyLint and SonarLint to check their code for consistency, and it's easier to use the default settings than configure them for yours (unless somebody has a configuration file lying around).

    • @BreetaiZentradi
      @BreetaiZentradi 2 года назад

      Always worth looking up WHY something is in there. 79 character line length for instance. The rational is that 80 chars or less prints on paper well and more importantly, Most screens are wide enough you can do a DIFF and side by side comparison. Can you set it to 150 or ignore it all together? Sure you can. But you will regret it when your trying to diff your code and your display is not 300+ characters wide.

    • @alisterware8062
      @alisterware8062 2 года назад

      @@BreetaiZentradi Also when reading the eye can scan 80 columns & return to the next line easily, much greater than that & vision starts to hunt for the start of the next line making reading uncomfortable.
      The publishing industry have many "Guidelines" like this - developed over 100's of years of experience.

    • @BreetaiZentradi
      @BreetaiZentradi 2 года назад

      @@alisterware8062 very good point. I like verbose_descriptive_snake_case_names but you hit the 79 character limit fast. You are forced into a vertical programming style. It works will for dffing later. I lose my long lines, but I end up with a better workflow.

  • @FenBender01
    @FenBender01 3 года назад +1057

    Good tips on writing python code. When you edit a video, keep the code on the screen for more time. 2 seconds are not enough to read it.

    • @gelanghaarteweile3048
      @gelanghaarteweile3048 3 года назад +148

      I know it's obvious but you do know you can pause the video?

    • @karolinasowinska
      @karolinasowinska  3 года назад +172

      I prefer keeping the dynamic pace, but perhaps I exaggerated a little! Thanks :)

    • @isidrodeleon673
      @isidrodeleon673 3 года назад +168

      @@gelanghaarteweile3048 We all know that video can be paused. But it is better to watch the video without pauses and understand it.

    • @dvtech4571
      @dvtech4571 3 года назад +9

      I think its a niche thing. Most programmers should pause video, cause' we usually finds out our own solution, but non-programmers should ask for the solution, if you want to catch-up more people try to expand your niche 🤗
      Oh and little trick: try subs, even (better) in another lenguaje(s), youtube algorithm should do the rest 🤗
      Thanks for sharing!

    • @giogio182
      @giogio182 3 года назад +17

      Yes, you can pause but sometimes she talks about something and shows only AFTER. It'd be nice to follow along.
      Also here (7:15) the editing starts before the transition has even ended. I mean, it's an obvious edit but maybe beginners need more details to follow.

  • @anotherbloodyhypocrite960
    @anotherbloodyhypocrite960 2 года назад +6

    I love this style of video showing code that works and then critiquing it and explaining why it should be changed is a really useful thing to see as a newbie learning code. You've got yourself another subscriber!

  • @MartinJaszczuk
    @MartinJaszczuk 3 года назад +6

    Seriously, these are really good tips. People coming from other languages may have a hard time with the Python way of doing for loops, I know it took me like a month to wrap my head around the current item, since you just name it in the loop and it's never used again. I first tried learning this when I tried to learn modern JavaScript, but didn't fully understand and use it until I revisited the topic in Python.
    Great video! Thank you!

    • @karolinasowinska
      @karolinasowinska  3 года назад

      Oh yes, the Python loops also weren't very intuitive to me for some time! But now I cherish them haha ;) Thanks!

    • @pxolqopt3597
      @pxolqopt3597 2 года назад

      I didn't understand function parameters for the longest time... like i used to never use functions and when I did I would misuse the hell out of them

  • @transientaardvark6231
    @transientaardvark6231 2 года назад +1

    Wow, thanks for the tip about try / except pass - I can now stop my Python scripts from inconveniently crashing like they normally do. I'll be making sure to always put that round my entire code from now on. I'm so glad the RUclips algorithm pointed me here.

  • @furiousfellow1583
    @furiousfellow1583 3 года назад +6

    Some tip: whenever encounter a try,
    /except/pass, add a #todo statement with what the program should do in case of a error, you might never implement it but at least it looks like you are aware of it 😆

    • @karolinasowinska
      @karolinasowinska  3 года назад +3

      Haha writing comments/todos is typically a very good idea!

  • @voxelfusion9894
    @voxelfusion9894 3 года назад +4

    I did exactly that in the thumbnail, but I had good reason:
    I was making a little web scraper with selenium, and wanted a function that closes an annoying cookie banner.
    Depending on your country, that cookie banner may not appear or will have different buttons.
    Removing the cookie banner wasn't necessary, just nice to have, so if it actually failed, it didn't matter, so I passed.

    • @fierce1340
      @fierce1340 3 года назад +1

      When you encounter an error, python will tell you the error (they're called Exceptions in python) that happened. You should always specifically check in your try except block for that exception because you won't be able to tell if you encounter a different error in the future. I do a lot of web scrapping with selenium and I've messed up a lot of collected data because I let every error pass through instead of just letting the program continue when it encountered the specific error I knew was going to happen.

    • @TinyMeatPete
      @TinyMeatPete 3 года назад +1

      As someone who makes so many bots with Selenium, I can tell you; you do not need a try except loop barely ever. You could just make it an if statement that checks if the cookie popup has appeared and if it has not them move on. If you want a full opinion, I'll happily check the code.

  • @osnofla13ify
    @osnofla13ify 2 года назад

    Welp, I definetly do like 5 of this mistakes. Thanks, I actually love this kind of videos.
    I study physics, so most of the programming I've learned by myself, I've become quite good in algorithms, but definetly lack the knowledge of stylizing my code in the right way.

  • @TWMist
    @TWMist 3 года назад +3

    with the try statement would it not have been better to have the except catch and display the error?

  • @ukrainian333
    @ukrainian333 2 года назад +1

    Few words about cycles with indexes - sometimes it really needed, but "n += 1" is not best way to do it (but it is way for juniors). Best practice are enumerate and itertools, yep, it's more complex, but at same time more faster =)

  • @ChewingGum113
    @ChewingGum113 3 года назад +11

    Thank you for sharing these examples! There are some I'm guilty of making in the past that I learn the hard way. I like the last one about passing data types of the parameters through functions, it refers to duck typing issues and helps avoiding it.

  • @justinharass1416
    @justinharass1416 3 года назад +2

    I don’t think that the empty try/except block is “bad”. I can see uses for it. Like when you expect an error, and don’t want that error to stop the whole program.
    I do want to add that while leaving the except block empty is ok, just printing the error is much better instead of getting rid of the whole try/except block…

    • @martinmckee5333
      @martinmckee5333 3 года назад

      Having it print the error is my preferred style if I do not have a specific need to handle the error immediately or I'm testing calling code to ensure that the errors I would be protecting against don't, actually happen.
      It avoids to completely unknown failure problem while preventing the errors from propogating.

  • @jj-big-slay-yo
    @jj-big-slay-yo 3 года назад +4

    Or just use black and isort for formatting. and then pylint or flake8 as an eslint replacement for python.
    And also a good tip: do not try to be too clever with your [incomprehensible without a long comment] code with binary operators and the clever but convoluted use of nested list comprehensions / generators with some lambdas or so.

    • @karolinasowinska
      @karolinasowinska  3 года назад

      Great point about making the code as easy to read as possible!

  • @andrecarvalho-li9kd
    @andrecarvalho-li9kd 2 года назад +1

    I'm just starting college for software engineering, and python is the first language i picked, didn't know a lot of the things you showed. Really helpful video, tysm.

  • @thefelixgan
    @thefelixgan 3 года назад +4

    Data Saving Mode:
    Mistakes
    1. Try and except: pass Block
    2. Mutating a string
    3. Using the camelCase for function and variable names
    4. Using global variables
    5. Unpythonic looping
    6. Not specifying data types

  • @palficsaba1710
    @palficsaba1710 3 года назад +1

    Okay Karolina. Okay. I see Your point. I accidentally clicked on Your video, but You milady got Yourself a new subscriber. Very good points and on topic, clear sentences and insightful perspective. Thank You.

  • @laurinneff4304
    @laurinneff4304 3 года назад +3

    You forgot one thing: variables in an if name main block are still globals. All code should be moved into functions

  • @thomasstambaugh5181
    @thomasstambaugh5181 2 года назад +1

    I appreciate you posting this. I have a few comments:
    1. This is perhaps silly, but I'm watching this in my enclosed front porch while smoking a cigar. You have a smoke alarm chirping in the background (such as at 3:06). I just opened my windows while it's 8 deg F outside and went through my house looking for the offender to silence. Little things like this can be a real distraction!
    2. Python was created to emulate -- and is heavily influenced by -- Smalltalk. The practice of camel casing was created by Smalltalk. No matter what PEP-8 says, legions of very experienced and very good Python developers use the camel-case convention. It allows a myriad of valuable practices including using a lower-case leading letter for local variables and an upper-case letter for (more) global variables. You don't even mention classes -- EVERY class name should start with a capital letter (because it is a global). Without camelcase, there is no easy way to see the difference between a variable name ("foobar") and class name ("Foobar"). A typical scenario is a local variable that holds an instance of a class. Good and readable Python code is "mySQLAdapter = MySQLAdapter()". Using snake case, this turns into "my_sql_adapter = my_sql_adapter()". Which is more understandable for a developer who is trying to get a crashed public server up and running? Not to mention that adds more "line noise" characters. Python was created to avoid such things.
    3. Type hints are WAY beyond the capability of a new Python developer watching this video for help. Python IS a dynamically typed environment. It was designed that way. It is also an OO language, and was designed for object-oriented programming. Most functions in good Python code are methods on a class. In that context, type hints lead to paralysis and terrible spaghetti code unless the developer -- and the rest of the app -- rigorously follows the "Liskov Substitution Principle" ("LSP"). That is IMPORTANT (google it!). Having said that, a Python package that is following LSP and using camelCase doesn't need type hints. Another venerable tradition from Smalltalk is to prefix each argument with "a" or "an", and then add the expected type ("String") as a suffix. So instead of naming the variable "age", instead name it "anAgeString". Now you don't need a type hint.
    Another stylistic comment -- if I was reviewing your example, I would have suggested that you use an f-string. I would suggest that your initial print statement should look something like:
    print (f"""My name is {aNameString}. I'm {anAgeString} years old, and these are my goods:""")
    I'm pretty sure there's a list comprehension that would be even more Pythonic than your example. Something like:
    [print(each) for each in ['apple', 'blueberries', 'cake']]
    These features -- f-strings and list comprehensions -- were added in Python 3 in order to make code like this more readable. They aren't that hard, and I think new Python developers are better off getting those in their hands than learning "simpler" things that have to be un-learned in a real shop.

  • @anton993
    @anton993 2 года назад +2

    6:42 I think that for this fix you could also use the .join() method, which displays the elements of the list as strings and between spaces!
    So instead of having a for loop you could have:
    print("
    ".join(my_goods))

  • @aadityagupta250
    @aadityagupta250 2 года назад +2

    I wrote except pass once in my life. I got bullied the same way as Richard from Silicon valley for linear searching in a sorted list. Never again.

  • @laszlofazekas5700
    @laszlofazekas5700 3 года назад +6

    About snake_case and PEP8: The most important thing is that to stay consistent. For instance in my case: I always use camelCase with methods and snake_case for functions/variables.

    • @karolinasowinska
      @karolinasowinska  3 года назад

      True. Using a mixture of many styles is definitely the worst thing someone can do!

  • @triularity
    @triularity 2 года назад

    The try/{catch,except}/ignore is useful, but only in very *limited* and specific situations where the operation failing is 100% option. A couple which come to mind:
    - You default to a fallback implementation and are trying to load an optional "better" version (e.g. a native system library which does it 100x faster). If it fails, it will continue with the default version. Perhaps it could output a warning, but this could be considered wrong if 90% of users aren't using the optional library and dislike the needless warning.
    - Some resource is being released (possibly just before the program exits) and has no useful way to deal with the error (e.g.. an input file is being closed), and propagating the error would only prevent further important cleanup. A better justification for at least logging a warning exists here, but continuing is still the ultimate action.

  • @aycc-nbh7289
    @aycc-nbh7289 2 года назад

    I was actually taught in university that camel case _should_ be used for function and variable names and I was never taught about using snake case, so perhaps there could be competing standards for variable and function names. I was also taught that all-caps names are reserved for constants, not global variables. I was taught Python first at university, but my first experience with snake case was with the default functions in C++.

  • @SealedKiller
    @SealedKiller 3 года назад +3

    I love how the accent sometimes goes to a perfect british accent.

  • @NoahSightman
    @NoahSightman 2 года назад +1

    3:55 AM: I didn't expect to find something like this, but I just realized that I didn't know how much I need it

  • @aniketpurohit8613
    @aniketpurohit8613 3 года назад +4

    f-strings can be a useful addition! :)

  • @ramonitoomandam619
    @ramonitoomandam619 2 года назад +2

    great video.
    what i think might be an improvement
    1. use larger fonts, not everyone watches youtube on >1080p desktop pc, some might watch using mobile, if they did, they won't continue if they can't see the code using small screen. you can magnify certain parts, but I think it might be too much work on editing.
    2. you are beautiful, my tendency to Simp becomes higher as the video progress, you might consider making your explanation video a bit smaller like vscode minimap, then maximize in the end when you are wrapping up.
    hope to see more. thanks

  • @kafarahat
    @kafarahat 3 года назад +20

    In my opinion, using global variables is not bad, actually there are cases where it can be pretty useful.
    I would rather say that global variable manipulation is a bad practice with very small number of exceptions that I have seen.
    Btw, nice channel. Subbed.

    • @karolinasowinska
      @karolinasowinska  3 года назад +2

      Of course, there are cases when it's useful to have global variables. But in general, people tend to abuse it! Glad you like the channel! :)

  • @kevinmcaleer28
    @kevinmcaleer28 2 года назад +1

    Great video - Thanks Karolina!

  • @fan_juggler
    @fan_juggler 3 года назад +4

    About try-except, for example, when you are writing something like TUI interface with curses, there are one hundred ways a user can crash the program by messing with the terminal, so it's much cleaner to just write try-except than trying to catch every possible error, for each of which you would need to write 'pass' anyway :)

  • @relytheone853
    @relytheone853 2 года назад

    I need a only python job. The language is just entertaining. Thanks for your help, this keeps me going. Keep up!

  • @PBMS123
    @PBMS123 2 года назад

    Why did you talk about a for loop and then show a while loop?
    Using while instead of for is bad coding in C, or in most languages. For is far better than while, because while is capable of an error that causes it to loop infinitely, whereas a for loop predefines the number of times it will run.
    i.e.
    for (int i = 0; i < 5; i++) {
    cout

  • @CaptainCsaba
    @CaptainCsaba 3 года назад +4

    I am only guilty for one of these but oh boy is it a big one for me. As Somebody who learned C# after Python I changed my style to the C# style of variables being camelcase and functions being pascalcase. I tried so long to create code with snakecase but it is just so unreadable for me. Functions and varibles have the same style, and it becomes bad to my eye to differenciate them. I want to move over this so bad but I just can't. I literally can't read the same long code as well in snake case as opposed to camel/pascal case.

  • @MisterNorthernCanuck
    @MisterNorthernCanuck 2 года назад +1

    Coming from Javascript, I appreciate these tips and standards, thank you!

  • @davidfont2596
    @davidfont2596 2 года назад

    I immediately implimented these things in the two programs that I'm writing to do my homework for me. No one will ever see these programs because I'll just turn in my assignments but, It is a good practice to start writing PEP8 compliant code in private because then it will be automatic when I'm writing code for a job.

  • @donjindra
    @donjindra 3 года назад +8

    The worst mistake, bar none, is that most programmers seem to think their favorite language is self commenting. It isn't. Please learn to thoroughly comment your code, folks.

    • @karolinasowinska
      @karolinasowinska  3 года назад +1

      Really good point!

    • @james4727
      @james4727 3 года назад

      trying to review your own code for exams taught me the importance of this hahaha. Now I write comments as if im having a conversation to myself.

    • @eklipsegirl
      @eklipsegirl 3 года назад

      Good variables’ and functions’ names are better than excessive comments.

    • @donjindra
      @donjindra 3 года назад +1

      @@eklipsegirl Names are important, but you're naive if you think that helps much. I see this mindset a lot and it's why so much code is so hard to maintain. Good comments do not simply restate what's already there in the code, or find perfect names. You should tell us in plain language what the function is supposed to do, how it's supposed to do it, and maybe even why this solution (out of many possible solutions) was chosen in the first place. Otherwise the second programmer to look at the function has to trust your code has implemented what you intended to implement. Experienced programmers know that this is not necessarily the case. Bugs are everywhere. So he has to "reverse engineer" your intent. Even if he can do this reliably, it takes time. The original programmer could have and should have saved him this time.

    • @james4727
      @james4727 3 года назад

      @@donjindra this ^^^ I try to make your code as unambiguous as possible.

  • @zentraidee9701
    @zentraidee9701 2 года назад +1

    Even implied the worst-case scenario of coding>Wish you do some basic tutorial on python then the step by step process to improve. Thanks for your video.

  • @Yeah_bruv
    @Yeah_bruv 2 года назад

    Been coding some months now but never knew about Pep8 - very helpful! Good video

  • @Nedwin
    @Nedwin 3 года назад +1

    Very nice sharing Karolina!

  • @janisir4529
    @janisir4529 2 года назад +1

    1000 lines of code, written by someone else a year ago? That's basically a dream scenario!

  • @yan_afrukh
    @yan_afrukh 2 года назад

    I was never aware about those pep8 guidelines. Thanks for this enlightenment, as a new student who's discovering python, respecting norms since the beginning would save me a lot of time later

  • @Rickety3263
    @Rickety3263 3 года назад +3

    Great video! I changed the battery in my smoke detector but then I realized I was good

    • @karolinasowinska
      @karolinasowinska  3 года назад +2

      Haha wow, what a quick action on your side. It took me half a year!

  •  3 года назад +1

    Loved it. I don't agree with the last one, in that you «should not ever write Python code like that», i.e. without specifying data types in the signatures. I think it's importance depends on the context. E.g, for scripting, I would totally avoid that.

  • @HawkmasterStambaugh
    @HawkmasterStambaugh 3 года назад +4

    The camel case bit is laughable. I've seen both from a lot of people in python throughout several jobs.

    • @PbPomper
      @PbPomper 2 года назад

      I guess that's because snake case is hardly used outside of Python. Most OOP languages use a mixture of camel and pascal case to distinguish beween classes, methods and variables. Snakecase is usually just used for constants.

  • @andrewregrets
    @andrewregrets 3 года назад +1

    It is also a good practice to put the before picture on the left and the after one on the right side of a screen ;)

  • @timfedotenko7557
    @timfedotenko7557 3 года назад +1

    I agree with all the corrections, but what we should always keep in mind while trying to make code "beautiful" or "pythonic", is KISS principle.
    Sometimes it is better to keep code not "beautiful", but clear and effective.

  • @waterdrinkert
    @waterdrinkert 3 года назад +1

    I became a spacebar ninja after trying to watch this video. The code disappears from the screen so fast I can't even pause fast enough.

  • @eklipsegirl
    @eklipsegirl 3 года назад +4

    There is a legitimate reason to use camel case: working with PyQT. Its classes and functions are all camel-cased, so it makes sense to follow along.

    • @karolinasowinska
      @karolinasowinska  3 года назад

      I agree, it makes sense then!

    • @nysaea
      @nysaea 3 года назад

      I'd argue there's another good reason, within reason and assuming consistency throughout the code: I will never understand why anyone would think snake case makes names more readable than camel case. Code written in snake case is barely legible to me because it visually tricks my brain into seeing several entities instead of one.
      It's one of those things where PEP8 start leaving common sense and safety territory and enter aesthetic suggestion territory, and it bothers me that anybody would use those particular recommendations as gospel.

  • @vikramvijay3264
    @vikramvijay3264 2 года назад +1

    It was Like a piece of cake ...thank you very much ...I'm an new subscriber 💐

  • @Millionaires.Empire
    @Millionaires.Empire 2 года назад +1

    a couple things you forgot: always surround functions with 2 blank lines, my_age=16 should be my_age = 16, using print(f"") in your def makes the code look cleaner. using function names that make sense is always better. and be careful for ghost tabs, vscode sometimes ghost tabs stuff.

  • @rhalfik
    @rhalfik 3 года назад +3

    Jesteś bardzo dobrym nauczycielem.

  • @kojack57
    @kojack57 2 года назад +1

    I spent most of this video looking up at my smoke alarm.

  • @hassainehassen5700
    @hassainehassen5700 3 года назад +3

    Thank you , you have directed me to pep8 style

  • @blackhole6310
    @blackhole6310 2 года назад

    The reason for the "unpythonicity" of the while loop here is not just because python has a nice looping function that handles variables and whatnot, it's mainly because the function for is using the C implementation instead of calling the C interpreter multiple times (for each manual comparisons and assignment). This is the first reason for using the for loop in the first place, however you are right when saying it's less prone to mistakes although while loops have a different purpose.

  • @klin1klinom
    @klin1klinom 2 года назад +1

    Those are true as well for most other modern languages and their up-to-date revisions. E.g., Java had for-each type of loop since version 8, and C++ introduced range-based iteration in C++11. Obscure exception handling is just bad in any language)

  • @caitlinmclaren2695
    @caitlinmclaren2695 3 года назад +4

    Thanks for your awesome videos, but: based on Robert Martin's "Clean code" book, it's better to use class variable than passing function parameters. Instead of that, You should have fixed the biggest problem with the code: "run_this_baby". Moreover, you can loop with or without indexes in Java, Python, and almost any other programming languages.

    • @karolinasowinska
      @karolinasowinska  3 года назад +2

      Good point, I was trying to be funny with "run_this_baby", but effectively I introduced an anti-pattern. Oops, thanks for pointing it out though. Of course, function names should be representative of what the functions do.

    • @alpers.2123
      @alpers.2123 3 года назад +1

      Clean Code is not clean

    • @The_Lawnmower_Man
      @The_Lawnmower_Man 2 года назад +1

      To elaborate on the point about " _you can loop with or without indexes in Java_ ":
      Modern Java, modern C++, and C# all support this index-less style of for-loop, which sometimes is colloquially called a "for-each loop", and particularly in C++ is called a "range-based for loop". (The actual keyword used for this kind of loop is "for" in both C++ and Java, whereas in C# it's "foreach" instead... and in addition to that, C++ also has a standard-library function named "for_each", which is meant for use in functional-programming situations & takes a function-value to be used instead of a conventional loop-body.) And, same as in Python, it's generally preferred to use this style of loop wherever possible when writing new code in those languages.
      Furthermore, even *old* versions of Java and C++ had the concept of an "iterator object" which could be used as the loop-variable when looping through a collection-object such as a std::vector or a std::list in C++ or an ArrayList or a LinkedList in Java. (In old-style Java, iterator objects were mainly intended to be used with "while" loops, whereas in old-style C++ they were intended to be used with C-style "for" loops.) I.e. an iterator object could be used *instead of* using a plain integer as the loop-variable.

    • @tomwilson2112
      @tomwilson2112 2 года назад

      @@The_Lawnmower_Man Yeah, I saw this as not a great example, because there's nothing unique about the Python FOR loop... it's just a "for each" in any other reasonably modern language.

  • @randlekonoble1011
    @randlekonoble1011 2 года назад

    Try & except is a life save saver when your importing 30 different functions from different files, just makes my code simple & makes it easy to debug !!

  • @NerdyStarProductions
    @NerdyStarProductions 2 года назад

    I feel like generally a lot of the tips are good high-level things to keep in mind as generic rules, and certainly would agree with the specific examples you give, but I think there are certain situations that warrant breaking these "rules".

    • @tomwilson2112
      @tomwilson2112 2 года назад

      It's a rule that all rules are made to be broken... but it's also a rule that if you think this is the time to break a rule, you're wrong. ;-)

    • @NerdyStarProductions
      @NerdyStarProductions 2 года назад

      @@tomwilson2112 Well yeah, if you just _think_ you should break the rule, you're probably wrong. But most programmers don't break a rule because they think they should, but rather because they can justify it. And if you are well-versed in the language, then you usually wouldn't be making invalid justifications.
      It's important to keep in mind that most these rules are just code smells, and code smells are not perfect tests for code correctness. They're just indicators that something seems potentially wrong, and should be double checked.

  • @happymonster9098
    @happymonster9098 2 года назад +1

    I am a java/C programmer who made the code for my current business in python without knowing it can be typed. You just gave me the exit from the untyped hell and thousands of hours of refactoring!

    • @nukularpictures
      @nukularpictures 2 года назад

      It's still not typed. It is just a hint. You can still do whatever you want to it.

  • @junealexissantos4341
    @junealexissantos4341 2 года назад

    I dont have proper cs background and just a year in coding. tips were really helpful ! Thank you🙏🏽

  • @weltkaiserendzeit2417
    @weltkaiserendzeit2417 3 года назад +3

    Well to be honest I wasn't aware that you could specify variable types in the arguments and output of a function even though I've been coding in Python since I was like 7
    It is astonishing how much left there is to learn

    • @tubeincompetence
      @tubeincompetence 3 года назад +1

      As I wrote in another comment. I don't think Python really does anything with this information anyway and you'd need a separate type checker for it. And it's something introduced in 2015 so I can easily see people not knowing about it yet. It just exists there if we want the user to see it most of the time (at least in your own private projects/smaller codebases).

  • @raym6415
    @raym6415 2 года назад

    Good points, and of course not that you came up with them, but the most important thing that you must have represented is the code, not something small and illegible on a computer screen for two seconds.

  • @owlcatxx
    @owlcatxx 3 года назад +4

    Love this video! As a newb python programmer, now I can pretend I know what I'm doing :D
    (Oh and for your fire safety, I hope you changed the battery in your fire alarm after filming his video! We can hear it beeping!)

    • @karolinasowinska
      @karolinasowinska  3 года назад +1

      Hahah I have to finally do it... you're the 100th person to notice this. :D

    • @JeffreyChadwell
      @JeffreyChadwell 3 года назад

      Thank you! I thought I was hearing things.

    • @vekyll
      @vekyll 3 года назад +1

      try:
      make a youtube video about Python
      except FireAlarmBatteriesEmpty:
      pass # ;-PP

  • @Djzaamir
    @Djzaamir 2 года назад +2

    I really loved the video, you explained all the issues in such an enjoyable fun manner. Thank you. I'll remember these :D

  • @Zeero3846
    @Zeero3846 2 года назад

    Case convention can vary by language, but I usually try to stick with the most predominant convention for each language if I know them.
    As for everything else, across languages, it is usually best to:
    - Avoid globals
    - Minimize the scope of a variable
    - Use guard clauses
    - Avoid throwing away exceptions
    - Mutating state, while not evil, is often harder to test and reason through
    - Having more than 3 levels of indentation could probably be written in less with greater clarity and maintainability
    - Remember Batch is an awful language, and never let anyone tell you otherwise.

  • @Manas-co8wl
    @Manas-co8wl 2 года назад

    4:17 This is the only point I have somewhat of a gripe with. Yes I know Python has standards, in fact every language has a standard. But ultimately they are still guidelines and not to be enforced. c++ used to have all lower snake case for both members, methods, and classes and people rarely follow them anymore.
    More important I think is consistency in YOUR code. You shouldn't have for example an upper camel case method in one place and a lower snake case in another, and if you do you should have a really good reason for it.

  • @AndrewPalmerJazz
    @AndrewPalmerJazz 2 года назад

    I've been going over the PEP-8 style guide closely, and one other thing it mentions is not to lie about your age.

  • @marcinszeremeta5411
    @marcinszeremeta5411 2 года назад

    Just a tip. We don't loop over collections like this in C++ ether. We don't say in uncplusplusic (maybe we should :D) thou. you just do
    for(auto& element : collection)
    doImportantStuff() // yeah, Camell Case is ok in here :D
    anyway, good video :)

  • @kayakMike1000
    @kayakMike1000 2 года назад +1

    Swallowing exceptions is lousy in any language... I log warnings and maybe reraise the exception...

  • @davidaw104
    @davidaw104 2 года назад

    I don't understand if this type of error logging is much better then having the console prompt you where the error comes from. After all it shows you where the error comes from with an arrow key.

  • @troymann5115
    @troymann5115 3 года назад +2

    Nice video! Might be easy to replace your for loop with a list comprehension: [print(item) for item in my_goods]. Comprehensions are faster than for loops.

    • @karolinasowinska
      @karolinasowinska  3 года назад

      Good point! Thanks:)

    • @Victor_Marius
      @Victor_Marius 3 года назад

      Why not print(*my_goods, sep="
      ")? You will avoid memory duplication!

    • @LittleLily_
      @LittleLily_ 3 года назад

      @@Victor_Marius Some people might not be familiar with that syntax, so the more readable alternative to that imo would be print("
      ".join(my_goods))

    • @Victor_Marius
      @Victor_Marius 3 года назад

      @@LittleLily_ good luck with that form for lists of non-strings

  • @m.h.6470
    @m.h.6470 3 года назад

    Point 7: use prepared statement strings with values that come from outside your method/function. Don't just use them directly. In this case it would look like this:
    print("My name is {a_name} I'm {an_age} years old and these are my goods:".format(a_name=name, an_age=age))
    Sure, in this case it is just a print and you know the inputs, but you never know, what people might be using it for...

  • @insu_na
    @insu_na 2 года назад +1

    First of all: You are entirely correct and you didn't need me to say that.
    Second tho: I love try: do() except: pass
    I *could* include libraries to do checks for whether or not files exist when I want to read all existing files with a given pattern into an array, but why should I when I can just read them in when no error occurs and when my program looks for a non-existing file to read in it just fails silently?
    Sure it's not clean, but it's easier and it can't break in unexpected ways, because breakage is the feature I expect.
    The particular example I last used this on is when I wrote a fan controller for my computer on Linux. I want to get values from hwmon that tell me the temperatures of certain components, but Linux does this amazing thing of initializing hwmon paths completely at random, so what was hwmon3 last boot could now be hwmon1 and so on. It's completely unreliable. So what I do is just iterate over every single hwmon, try to read the contents of a file and if it's successful, add the path to that file to a list of paths and if it fails well that file doesn't exist and python will throw a filesystem exception. But if it doesn't exist I don't want to add it to my list anyway, so I can let it fail and sleep soundly, knowing that other types of actually important errors are handled later in code.

  • @TheMorisBlack
    @TheMorisBlack 2 года назад +1

    Good video! But you could potentially show people how to use try: except: properly not just say it has no use. I personally use it for small debugging like instead of showing me errors that don't give me any real info I get everything I need as an output in case of an error(anything you want like type or size or something ). Like if I work with a file that has over 100000 symbols and something inside is cousing an error try can be very useful.

  • @gaalmarcell1410
    @gaalmarcell1410 2 года назад

    Great time compareing those two codes for a second just to pouse and see that the new one doesnt work

  • @myronww
    @myronww 2 года назад

    Computing everything on the return line in a massive blob of a run-on code statement

  • @macbobXD
    @macbobXD 2 года назад +1

    thanks 1st tip is what i will use to make life harder for others 👍

  • @kebakent
    @kebakent 2 года назад

    I'd test the string thing in the interactive interpreter, see the error, and do it differently

  • @Omnifarious0
    @Omnifarious0 2 года назад

    It's awful for several reasons. One huge reason is that it will catch SystemExit, for example, so some random piece of code down your call tree will want to exit the program, and then that catch will keep it from happening without even a comment. It will also catch StopIteration, and also KeyboardInterrupt, which is thrown when you type Control-C. It's horrible.

  • @PythonDevelopment
    @PythonDevelopment 2 года назад

    Using the snake case is true for created variables acording to PEP 8. I used only it

  • @zimcoder
    @zimcoder 3 года назад

    for the array example, C# has the foreach way of looping through. it's basically the same thing as you show there.

  • @denn9484
    @denn9484 3 года назад +1

    I love your attitude and energy. Nothing about this video is boring :) Learned a bit too! Sub'd.

  • @noel5573
    @noel5573 2 года назад

    Replacing a standard for loop with a foreach is not „pythonic“ by any means. Its a common practice in all modern languages (including later iterations of Java, c# and so on)
    Also, Using a traditional for loop is not an anti-pattern if you actually want the index. Simply different use-cases.

  • @harigovind6706
    @harigovind6706 2 года назад

    1:18 you can't say that code is awful or wrong cause it depends on the need.i use it often cause I need to try something and if error happens I just want to continue the execution rather than doing any other thing in except block and later execution does not depend on that try block.i just want to continue execution without breaking that's all.but it's a better practice to also log your error instead of just pass

  • @FelixMoBu
    @FelixMoBu 2 года назад +1

    Did no one hear the smoke warner? I cind a freaked out because I thought it was in my apartment and every time I paused the video to look for my smoke warner they where silent and I set down to continue watching... Hard times ^^

    • @karolinasowinska
      @karolinasowinska  2 года назад

      Hahah sorry!

    • @FelixMoBu
      @FelixMoBu 2 года назад +1

      @@karolinasowinska that settles me even more, so it was definitely not only in my head. I appreciate!

  • @thefrub
    @thefrub 2 года назад +1

    I went and checked my smoke alarm after watching this video. Change your batteries lol!

  • @lollisko
    @lollisko 2 года назад +1

    3:06 Karo! Change the battery on your fire alarm! No pass at there honey!

  • @talon24
    @talon24 3 года назад +1

    cool, except why did they change from camel casing? like almost every other language its the standard. Was it just to be contrary using snek casing? not like it adds readability, feels like way more useless shift key and upper right use of the keyboard overall.

  • @computerscience1017
    @computerscience1017 2 года назад +1

    Great tips. Subscribed!

  • @lordmuffin111
    @lordmuffin111 2 года назад

    In the refactored code in the first print statement you should use format …

  • @peterholzer4481
    @peterholzer4481 2 года назад

    Small nitpick: The ALL_CAPS convention applies to constants, not global variables.

  • @IvanMiletic
    @IvanMiletic 3 года назад +1

    Is it okay to use try except pass when I actually do want to ignore an error if it happens?

    • @karolinasowinska
      @karolinasowinska  3 года назад

      It's much better to write your code in such way that takes care of all the edge cases

  • @jazmin6031
    @jazmin6031 2 года назад +1

    I'm so new and so bad that I didn't know this was bad, hehehe. I will improve, I dream of being a decent developer one day

  • @princeofexcess
    @princeofexcess 2 года назад

    I would say if youre a beginner use snake_case but consistency is much more important than convention. If you are not writing a library you may choose to break this convention.
    Also im sure this wouldnt be on the list if Karolina was a strict camelCase proponent.
    If someone else hates your cases they can always use case converter plugin.
    You will meet tons of grammar natzis that hate your code because you deviate. That is the price you will pay for being different so choose to express yourself wisely. Its a dangerous world out there.
    Maybe the future is more accepting.

  • @pedrovpa1
    @pedrovpa1 2 года назад

    Not having to declare types is awesome, until you try to use as Index something Python defined as a float...

  • @tctrainconstruct2592
    @tctrainconstruct2592 3 года назад

    the replace in the string replaces all characters, so you didn't show actual item replacement code in python. For example if i have a fen string and i use fen = fen.replace("p", "q"), it doesn't just replace the first black pawn by a black queen, but all of them. Also, if we would want to replace character 7, how do we do that?

  • @ShootingUtah
    @ShootingUtah 2 года назад

    I detest snake cast naming! It's much easier to hit shift and a letter for a capital in camel case then it is to constantly be reaching up to the '_' character! Plus other languages style guides want camel case so I don't care what anyone thinks about it I'm always going to use camel case.

  • @stefanalecu9532
    @stefanalecu9532 9 месяцев назад

    06:43 yeah, all of the languages you mentioned have foreach loops too and unless you really need an index or something (and that use case would still not require that for loop since there's `for idx, elem in enumerate(arr)`).