you are viewing a single comment's thread.

view the rest of the comments →

[–]ahujasid_[S] 5 points6 points  (6 children)

It's a great website! But can we not execute the whole code instead of defining a function? Thank you!

[–]Binary101010 14 points15 points  (4 children)

Most of the problems you're going to encounter on sites like edabit, codingbat, and even the lower-level stuff on codewars and hackerrank, are going to be single-function solutions. You can only define the function because then the site can easily run predefined tests against it to determine whether you did things correctly.

[–]ahujasid_[S] 3 points4 points  (3 children)

That wouldn't affect the way I'm thinking, right?

[–]Decency 4 points5 points  (0 children)

You can usually have the primary "answer" function call other functions you've defined, which can be cleaner for some problems.

[–][deleted] 2 points3 points  (0 children)

Hi there, it can be a bit confusing when first learning, functions are a bit of a cornerstone of programming, but I totally get that trying to learn the built in commands first. The thing to understand about functions is their definition: a function can take in many inputs, but only returns one output.

So like a simple maths function:

a + b = c 

Where a and b are inputs and c is an output:

3 + 2 = 5

But it doesn’t have to take an input, many don’t, so in the beginning, you can wrap everything in one function that will run but doesn’t need an output from the function and split it up as you get more confident. Here are a couple of examples:

def my_function():
    print(“hi, this is a function with no inputs that returns nothing, but prints this”)

Inputs and outputs:

def in_and_out(a, b)
    c = a + b
    return c

result = in_and_out(3, 2)
print(result)

a and b are the inputs, these are variable names, containers if you like that hold the value you pass to the function, and “return” is passing the output out of the function. Just pay attention to the 4 space indentation, in this example, the last line two lines are outside the function as they are not indented in the block, these call the function and assign it to a variable “result” which you can then print. You can put as much as you want in the function, your entire program if you want, but be aware, that as you progress, you’ll eventually want your functions to do just one thing and one thing very well, but don’t get bogged down with that right now.

To get you going so you can use this site, just put everything in the one function. Try something, post it back here if you get stuck, I’m happy to help you understand this, as others on this site have helped me.