Don't ever write Python code like this

Поділитися
Вставка
  • Опубліковано 20 жов 2024

КОМЕНТАРІ •

  • @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.

  • @blazep5881
    @blazep5881 3 роки тому +649

    5:34 even if you move the variable inside the if __name__=="main" : block it's still a global variable. If you really don't want it to be a global var you'll need to define a main function and use it there and call main inside the if __name__ block.

    • @SkrtlIl
      @SkrtlIl 3 роки тому +47

      Came here to say this. Lots of python programmers mistake that if-block for a main function

    • @HexenzirkelZuluhed
      @HexenzirkelZuluhed 3 роки тому +13

      Upvote, so I don't need to point that out.

    • @tubeincompetence
      @tubeincompetence 3 роки тому +2

      huh.. nice to know. :)

    • @davidcalebpaterson7101
      @davidcalebpaterson7101 3 роки тому +6

      Can someone explain in detail why global variables are "bad" and how to move it to main, I am trying to learn that.

    • @HexenzirkelZuluhed
      @HexenzirkelZuluhed 3 роки тому +35

      @@davidcalebpaterson7101 Global variables contribute to "namespace pollution". You can accidentally reuse common names. Also code is generally more readable when your variable's definition and scope is as narrow as possible. If you use a variable only in one function you *know* it can only affect that piece of code. A global variable *might* affect many other places as well, you need to check to be sure. So it basically it makes your job easier in the long run not to use them if you don't need to.

  • @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.

  • @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 3 роки тому

      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.

  • @apmcd47
    @apmcd47 3 роки тому +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.

  • @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!

  • @lordwelpa
    @lordwelpa 3 роки тому +69

    Also overusing "from X import *" is a plague. It seems to be a very benign thing but it could lead to serious issues. Been there, done it, spent a week debuging my code :)

    • @tobiasbergkvist4520
      @tobiasbergkvist4520 3 роки тому +13

      Actually, this is a great feature when developing your own modules. I often use this from a Jupyter environment while modifying Python-files I'm maintaining myself.
      You want to change a function in some random file (X)? Simply use "from X import *" and copy-paste the specific function into your notebook. Now you know that the redefined function will have all its dependencies from that file available. That also means you can start modifying the function while testing it, without worrying if it tries to call another function from that file.
      On a side-note, I think "from X import *" should never be used for third-party modules that you don't intend on debugging or modifying the source code of. It is a great debugging and development tool - but not something you want to leave in "finished code".

    • @MakeMoneyOnline-AI-ChatGPT
      @MakeMoneyOnline-AI-ChatGPT 3 роки тому +1

      yeah, the disadvantage is when debuging

    • @drheinrich940
      @drheinrich940 3 роки тому +3

      i must admit that i fail to understand why this is a bad habit. Could you elaborate ? I thought it was good practice beaucause it implied lighter library loading.

    • @MakeMoneyOnline-AI-ChatGPT
      @MakeMoneyOnline-AI-ChatGPT 3 роки тому +1

      @@drheinrich940 when you are working on a larger application, especially old codes without proper documentation (comments), it becomes little harder to trace back some codes and it takes more time to figure out which imports supplies a particular class or function, this is from my experience though.

    • @vekyll
      @vekyll 3 роки тому

      _One_ import * per module is ok. (So if you can trace everything else, what you cannot belongs to that module by elimination.) The problem is, it's hard to stop at just one. :-D

  • @minekpo1
    @minekpo1 3 роки тому +33

    5:18 I believe screaming snake case is used for constants, not global variables

    • @katalysmus
      @katalysmus 3 роки тому

      Yeah same

    • @vekyll
      @vekyll 3 роки тому +4

      They aren't that different, or at least they shouldn't be. If you need global names at all, they better be constant. Global variable that actually varies is worst of both worlds. :-]

    • @rawrproductions7961
      @rawrproductions7961 3 роки тому +2

      @@vekyll not necessarily true, here's an excerpt on when they would be useful, "global variables are something that should be used only when needed. I would rather use global variables than using some artificial constructs (like passing pointers around), which would only mask the real intent.
      Some good examples where global variables are used are singleton pattern implementations or register access in embedded systems." They're not the worst of both worlds, sometimes there are real applications to them being modifiable and not only constant. Very few, obviously, but they exist and have their place.

    • @vekyll
      @vekyll 3 роки тому +1

      @@rawrproductions7961 Since you mention "passing pointers around", you obviously aren't talking about Python. Yes, various languages have various criteria.

    • @nialltracey2599
      @nialltracey2599 3 роки тому

      That was my initial understanding too -- C constant conventions indicate to programmers that a variable should be treated as a constant.
      However, someone later pointed out that Python is a shell scripting language, and "screaming snake" is used for environment variables in shell scripting, and they aren't constants.

  • @alejandrocarvajal9068
    @alejandrocarvajal9068 3 роки тому +22

    Great video, I'm here a little late, One of the tips that could improve anyone's skill is to take a look a native functions and modules to avoid reinventing the wheel, most of the time the native modules have faster implementations for a task that you might need to solve.
    Personal tip: if you think you can do a better job and writing a better implementation than the native function, that just shows the lack of understanding and research skills.

    • @karolinasowinska
      @karolinasowinska  3 роки тому +1

      Good tip! You're right

    • @IHaveYourMilk
      @IHaveYourMilk 2 роки тому +4

      Do not agree with the "Personal Tip" for if it was generally true, we would have no new, better libraries at all (everyone would think they cant do better then the old stuff)...
      That said, I do agree that before implementing something (meaningful), you should research what is already done.

  • @aerosoftware
    @aerosoftware 3 роки тому +1

    Information correction regarding loops, that's more C style. In C++ it's a bad habit.
    C++:
    std::vector< std::string > my_goods{ "apple", "blueberries", "cake" };
    for ( auto const& item : my_goods )
    {
    std::cout

  • @hrudyplayz
    @hrudyplayz 2 роки тому +33

    Great video, i agree with most stuff mentionned here except for a few points, as well as add bit more precision:
    - Globals, even inside __main__ are still globals, they're just context-specific globals (which i agree are better than creating useless globals, no matter the context). In fact, even functions are globals in a sense, though they're handled in a better way.
    I wouldn't particularly tell people to avoid globals at all cost though. You should definitely avoid them if you make a library that is meant, for example, to be used with other projects (or even shared publicly). I feel like using them exclusively for a specific project is okay though. There's little chances that conflicts could happen or that it would have an impact if you handle your project correctly and don't just update every dependencies without checking.
    - The .replace solution to string indexing isn't great. It works in this particular example, but if you had multiple "C" characters it would mess all of them up. It is better to just write a replaceIndex method somewhere, that returns string[:index] + character to replace + [index + 1:].
    - The try except pass is indeed terrible. Using it to wrap the entire __main__ function is okayish. I mean it will work and will do stuff "as expected", but the program will just stop doing anything (crash if you will) instead of giving a useful output to both the dev and the end user. Basically, it's useless, not because it might mess with execution order and such (which definitely will happen if you use it anywhere other than the __main__ function), but because it just hides the fact that your program crashed, which is worse UX design than just letting the normal Python error happen.
    - The type indication is a good tip to give, i would just tell you to omit those if your function accepts multiple types for an argument for some reasons. I would also go against writing the return type this way, depending on the function (knowing that it returns None isn't generally useful for example). I would also recommend to use docstrings for this whenever possible, sometimes it may be better than plain type indications.
    - You should definitely use pythonic loops like shown in the video. I will also add that you should avoid using while loops for iteration in most languages. A while loop is slower performance-wise (as it needs to compare the values everytime) and harder to read and use as it needs both to have the initial index for the variable and the increment at the end of the loop. Some normal range for loops can be okay even in Python i feel, but if you use the value of the objects you iter for, definitely prefer the "for in" format. There's also the enumerate function that you can use as well, if you need both indexes and values.
    Please note that the opposite is true as well, don't write functions in a too "pythonic" way. Some people will tell you to use list comprehensions instead of for loops, and i'll disagree there, it's just a matter of taste, but for loops are definitely more readable than your usual comprehensions, you should use those but only on simple iterations, please try to avoid the nested comprehensions when normal for loops would do the same but more readably.
    - Finally, and i know this is controversial, but i disagree with your point on PEP-8. Your goal should definitely be to have a code as readable as possible, and sometimes PEP-8 goes against that. Some recommendations there actually make the code harder to read, and some are good things everyone should use. Rather than forcing yourself to use PEP-8, create your own style with coherence in mind. I, myself, personally use camelCase ("mixedCase") instead of snake_case too, i simply prefer the first one compared to the latter one which leads to way longer and harder to type variables (thank god autocomplete exists), i also like to use simple compound statements correctly spaced as blocks, which PEP-8 doesn't like.
    As for work on bigger, team-based projects, i would recommend writing a style guideline that most people in the team agree on instead of just using PEP-8. At worse, if people can't agree on something, just have the style required for some commonly edited or used parts of the code.

    • @raffimolero64
      @raffimolero64 2 роки тому

      > using camelCase in python
      😤

    • @hrudyplayz
      @hrudyplayz 2 роки тому

      @@raffimolero64 camelCase is better than snake_case, change my mind.

    • @Aoekin
      @Aoekin 2 роки тому

      definitely agree with the PEP-8 not all places I found out use just Pep-8, but have their own guidelines,.

  • @KutluMizrak
    @KutluMizrak 3 роки тому +1

    try except is for literally HANDLING EXCEPTIONS.
    it's in the name.
    you are supposed to handle SOMETHING with except. That's why it's there.

  • @ayva1106
    @ayva1106 2 роки тому +3

    Reading the pep8 I didn't even realize how much stuff I picked up automatically from reading other people's code and didn't even need to think about

  • @Skatche
    @Skatche 2 роки тому +1

    Hard disagree: snake case is unergonomic. I won't risk carpal tunnel syndrome to fit with what some foreign body deems "standard". Camel case isn't perfect either, but it's a lot easier to type.

  • @sprintwithcarlos
    @sprintwithcarlos 3 роки тому +46

    Even though Python does not enforce data types, your advice about using type hints is great. This is a very good video
    Happy 2021, hope your channel grows a lot because your content is quite good

    • @karolinasowinska
      @karolinasowinska  3 роки тому +4

      Thanks so much, that's very motivating to hear! :) All the best to you in 2021!

    • @AlexAcostaB
      @AlexAcostaB 3 роки тому +1

      Also that it is available from version 3.5 (PEP 484) according to documentation. Perhaps I'm wrong in my research. Great video btw :D

    • @MateuszAdamczyk
      @MateuszAdamczyk Рік тому

      Data types in Python suck badly and they are not usable. Moreover, pep8 is not as important as consistency with existing codebase and team rules.

  • @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 UA-cam algorithm pointed me here.

  • @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.

  • @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.

  • @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

  • @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

  • @mario_luis_dev
    @mario_luis_dev 3 роки тому +85

    this was very informative. Coming from a C++ background I see that my Python skills are very un-Pythonic 😅 Need to get used to these pep-8 standards more

    • @slavkokaradzic86
      @slavkokaradzic86 3 роки тому

      Agreed lol

    • @Victor_Marius
      @Victor_Marius 3 роки тому +5

      If you don't follow pep8 it won't make you less professional. There are a lot of frameworks and libraries written in camel case for example.

    • @Victor_Marius
      @Victor_Marius 3 роки тому +4

      You do want your workplace wants you to and what you want

    • @georgeousthegorgeous
      @georgeousthegorgeous 3 роки тому +9

      nobody ever cares about these standards. code just needs to be clean, understandable and do it's work

    • @SuperNovaJinckUFO
      @SuperNovaJinckUFO 3 роки тому +1

      In my opinion, you should take pride in that XD (C++ all the way!)

  • @nukularpictures
    @nukularpictures 2 роки тому +1

    I hate snake_case. It's not more readable its just a mess, especially if you have long names. I don't care what some guidelines are, I use snakeCase. No one ever said anything about it and honestly it does not make the code less professional. As long as you use a clear structure you are fine. Just don't switch it around and keep it consistent.

  • @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!

  • @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

  • @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.

  • @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!

  • @atrus3823
    @atrus3823 3 роки тому +1

    The bare except is worse than that. KeyboardInterrupt is an exception and let's you Ctrl + C out of a program. If your program gets stuck in an infinite loop inside a try block with a bare except, you can't exit!

  • @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.

  • @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.

  • @0xCAFEF00D
    @0xCAFEF00D 3 роки тому +3

    For the replacement of C with K I would prefer 'K'+myName[1:] rather than replace in this example. The intent was to replace the first character, not every C with a K. They just happen to coincide. They should know both replace and string slicing of course.
    Specifically for a video like this the people who don't know about string mutability are probably served better knowing how to do what the code tried to without error.

    • @vekyll
      @vekyll 3 роки тому

      I disagree. The usual phrase in natural language is "Karolina with a 'K'", and while it is completely implicit _what_ to replace, I'd strongly argue it is "Carolina with a C written K", not "Carolina with first character written K". "Bianca with a K" is "Bianka", not "Kianca", right? :-D

    • @0xCAFEF00D
      @0xCAFEF00D 3 роки тому

      @@vekyll You've missed my point. I'm not saying replace isn't a good feature. But it's for actually replacing a set of things with another thing. Like .replace(' ',''). If a name has multiple of a character you'd like to replace. But if you just want to replace one of those you'll have to include some of the surrounding characters in both the old and new substr in the replace.
      That's why I think showing the slicing method is important. If we could just show one method we'd show that one because string slicing couldn't deal with every case. The rookie would find replace eventually. While they might end up doing crazy replace tricks if that's all they know.

    • @karolinasowinska
      @karolinasowinska  3 роки тому +1

      Perhaps you're right, I didn't think about it. Hopefully it doesn't confuse anyone though!

    • @vekyll
      @vekyll 3 роки тому

      @@0xCAFEF00D Yes, I probably missed your point, since to me, Python is executable pseudocode. When you want to put K in Karolina, you put it _instead of a fixed letter_, not _in a fixed position_. Do you agree on that?
      Your second argument is nonsense, at least according to my experience (which includes teaching hundreds of people about Python). Beginners are incredibly diverse, and yes, there are a good number of them that do everything with indexing instead of using more appropriate methods.

    • @vekyll
      @vekyll 3 роки тому

      @@karolinasowinska He isn't right, he just needs some time to understand it. :-)

  • @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.

  • @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! :)

  • @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.

  • @jonathan-._.-
    @jonathan-._.- 3 роки тому +36

    i was quite afraid for a moment youd found the python code i wrote so far :D

    • @karolinasowinska
      @karolinasowinska  3 роки тому +3

      Haha nah, I found my code from one year ago :D

    • @jonathan-._.-
      @jonathan-._.- 3 роки тому +4

      @@karolinasowinska moral of the story : dont look at old code , might leave permanent scars :3

    • @karolinasowinska
      @karolinasowinska  3 роки тому +2

      @@jonathan-._.- haha sweet oblivion is rarely a bad strategy! ;)

    • @jonathan-._.-
      @jonathan-._.- 3 роки тому +1

      @@karolinasowinska yeah elder scrolls oblivion - really good game :3

    • @lifestoriesfromearth6271
      @lifestoriesfromearth6271 3 роки тому

      do u have a recommendation book for this change

  • @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))

  • @drtheoretisch
    @drtheoretisch 3 роки тому +7

    I would have also changed the print params to print(f"My name is {x} I'm {y} years old, and these are my goods:") which makes it much more readable by applying string interpolation :)

    • @karolinasowinska
      @karolinasowinska  3 роки тому +1

      Good point! ;) Thanks!

    • @martinmckee5333
      @martinmckee5333 3 роки тому

      I love the string interpolation syntax, but I still generally use format() to support older Python versions.

  • @kevinmcaleer28
    @kevinmcaleer28 2 роки тому +1

    Great video - Thanks Karolina!

  • @sealkeen
    @sealkeen 3 роки тому +18

    6:48 1) Can you assign a value to the variable in the loop while iterating through some collection in a Pytonic Way?
    2) Can you also write a server-side component that deals with database migrations, handling web requests and implements a server API in Python and run the server using only Python?

    • @karolinasowinska
      @karolinasowinska  3 роки тому +21

      Yes you can!
      >>> for count, value in enumerate(values):
      ... print(count, value)

    • @mattacarregui3934
      @mattacarregui3934 2 роки тому

      @@karolinasowinska is the (values) next to enumerate just representing what is in enumerate or is that part of the syntax?

    • @intelchip_x86
      @intelchip_x86 2 роки тому

      @@mattacarregui3934 values is the name of a list, its just used as an example in the comment

    • @rafagd
      @rafagd 2 роки тому

      1) Kinda. You'd need to run a for i in range(len(array)): array[i] = something, or build a new array. Unless you mean a variable that is not the array, which is trivial you just do it.
      2) You mean, write Django?

    • @rafagd
      @rafagd 2 роки тому

      @@mattacarregui3934 enumerate is a function that returns an iterator to your array (named values in the example).
      Each iteration of the loop makes enumerate spit out a pair (index, values[index]).

  • @XxxGuitarMadnessxxX
    @XxxGuitarMadnessxxX 2 роки тому +1

    This is a much older video of yours at this point, but I first wanted to thank you for this video (new subscriber here lol) - and with that, I was hoping to find a way to learn python syntax in a more fluid way; i.e. I'm a hobby programmer that has *ONLY* messed with a little bit of C and a whole lot of C++ the past couple years and I just can't bring myself to like Python simply due to it's indentation and similar syntax "features". Is this something you just tend to get used to or is something that you tolerate in order to write python code?
    Thank you in advance for any replies!

    • @XxxGuitarMadnessxxX
      @XxxGuitarMadnessxxX 2 роки тому +1

      I do realize this is more a subjective question though lol despite how easy tasks might be using python, I just can't seem to force my way through having to keep in the forefront specific indentation rules as I write 😅

    • @karolinasowinska
      @karolinasowinska  2 роки тому +1

      @@XxxGuitarMadnessxxX Hi Ryan! You definitely get used to it. At first Python felt really strange to me (I also had experience with C++/Java before). :)

  • @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

  • @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 =)

  • @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 :)

  • @NerdX151
    @NerdX151 2 роки тому +1

    I think that "pass" can be useful in some situations. Example: I recently had a customer who wanted a simple program that could fetch pdf links from their database and download them. They wanted the output to be as simple as possible. If some of the files had invalid urls they just wanted the program to print out "Filename... Could not download". I DID make a print statement for the exception, but I commented it out and threw in a pass. That way the non-tech savvy could run the program without freaking out about a lot of error messages while downloading, and IF they wanted their programmer to debug the code, all he needed to do was to comment out the "pass" and un-comment the print statement. Voila, everyone was happy.

    • @pepperdayjackpac4521
      @pepperdayjackpac4521 2 роки тому

      now that's how u do it. Balance!

    • @victortitov1740
      @victortitov1740 2 роки тому

      to be honest, the catch-all-do-nothing is the worst for users, not developers. Developers can step through the code in debugger to see what goes wrong. The user has no clue.
      That is especially a problem when exploring a new software. I press a button, nothing happens. Is it working? Maybe it did something, i just don't know where to look? Maybe it's still doing something? Should i press it again? if it failed, what can possibly be the cause? is it a wrong input? if so, which one of the 15 i just did? or is it internet connection? or an installation issue? I really hated FreeCAD when learning it for this reason.

  • @jakman85
    @jakman85 2 роки тому +3

    C# programmer here. The loop you showed that was "unpythonic" is also not good practice in C#. You would use either LINQ ForEach to use lambda expressions or use a foreach block with similar syntax to your python code.

  • @rolf.m.h.5560
    @rolf.m.h.5560 2 роки тому +1

    "-it looks unprofessional
    -it makes your code hard to read
    -your colleagues are secretly going to hate you"
    Who cares. The expression "Python" comes from "Monty Python". You should play with it and enjoy it, and not try hard to seem very professional or "pythonic". One makes a lot of mistakes and learns from them. If you are not interested in where you make mistakes but want the whole program running happily, use try-except-pass freely and often. It is not awful, but by using abundant comments everywhere in your code, which show up somewhere in logs or in places that do not stop a running program, you can do a lot about the occurring errors, but maybe you don't want to see and show the others where there are errors. Therefore, you just pass over them as you do over the pimples and bruises on your body which do the job of healing automatically, of which you don't want to be much aware. The end result should not be a perfect program that crashes when there is the slightest error somewhere in the middle, but a body of code that runs happily even if it takes a lot of corruption, module-files go missing, or are cannot be imported somewhere any longer.

  • @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!

  • @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

  • @NyscanRohid
    @NyscanRohid 3 роки тому +3

    "What are you doing in `except`?"
    `pass`: "Mind your own business!"

  • @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.

  • @playerscience
    @playerscience 3 роки тому +5

    I didn't even know that it *Is Possible* to define a variable type in python.
    Thanks 😊

    • @べ断桥烟雨ミ-d8g
      @べ断桥烟雨ミ-d8g 3 роки тому

      Type Hints was introduced in Python 3.5, for basic data types, you can add them directly after parameters or vairables. But for lists, tuples, iterators, dictionaries and other complex data types, you should import them from "types" package. Also for previous versions of Python, you can define Type Stubs files for telling intepreter what those variables or functions actually are.

    • @Justsomeinternetguy9
      @Justsomeinternetguy9 3 роки тому +2

      its important to note that this is called type hints, and as the name suggests, it just hints at the type. This is in no way used or acted upon in the program. If you define it as a string but then assign it a number, it wont stop you, or care, or even notice. These are there strictly for you to document your code. (and some unittesting and linting tools may check them to make QA testing easier)

  • @DEtchells
    @DEtchells 2 роки тому +1

    Just now starting to learn Python, YT put this in my recommended list. Super useful, I’m gonna try hard to make my code fully Pythonic! :-)

  • @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.

  • @christiencodes3086
    @christiencodes3086 2 роки тому +1

    The try except bit speaks to my soul

  • @emanuelblei7699
    @emanuelblei7699 3 роки тому +4

    I found that topic and presentation of the video quite nice. However, I you would have shown the code for a bit longer. It's really hard to read otherwise.

    • @karolinasowinska
      @karolinasowinska  3 роки тому

      Ah, sorry, I just assumed people can pause when they need to see more detail, but you're right!

    • @emanuelblei7699
      @emanuelblei7699 3 роки тому +1

      @@karolinasowinska Yes, that is true. That might work best for the last part where you show the 'before' and 'after'. Maybe less so for the other parts where you show how you adjust the code. But, it is still a good video. Don't get me wrong on this.

    • @karolinasowinska
      @karolinasowinska  3 роки тому

      @@emanuelblei7699 I'm glad you liked it! Thanks for sharing your thoughts as well, I appreciate it :)

  • @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.

  • @nikogonz1
    @nikogonz1 3 роки тому +6

    hey great video! you should do more of this! I love watching videos about what I should not be doing in python as I'm still learning.

  • @davidg5898
    @davidg5898 2 роки тому +2

    Good to know. In my physics undergrad days we started on C languages and then were taught Python, and we just used all of the C conventions. I'm going to try and get used to Python style when working in it.

  • @AthanasiouApostolos
    @AthanasiouApostolos 3 роки тому +5

    As an ex java developer and soon to be data engineer I find your tutorials very useful. Thanks for uploading :)
    I assume ->None is the return annotation but does it give an error if we return a different data type like int or string?
    "run_this_baby" lol I will use it in production the next time.

    • @karolinasowinska
      @karolinasowinska  3 роки тому +3

      I think it might let the undesired data type go silently. So it's more of a readability feature rather than a safety measure.
      Haha run_this_baby is a perfect name substitution for 'main' 😂

    • @paulvorderegger1522
      @paulvorderegger1522 3 роки тому

      IDK if this helps but if you're an ex java developer "None" is the equivalent of "null" in Java.
      Python usually doesn't give you errors if you return "the wrong type", because really, you can't return the wrong type. You can set a variable to a string and later assign an integer to it and everything is good.

    • @marcodoe4690
      @marcodoe4690 2 роки тому

      wait until you see how interfaces are written in python. it's my personal favourite meme.

  • @MYCHEM1CALR0M4NCE
    @MYCHEM1CALR0M4NCE 2 роки тому +1

    I recently found the whole except: pass thing to be quite useful to be honest. Obviously its awful code, but I had a loop that iterated though about 10,000 windows of data, and it did a fair bit of arithmetic, and sometimes zeros would be spat out that lead to infinities and undefined things etc., and whenever these zeros occurred, I knew there was in fact no solution for that particular window of data (which was fine), and so instead of using a bunch of clauses to catch everything, the try except: pass worked wonders

  • @yuanyuan23191212
    @yuanyuan23191212 3 роки тому +3

    Mistake #5: unpythoic looping -----> sometimes we need to use the index of the element. For example, compare current element with next element, then decide if break the loop. Wouldn't it be necessary to use the index here?

    • @karolinasowinska
      @karolinasowinska  3 роки тому +3

      The pythonic thing is to use the enumerate function for that :)

  • @felixszopos-papp1478
    @felixszopos-papp1478 2 роки тому

    Regarding that first mistake.. The pass instruction exists to be a temporary placeholder while implementing code. It would only be a mistake to use it there, if you actually left that except block to be implemented down the line.

  • @marioloera6210
    @marioloera6210 3 роки тому +3

    cool video, perhaps you can use f-strings, a mix of use single-quoted strings and double-quoted strings: "Welcome to my program" 'Carolina'

    • @karolinasowinska
      @karolinasowinska  3 роки тому +2

      I'd always recommend sticking to either single or double! ;)

    • @dragoneater2008_
      @dragoneater2008_ 3 роки тому

      F strings aren’t like that. You can use
      Name=input(‘please enter your name: ‘)
      Print(‘welcome to my program {name}.’

  • @mcalister1911Ab
    @mcalister1911Ab 3 роки тому

    you have to use the function param name as run_this_baby (name = my name , age = my_age) -> this is more readable
    also that replace is possibly dangerous because it will change all the "C" inside the string.You have to add the my_name.replace("C" , "K" , count = 1) -> only will change the first C on the string
    the return in the run_this_baby function is redundant

  • @TWMist
    @TWMist 3 роки тому +3

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

  • @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.

  • @SealedKiller
    @SealedKiller 3 роки тому +3

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

  • @MerlinZuni
    @MerlinZuni 2 роки тому +1

    I‘m a noob. Just started working with pyGame today for fun. This was very informative. I did not know about the snake case. Cheers, for that

  • @medoubella
    @medoubella 3 роки тому +5

    Hello there,
    what if when for-looping, u need to access the index of the current element, is there any 'pythonic' way of doing that other than using the unpythonic i in range(len(list)) ?

    • @karolinasowinska
      @karolinasowinska  3 роки тому +8

      Great question, you should use "enumerate" function:)

    • @tonyy6026
      @tonyy6026 3 роки тому

      .find() works as well

    • @isidrodeleon673
      @isidrodeleon673 3 роки тому +1

      for i, element in enumerate(list):
      print("Index: ", i, " Value: ", elem)

  • @camadams9149
    @camadams9149 2 роки тому +2

    Great video! Just started learning Python today after spending the last few years mastering C & JavaScript
    Already excited that there is a language wide style standard

  • @iamchesco
    @iamchesco 3 роки тому +3

    Awesome!!! informative and fun. Keep up the great content!

  • @giovannicriscwcc4249
    @giovannicriscwcc4249 8 місяців тому +1

    very useful and well explained ! thanks Karolina !

    • @karolinasowinska
      @karolinasowinska  7 місяців тому

      Glad it was helpful!

    • @giovannicriscwcc4249
      @giovannicriscwcc4249 7 місяців тому

      @@karolinasowinska exception handling lead to the deepest fantasies 😂 I must admit I am a python "pass" keyword fan, and then I "pass" hours crying on debug

  • @eliasjohanliavaag
    @eliasjohanliavaag 3 роки тому +7

    Had to check whether it was my fire alarm beeping while watching this. Hope you replaced its batteries! :D

  • @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.

  • @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.

  • @ForgottenComputer
    @ForgottenComputer 2 роки тому +1

    Very cool! I love this and it is an immediate subscribe... One note: agreed try-except in your example is terrible, and except-pass is even more, but new coders should not be discouraged in general from using try-except; this extremely useful Python construct helps big time when dealing with uncertainties regarding behavior of external APIs, network connections, dirty data, etc.

  • @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.

  • @baphnie
    @baphnie 3 роки тому +2

    It never ceases to amaze me how programmers are lauded for creative problem-solving and innovative thinking, yet still conform to such religious rigidity as 'standards' and 'best practices' that have no real effect.

    • @karolinasowinska
      @karolinasowinska  3 роки тому +5

      I used to think the same. But then I started working with other people in a team and I understood the importance of standards! Your code does not only have to solve a problem, but it also has to be readable for others who will develop on it after you.

  • @aniketpurohit8613
    @aniketpurohit8613 3 роки тому +4

    f-strings can be a useful addition! :)

  • @Nedwin
    @Nedwin 3 роки тому +1

    Very nice sharing Karolina!

  • @pyroghost11
    @pyroghost11 3 роки тому +3

    Wow, you seem to be a great teacher based on how enthusiastically talk about this topic! Awesome

  • @Unaestheticc_
    @Unaestheticc_ 2 роки тому

    you didn't talk about the fact that writting print(f"My name is {x} I'm {y} years old etc") is a way better than print("My name is ",x,0 " I'm", y, " years old etc")

  • @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.

  • @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++.

  • @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).

  • @Mrcjhepburn
    @Mrcjhepburn 3 роки тому

    I'm new to Python... Why assign a data type in Python? The data types don't stick. If you have... x: int then assign it a value of 5.4, now it's a float.
    x: int
    x= 5.4
    print(type(x))
    output:

  • @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!

  • @majkus
    @majkus 2 роки тому

    Back in the old days, vanilla C programmers often used a program called 'lint' to catch things like type mismatches. It was sometimes worthwhile to go through the exercise of making code 100% lint-free. For example, common functions like printf have return values (the number of characters printed, or an error), but normal practice is to simply write 'printf' as if it were an imperative statement - this would be flagged by lint, because the return value was ignored. To fix this, one would write (void)printf... Now, this is still just ignoring the value; but by going through the exercise of adding '(void)', the programmer was forced to _think_ about printf's return value, at least briefly, and whether it would be helpful to check this value, and so on.

  • @rodrigoamoedo8523
    @rodrigoamoedo8523 3 роки тому +4

    wellcome to my life...
    even worst, my friends nested nested nested loops, are a pain in my back

  • @deidara_8598
    @deidara_8598 2 роки тому +1

    You missed a few things: the first print statement in run_this_baby could be turned into a format string. Format strings are much more readable than splitting the string into chunks and concatinating them, and should be preferred in most cases.
    print(f"My name is {x} I'm {y} years old, and these are my goods:")
    is much more readable than
    print("My name is", x, "I'm", y, "years old, and these are my goods:")
    Also you should put everything in the __name__=='__main__' inside a seperate main function and call the main function instead. Avoid global vars like the plague.

  • @rhalfik
    @rhalfik 3 роки тому +3

    Jesteś bardzo dobrym nauczycielem.

  • @walle1976
    @walle1976 3 роки тому +1

    Three more improvements: move main code into a def main() method, remove empty return and use fstring or .format in the print statement of run_this_baby method.

  • @theresatonev2504
    @theresatonev2504 3 роки тому +3

    Thanks for the tips!
    P.S. I think you need to change the batteries in your smoke detector. XD

    • @karolinasowinska
      @karolinasowinska  3 роки тому

      Hahah you're right, everyone keeps telling me this, and I am the only one who cannot hear that beeping anymore:D

    • @neiliusflavius
      @neiliusflavius 3 роки тому

      @@karolinasowinska ah, good to know it's not mine beeping!

  • @mivelak1
    @mivelak1 2 роки тому

    I know that using global variables is bad. In this case MY_AGE can be considered a constant value.
    It means that it's value should not vary through program. PEP8 says as follows:
    'Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.'.
    It leads to my question:
    Why shouldn't we define constats on a function level?

  • @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.

  • @minhly650
    @minhly650 2 роки тому

    2:14, for this specific example that you show here, it does not make sense when passing errors if it occurs. However, there will be some cases that they do not want errors to block other code below, but they also do not care about the errors since they are not critical.

  • @hassainehassen5700
    @hassainehassen5700 3 роки тому +3

    Thank you , you have directed me to pep8 style

  • @legojenn
    @legojenn 2 роки тому

    I'm learning Python and I'm liking it, but it's hard. You touched a nerve with global variables. Coming from C/C++ and Java, I was not comfortable thinking that all variables were global.

  • @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

  • @mgav006
    @mgav006 3 роки тому +2

    Just starting out with building my first few scripts using Python so thanks for the tip on the style guide. Wil incorporate it into my code :)