r/learnpython • • Sep 01 '22

I hate using functions can someone shame me into using it

please i need to be shamed and punished into using it. or maybe convince me into using it, because I like writing long codes

48 Upvotes

151 comments sorted by

410

u/[deleted] Sep 01 '22

Writing long code is fine if you like unemployment.

6

u/[deleted] Sep 01 '22

what if the loop is inside a function

**taps head

1

u/solitarium Sep 02 '22

This is is the way

-56

u/Outrageous_Notice445 Sep 01 '22

lol then I'm not getting employed soon

56

u/[deleted] Sep 01 '22

Out of curiosity... why would you want to deliberately do something badly? Like, purposely set out to be bad at something?

12

u/longtermbrit Sep 01 '22

I ask myself the same thing whenever I see someone politely corrected on something really easy to fix yet they refuse to do it.

-58

u/Outrageous_Notice445 Sep 01 '22

IDK. Is way too complicated sometimes

26

u/Dysfu Sep 01 '22

My guy, they’re really not that complicated. The only person stopping you froM learning is yourself. If you can figure out the syntax of the language to the point where you are solving problems you can stretch yourself to learn functions.

23

u/Outrageous_Notice445 Sep 01 '22

Okay I will try

31

u/[deleted] Sep 01 '22

Nobody ever got good at complicated things by avoiding them... just saying.

20

u/sotonohito Sep 01 '22

I'm... baffled.

It's MORE complicated to write a simple function than it is to spend your time typing and retyping the same code over and over and over each time you do it risking typos and getting stuff wrong?

You should write and use functions because it's easy and you're lazy.

I can't even imagine doing all the extra work involved in even copy/pasting the same code all over, not only that it makes the proram harder to read and understand.

Furthermore it helps you break up the probem into managable bites.

If you find out you need to change some functionality you can just change it once in the function rather than searching through your entire bloated mess of code to find all the times you retyped it (and inevitably missing some) and making your code buggier and harder to fix.

And you miss out on future proofing things. If I write, for example, a function to roll a die then later decide I need to include the possibility of more than just six sided dice, I can easily modify the function and bam done. Doing it your way I'd be spending endless boring hours digging through code and never getting it right.

What's easier to read/write:

while true drawBoard promptForPlayerMove drawBoard calculateComptuerMove drawBoard loop

or putting all the code for drawing the board in three different times, all separated by the huge mess of code (that hsoul be a whole host of functions anyway) for getting the player's move or calculating the computer's move?

You're making so damn much extra work for yourself, work that will fuck you up, add bugs, and make your code harder to fix and read.

34

u/ohyoubearfucker Sep 01 '22

Try to learn and enjoy complicated stuff. You'll need it!

5

u/thorsteiin Sep 01 '22

I dont know maybe the field is not for you then?

3

u/Hmolds Sep 01 '22

Then your functions do too much. Break down your code into smaller and simpler functions. One line functions are okay!

2

u/L0uisc Sep 01 '22

It's way simpler if you have good structure and small functions and classes for grouping repetitive pieces or logical units of code together.

2

u/solitarium Sep 02 '22

Would you enjoy having a teammate that deliberately made your job harder for the sake of avoiding complication?

As the old adage goes, do onto others

1

u/Moikle Sep 01 '22

You are making things far more complicated for yourself this way.

Functions massively simplify things

76

u/Gloomy-Strategy6805 Sep 01 '22

You have a degradation kink or something?

27

u/zsarolo Sep 01 '22

I think they do. “Shamed” AND “punished” ? That’s descriptive….

15

u/Bombslap Sep 01 '22

Oh yeah, copy and paste my code daddy

15

u/Pickinanameainteasy Sep 01 '22 edited Sep 03 '22
def shame(user):
    print(f'Shame on you {user}')

shame('Outrageous_Notice445')

5

u/Outrageous_Notice445 Sep 01 '22

I kinda get it now thanks

6

u/Pickinanameainteasy Sep 01 '22 edited Sep 02 '22

I was similar when I first started. I wondered why I needed functions. But then I wrote this script that basically did the same thing with multiple different variables. It was an awful mess and updating it was hell. It went something like this:

if name == 'Bob':
    print('Bob')
elif name == 'Alice':
    print('Alice')
elif name == 'Eric':
    print('Eric')
elif name == 'Carry':
    print('Carry')
else:
    print('Bill')

Except there were many different names (~20) and instead of just being return statements it was like 15 lines of code. In order to make an update I had to go to each if statement and make the same change, in other words I had to make ~20 changes and hope I didn't mess anything up.

Later I realized functions make this much easier, let's say I have return.py with the following function:

def return_names(name):
    print(name)

This way I can just make 1 change if I need to update. Not only that but you can import functions into other code. So if I have 5 functions that I will use in multiple programs, instead of the writing the same function logic at the beginning of my code i can just import the function in and make it much more readable.

Now let's say I create role_call.py and need to return names I don't have to do this:

name = 'Bob'

if name == 'Bob':
    print('Bob')
elif name == 'Alice':
    print('Alice')
elif name == 'Eric':
    print('Eric')
elif name == 'Carry':
    print('Carry')
else:
    print('Bill')

I can just do:

from return import return_names

return_names('Bob')

You're code will be more modular and less cluttered

1

u/[deleted] Sep 02 '22

[removed] — view removed comment

1

u/Pickinanameainteasy Sep 03 '22

Oh lol. Fixed it

45

u/shiftybyte Sep 01 '22

No problem, you are from now on forbidden from using functions.

want to get user input? can't.... because input() is a function...

want to print to screen? can't... because print() is also a function...

16

u/ohyoubearfucker Sep 01 '22

Good point, but I think OP is referring to def someFunction() type stuff, i.e. writing classes and functions

21

u/shiftybyte Sep 01 '22

OP can now understand why it's important to learn to write functions, so they can be used easily...

2

u/ohyoubearfucker Sep 02 '22

I get that, and yr right -- it's vital. But I also remember the stage in which I used functions without really understanding what they meant and how they worked. Having to write yr own is intimidating at first, now I cannot imagine not writing my own.

2

u/my_password_is______ Sep 01 '22

obviously that's not what the OP meant

-17

u/Outrageous_Notice445 Sep 01 '22

mate that's impossible i'm only talking about def

17

u/shiftybyte Sep 01 '22

This was to illustrate why functions are important.

In general some things you can't do without a function that someone def'd for you to use.

Also some tasks become a lot less repetitive if you make a function that simplifies it.

23

u/TholosTB Sep 01 '22

In high school, during the dark ages, I had a "Computer Lab" elective. I was the first and only person to take it. So the guy who ran the lab gave me a UCSD Pascal book and told me to implement matrix addition for two sets of matrices.

I found the example in the book and could not for the life of me figure out why their example only had the code once. So I wrote all the code out twice, once for each pair of matrices.

Don't be me. Use functions.

10

u/Brave-Rain-9085 Sep 01 '22

I just wrote a program without a single function and someone in my office looked it over, panicked, and told me I write code like a psychopath lol

3

u/Extension_Job5829 Sep 01 '22

what sort of fetish is this

0

u/Outrageous_Notice445 Sep 01 '22

Is a strange one right

1

u/Extension_Job5829 Sep 01 '22

not necessarily there are stranger fetishes out there

4

u/AstrophysicsAndPy Sep 01 '22

complex nested list comprehensions, my fav

2

u/Extension_Job5829 Sep 01 '22

I absolutely adore list comprehensions

3

u/InjAnnuity_1 Sep 01 '22

I'd bet that you're using functions (e.g., like print) just fine. But creating your own might seem a little daunting.

I suggest starting small. Very small. Often, the best function is one that does one simple thing, and does it well.

Just try it in some silly little throwaway program, just to get the hang of it.

-2

u/Outrageous_Notice445 Sep 01 '22

Yh creating my own functions feels like a hassle

4

u/InjAnnuity_1 Sep 01 '22

If you're creating functions for no payoff, sure, what's the point? But you'll find occasions where there's a big payoff. Then the hassle will come from not creating and using them.

1

u/Grunthos_Flatulent Apr 13 '26

True dat.

I've just finished a small project where functions would serve no useful purpose and would more than double the size of the script and nearly double the size of its compiled bytecode (I know because I tried it both ways).

That's no reason to not learn how to code functions though. There are plenty of situations where they're pretty much indispensable and can reduce complexity and greatly improve readability.

1

u/InjAnnuity_1 Apr 13 '26

The other big improvement is reliability. Many functions can be tested thoroughly, once, in isolation. Once proven, that's one less place for bugs to hide.

Much more reliable than writing out [nearly] the same code in a dozen places, and then having to fix every single one of them when a bug becomes evident.

2

u/[deleted] Sep 01 '22

Not using functions as a sure sign of an amateur. The reason why people avoid functions is because they don't know what to do with them. They don't know how to pass their variables around effectively

3

u/Outrageous_Notice445 Sep 01 '22

yh I'm an amateur, I don't know when and where to use them

1

u/AstrophysicsAndPy Sep 01 '22

Usually the purpose of function is to reuse the code snippet. For example, let's say you need to draw multiple figures that have same x and y labels but with different titles every time. Now you can accomplish this in 4 lines max. Not an issue, now let's say you have 100 of these figure to plot so instead now you'll have to write an additional 400 lines. However, if you'll definite a function, you just need to write 105 lines of code instead of 400 for doing this.

1

u/[deleted] Sep 01 '22

Send me your code. Ill tell you where and why you should be using functions. Most likely, you right your code first and then ask where you should be using functions. You should be writing your code the way you communicate. Communicate abstractly, then define what you mean.

1

u/[deleted] Sep 01 '22

Any time you are performing an atomic function (i.e. one that can’t be split up and solved as smaller sub-problems), you should use a function.

I.e. pretend you were writing a program that accepted user input, validated it, then performed some logic on it. You would create a function to accept the input a function to validate the data entered, and a function to perform the logic, and then call them one after another.

This makes it easier to conceptualize, easier to write, and easier to revise later.

If you did this all in one monolithic script it would be a jumbled mess with no clear separation of logic.

150

u/agnaaiu Sep 01 '22

This is like saying "I want to become a cook but I hate using knives".

12

u/StoicallyGay Sep 01 '22

A better analogy would be like:

I like writing books and taking notes but I hate using nested bullet points, chapter markings, titles and subtitles, headings, and literally form of organization.

Because even if you only call a function once, modularizing the code so your main function only calls like 5 properly named functions in sequence makes it more readable.

40

u/[deleted] Sep 01 '22

[removed] — view removed comment

11

u/Got_Faith Sep 01 '22

Yh so basically "I want to be a cook but I don't like using a Kitchen".

Sure you can cook on a fireplace but for employment, probs need to work with others in a kitchen.

34

u/kid_ghibli Sep 01 '22

Open your project that you worked 2-3 months ago, the longer back the better. Now try to improve it in some way, just mild design/UX thing or maybe a better algo. I'm 90% sure you'll refactor it and use functions.

32

u/Firake Sep 01 '22

Ok I guess have fun rewriting blocks of code you need to reuse a bunch of times and. Oh? What’s that? Your objectives changed and you’ve gotta change that process? Well, have fun changing the process at every step of the way individually. I hope you do it all the same way or you’re gonna have major bugs.

32

u/Linked1nPark Sep 01 '22

This is like being an author and writing out every copy of your novel by hand instead of just writing it once and letting a printer do the rest.

15

u/[deleted] Sep 01 '22

OP would make a great 1600s monk.

78

u/Different_Suspect_30 Sep 01 '22 edited Sep 01 '22

Use Tkinter to make a Gui which should include buttons, checkboxes, radio buttons etc...

without using any function or method

Let’s see how you do it

Good Luck!

17

u/ColdOutEh Sep 01 '22

Don't provoke OP

18

u/RaidZ3ro Sep 01 '22

DRY: Don't Repeat Yourself.

7

u/LagerHead Sep 01 '22

DRY: Don't Repeat Yourself.

5

u/xCelestial Sep 01 '22

KISS: Keep It Simple, Stupid

1

u/RaidZ3ro Sep 03 '22

Fair point. DRO: Don't Repeat Others

3

u/giorgosprrr Sep 01 '22

Wrong Reddit sub dude

1

u/Outrageous_Notice445 Sep 01 '22

why lol

16

u/czar_el Sep 01 '22

Because r/imafuckingidiot is over there.

J/k, not trying to really be mean, you invited shaming.

But for real, functions make your code less prone to errors. If you hard code each time you repeat a process, each additional time you type is a chance for typos or omissions. And if it happens, you have hundreds of lines to review to find it, rather than one function section.

If you code in an environment where others have to work with your code and/or review your code, they will hate you. Every additional line to review is more effort and time, which is a waste for them and the organization.

It's also a signal that you are either 1) uneducated/unskilled, or 2) stuck in your ways and unwilling to modify for a better approach. Neither is a good signal to send.

6

u/[deleted] Sep 01 '22 edited Sep 02 '22

Functions are one of the most powerful tools at your disposal. If you don't use functions then in the game you might be writing where you need to get a positive integer from the player you must write four, five, or more lines of code to get the number and handle user errors and retries. Every time you need a positive integer from the player you write the same 4, 5 or more lines of code. If you then decide to accept only positive even integers you have to track down and change every place where you write those 4 or 5+ lines.

If you use a function you write that code once. Plus you don't clutter up your high-level code with low-level stuff that isn't really part of the high-level logic. You hide all that low-level fussing inside the function. It's as if you extended python, adding a function to get a positive integer. And if you need to change what you accept you only change in one place, the function.

With a little practice you actually write code differently. You get to the point when you need to ask the player for a positive integer. You say "I'll have a function do that" and write something like:

num_coins = get_pos_int("How many coins?")

and you write the function sometime later instead of getting bogged down in minor relatively unimportant detail. When you write the function you note that it takes a prompt like input() and always returns a positive integer, and it's simple to concentrate on that and nothing else.

Functions are one of the most important programming ideas of the last 70+ years. You need to get good at using them.

I like writing long codes

It's nice to be able to churn out lots of code, but you can write bigger, more useful code if you can use functions well. It's well known that human brains have limited capacity and can only keep so much code "in your head" while writing, so using functions to avoid repeating code means you can do more useful things in code before hitting your limit. Try to get your kicks from getting the job done with readable, non-repetitive, concise code.

6

u/[deleted] Sep 01 '22

Use functions you slut!

5

u/AK1174 Sep 01 '22

yeah I too love refactoring thousands of lines of repeated code because I’m too mentally disabled to use the function keyword.

2

u/[deleted] Sep 01 '22

Haha

1

u/shartfuggins Sep 01 '22

Why do you hate using functions? Serious question, giving you the benefit of the doubt that you're not trolling.

Also, the way you phrase it.. "using it" makes me think you see functions as sort of a separate tool or optional add-on, not an integral part of coding.

1

u/Outrageous_Notice445 Sep 01 '22

I have tried to learn how to use it but everytime I get confused it get so complex. Fyi I only don't understand how and where to use the def function

1

u/shartfuggins Sep 01 '22

Ok, let's forget about shaming, though that's funny and all.

This sounds like a misunderstanding or at least being unfamiliar with the syntax. I suggest reading python code written by other coders. Find some smaller projects on GitHub and just read them through. Try to follow one program line by line and see how it uses functions.

I think of functions like assistants or helpers. A function is good at one thing, and when you need that thing to happen, you ask it.

Likewise, when you write a function, you're creating or training a new helper on how to do one particular thing. If you're not doing anything complex enough to justify bringing in helpers, or no task needs doing more than two or three times, then don't use them.

1

u/memeticmagician Sep 01 '22 edited 25d ago

The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.

Pocket gray retire grasshopper treatment waffle

1

u/Outrageous_Notice445 Sep 01 '22

No I do use loops ,but I don't use the def function

1

u/memeticmagician Sep 01 '22 edited 25d ago

The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.

Cobblestone repeat scary nail placid cinnamon consist sophisticated different

1

u/kaiju505 Sep 01 '22

If verbosity is your kink, maybe switch to Java

1

u/Outrageous_Notice445 Sep 01 '22

I heard is confusing

3

u/MarsupialMole Sep 01 '22

Defining functions gives you new toys to write long codes with.

3

u/Room07 Sep 01 '22

So all of your variables are global? You are using variables right? 😉

3

u/HomeGrownCoder Sep 01 '22

Statements like this will eventually sort themselves out. Best of luck to you

3

u/BananaGooper Sep 01 '22

I pray you never contribute to any open source software

3

u/rotterdamn8 Sep 01 '22

You might find a better answer in r/Masochism

2

u/Interplanes Sep 01 '22

Functions eventually make things easier

2

u/TGEL0 Sep 01 '22

If you give your function a nice descriptive name you instantly save time on writing unnecessary comments.

2

u/Technical_Flamingo54 Sep 01 '22

It scales like a train wreck, have fun trying to expand your projects

2

u/NetFutility Sep 01 '22

Can't even use + or = cause there's a function being called in the background. Maybe you should use C.

2

u/HomeGrownCoder Sep 01 '22

Statements like this will eventually sort themselves out. Best of luck to you

2

u/RDX_G Sep 01 '22

You sound exactly like me in the past , always shy away from writting the function...until i started learning recursion.

2

u/Fred776 Sep 01 '22

Not really answering the question here, but why do so many people talk about "codes" these days instead of "code"?

The only time I had heard it before recent times as a plural is in the context of scientific Fortran, where there is a history of referring to a program as a "code" (e.g. "a fluid mechanics code"). Note this is still singular, but "codes" would be used to refer to multiple such programs.

But otherwise, if you are referring to the stuff that forms the whole or part of your program, it's just "code".

2

u/[deleted] Sep 01 '22

In 1985, when i was working in game development at Elite Systems Ltd, we had a new starter who was, apparently, an experienced Z80 assembly language programmer. He was given a project for the Sinclair ZX Spectrum and made a start on it. Not too long into the project he ran out of memory and asked for help.

We looked at his code and it became blindingly obvious why he'd run out of memory. No sub-routines. None. Not a single one. His code started at the execution point and just continued. Game programming in those days was difficult enough, what with the limited memory available, without writing such poor code.

He lost his job and the project was re-assigned.

2

u/Dragon20C Sep 01 '22

Lol how are you even coding anything complicated?

2

u/[deleted] Sep 01 '22

You use functions; you just don’t understand that you’re using functions.

2

u/[deleted] Sep 01 '22

My first big apps had like 150 line functions. Had a good programmer explain to me why that was a problem. Troubleshooting is a nightmare. If it’s more than 10 lines, you need to start thinking about how to split it up.

2

u/Biffgasm Sep 01 '22

What is your dysfunction?

2

u/Socketlint Sep 01 '22

I have the opposite problem

2

u/cybervegan Sep 01 '22

I believe Amavisd might be looking for new developers - you'll love it, it's about 10,000 lines of hairy Perl code with loops, logic and data intertwined, functions with 1,000's of lines of code and parentheses nested so deep that your editor's syntax highlighter will crash.

2

u/tachoknight Sep 02 '22

Nah, you’re good. If your code is a sequence of related operations, functions aren’t necessary. A function is a logical tool for grouping a bunch of operations together that produce a result by itself; functions are a way to group a bunch of related operations together that you may want to use again and again (like in a loop) or do a bunch or work that is necessary, but unrelated to what you want to do ( e.g. get data from a database so you can then “process” it).

Functions are there to help you make more logical sense of what you’re trying to accomplish; you can accomplish something similar with a lot of comments around your code, but the moment you’re thinking, oh, I want to do this sequence of commands again, or, geez, this feels like a weird, but necessary tangent to what I’m trying to accomplish, then use functions.

2

u/apianbellYT C++ Master Sep 02 '22

Long code is fine if you want your computer to burst into flames.

2

u/[deleted] Sep 02 '22

I guess you really have leaned into the term "scripting language".

2

u/w_savage Sep 02 '22

I was the same way, then functions clicked in my brain and can't imagine doing it without them now

2

u/antiproton Sep 02 '22

God, thinking is so hard, amirite? Why bother learning when you can spend your time playing mobile games on break at McDonalds?

1

u/TonightHot7414 Oct 31 '25 edited Nov 01 '25

Hi Brother !!!! You are not alone!!!! Full Support.
I'm beginner, deal with 100 max lines script type code for solo use, works perfectly.

1

u/[deleted] Sep 01 '22

Me too but functions give you more expressivity, I just barely know how to use them. Try a tkinter project, that will force you

1

u/mutual_coherence Sep 01 '22

I mean using functions is actually lazier than repeating the same lines of code. If you have to change it you don't need to remember where all the places you used that of code is. It saves you time AND it reduces your chances of making a mistake.

1

u/wayne0004 Sep 01 '22

There are two main reasons why to use functions:

  • DRY: Don't Repeat Yourself. The same way a while loop is used to repeat the code until the criteria is not met anymore, and the for loop is used to repeat the same code X times, a function is used to repeat the same lines several times throughout your code. Now, if you don't want to use functions, if you have repetitive code (you probably do), and you have to modify it, you'll need to manually go to each one of the instances and change them separately (because sometimes using the "find/replace" option in your IDE may change things you don't want to change). This is prone to error, you may skip one of the instances and now your code doesn't work, which may lead to you not wanting to work on old code because of fear of breaking things.

  • Modularization. If you write a function, you divide your code into two parts: the inside of the function, and the outside of it. Inside the function, you don't care about where the function will be called, you focus on making the function work; outside of it, you don't care how the function do the thing, you trust that it does and work from it. The fact that you certainly use print, input, len and other functions without knowing how they work means that you kinda understand the benefits of it.

1

u/jaypeejay Sep 01 '22

What are your goals with coding? Is it just to write tiny little scripts? Then maybe you can get by without functions since you’ll be the only one reading the code. Do you want a job, or to be a competent programmer? Then you’ll need to learn how to write to functions.

1

u/uglyasablasphemy loves scraping Sep 01 '22

Don't worry about it, at some point in your path is going to click for you and you'll shame yourself into using them.

1

u/B166er_ Sep 01 '22

You will use them eventually when you try to do something with more complexity. Same with classes once you get there.

1

u/ViralLola Sep 01 '22

Because repeating yourself is for chumps.

1

u/nufli Sep 02 '22

What?

2

u/ViralLola Sep 02 '22

See above.

1

u/nufli Sep 02 '22

Damn. Had to try

2

u/ViralLola Sep 02 '22

It was worth a shot.

1

u/[deleted] Sep 01 '22

If you actually want to be a programmer for your career then learn to do it properly. This “I don’t like this common feature of almost every language because it’s hard” type post makes me think you’re about 16 and just don’t want to put any effort in to learn.

If you’re just doing it for fun write whatever shitty code you want but you’ll quickly run into things that stop you making bigger and more interesting projects.

1

u/ButchyGra Sep 01 '22

You hate using functions because you have to think, learn and track variables and consider scoping. You’re being lazy, that’s fine if you’re messing around, not good if youre looking to make a career out of it

1

u/anh86 Sep 01 '22

Eventually you will write something that requires an absurd amount of repeating yourself if you don't use functions. You'll do it because you don't like functions. Then you'll want to change something and instead of updating the one function you will have to make the same change in 200 places. You'll do it and then have to debug to find all the spots you missed. After doing all that and finally getting your code working again you'll realize functions are pretty great.

1

u/PinAppleRedBull Sep 01 '22

I almost never use functions as well but no one pays me to write python and most of the scripts I use are just automation scripts that are 2-300 lines of code at max.

1

u/NameError-undefined Sep 01 '22

long code is ugly code. "5 lines of code is 4 too many"

1

u/ekchew Sep 01 '22 edited Sep 01 '22

Functions can be useful to help you deal with annoying situations where you have to keep fixing your code because you didn't think of everything. Once you have thought of everything, you can bottle up your logic and use it wherever you need it.

I'll give you an example based on when I was writing my first command line game. Say you're asking the user to enter a number from 1 to 4. You start with:

choice = int(input("Please enter your choice in the range 1 to 4: "))

This works until the user enters 10 just to mess with you. So now you have to add:

if not 1 <= choice <= 4:
     print("Your choice is out of range.")
     choice = int(input("Please enter your choice in the range 1 to 4: "))

Then they enter 10 twice. Shit. Guess we need a loop?

choice = int(input("Please enter your choice in the range 1 to 4: "))
while not 1 <= choice <= 4:
     print("Your choice is out of range.")
     choice = int(input("Please enter your choice in the range 1 to 4: "))

Then the enter "spam". That's not even a number and you get a ValueError exception. Ok, how about this:

goodChoice = False
while not goodChoice:
    value = input("Please enter your choice in the range 1 to 4: ")
    try:
        choice = int(value)
        goodChoice = 1 <= choice <= 4
        if not goodChoice:
            print("Your choice is out of range.")
    except ValueError:
        print("Your choice is not a number.")

This is getting pretty painful, but at least your logic is getting pretty airtight. Now someplace later on you need to ask for another number, this time in the range 1 to 10. Shit. How did you do all that before? But let's say you made the above a function?

def request_int(prompt: str, from: int, to: int) -> int:
    goodChoice = False
    while not goodChoice:
        value = input(f"{prompt} in the range {from} to {to}: ")
        try:
            choice = int(value)
            goodChoice = from <= choice <= to
            if not goodChoice:
                print("Your choice is out of range.")
        except ValueError:
            print("Your choice is not a number.")
    return choice

Now you can call:

choice1To4 = request_int("Please enter your choice", from=1, to=4)
choice1To10 = request_int("Please enter another choice", from=1, to=10)

Assuming request_int is well debugged, this should save you a lot of aggravation. And if there is still a bug in request_int somewhere (there may be? I haven't run this code), you only need to fix it in that one place.

1

u/[deleted] Sep 01 '22

You can go write bad code and maybe no one will notice for a while. But when someone notice (they will) they will ask why you do things that way, repeating code and shit, and if you say I don't like functions you'll be in a shitlist. When they have the chance they will replace you with someone that will use those functions.
The concept is hard to grasp when you're starting but once you get the hang of it you'll like it and you will phisically cringe when you look at your POS old code. I'm not just roasting you. I saw someone get fired because he was the one that applied the least of the code style conventions in the company. They waited for a bit and since they guy just refused to learn they just hired someone else. His code was unmantainable, hard to reutilize and most of us just ended up deleting what he did and writing it better (in functions). I won't humilliate you today. Your coworkers will humilliate the shit out of you so much that maybe you'll end enjoying S&M stuff, the Humilliation of getting your fresh new code re-written by your pairs should be enough.

1

u/OjjOj_10 Sep 01 '22

Don't force yourself to use functions ! Will come a day where you will find yourself searching for an optimal way to do something when you find that functions are the key

1

u/Ill-Criticism1062 Sep 01 '22

I got a long dick ,wanna date

1

u/sleep-enjoyer Sep 01 '22

I genuinely have no idea how you can have this opinion and expect to write code

1

u/nobody007 Sep 01 '22

Maybe you are busy on writing code rather than stepping back to think about the problem carefully that you are working on. Function is the only way where "divide and conquer" can be implemented properly.

1

u/[deleted] Sep 01 '22

OP is a Do repeat yourself merchant

1

u/hanneshdc Sep 01 '22

Try coding without copy-paste for a few days. You’re still allowed to cut and paste to move code around.

This will become tedious without functions!

1

u/captianjroot Sep 01 '22

Writing massive scripts isn't very reusable, portable, or maintainable.

Dividing your code into functions is easier to debug and test, because you can make your tests check smaller parts of your code at a time, making it easier to find the issue if tests fail.

If you ever need to reuse part of your code for a new project, you can just import individual functions and run then instead of importing and running an entire script.

Also if you have small chunks of logic that you reuse in the same project, you can put them in functions instead of copy pasting the same code. Reducing boilerplate like that also makes things easier if you have to change anything in the future and avoids typos from the duplication

1

u/Spoodys Sep 02 '22

Start doing test automation on some agile project, then you will understand the purpose of functions.

1

u/foto256 Sep 02 '22

If your body didn’t use functions every time to stubbed your toe your heart would stop.

1

u/Miniflint Sep 02 '22

Once you’ll understand then you’ll love it. Give it a try and see how much cleaner the code is

1

u/Vast_Manufacturer811 Sep 02 '22

You’re new to Python aren’t you? I remember when I first started out, I avoided writing functions as I actually enjoyed repeating the same lines of code over and over again.

Trust me, you think that will last forever? Ha. You’ll come to love functions soon enough.

1

u/jgr0919 Sep 02 '22

How do you test your code, I like using functions and blocks of code so that I can do incremental testing.

0

u/[deleted] Sep 01 '22

[deleted]

1

u/Outrageous_Notice445 Sep 01 '22

Oh no I suck at programming

1

u/[deleted] Sep 02 '22

sorry for being an a-hole

4

u/[deleted] Sep 01 '22

[removed] — view removed comment

1

u/PhilAndMaude Sep 01 '22

So what's the singular? :-)

0

u/[deleted] Sep 01 '22

[deleted]

5

u/GreenPandaPop Sep 01 '22

Yes, except you're using it as a verb, so the person you're replying to is still correct.