r/learnpython • • Dec 20 '24

Why is ":" required in the following command?

Hello, world! I'm just starting to learn Python on my own and I'm using W3Schools as my teacher. They show the following command:

if 5 > 2:
print("Five is greater than two!")

But they don't explain why ":" is necessary. For instance, this following line of code does not require a colon:

import sys

print(sys.version)

How come? And why is it important to use indentation on the first example but not the other?

Thanks in advance for your answers!

0 Upvotes

42 comments sorted by

27

u/schoolmonky Dec 20 '24

Ultimately the other commenters are right: it was just a choice that the language designers make that ifs require colons. There is a pattern to it though: any statement that begins a block (i.e. anything where the following line has to be indented) ends in a colon. I suspect they did this mostly to look like other programming languages in that regard.

2

u/Cutsa Dec 20 '24

Thank you, that explains it!

2

u/sepp2k Dec 20 '24

I suspect they did this mostly to look like other programming languages in that regard.

Which other languages? I'm not familiar with any language that uses colons to start blocks besides Python.

8

u/SicnarfRaxifras Dec 20 '24

I think they mean it's a visual break in the code block - other languages use {} for example.

6

u/sylfy Dec 20 '24

Essentially this. Where other languages use {} to denote code blocks, Python uses : and indentation, the primary motivation being to facilitate readability.

3

u/Frewtti Dec 20 '24

yaml

makefiles

pretty common, and makes sense for a whitespace controlled language.

14

u/Inevitable_Cat_7878 Dec 20 '24

It's called syntax. There is no why. To answer your questions:

  • The colon (":") is necessary. It tells python that it's the end of the condition.

  • The indent tells the computer to execute the indented lines as a group if the condition is true. Indented lines is python's way to group commands together. C and C based languages (Java, Javascript, C#, etc.) use brackets ({}) to group commands.

if 5 > 2:
  print("Five is greater than two!")
  print("adding more lines to print.")
print("Done executing the if statement")

If there is no indent, it would throw a syntax error. In the above example, since 5 is greater than 2, the 2 print functions will execute. If it was false, the computer would skip over those 2 and just print the 3rd statement.

In your 2nd example, the 2 lines will be executed in order. If you indented either one, the system will throw a syntax error since there is no reason to indent those statements.

The same lines would be written in C as follows:

if (5 > 2)
{
  printf("Five is greater than two!");
  printf("adding more lines to print.");
}
printf("Done executing the if statement");

3

u/Cutsa Dec 20 '24

Thank you! Super informative!

10

u/MidnightPale3220 Dec 20 '24

Yes, seems to be the best answer so far.

I would just like to mention that this bit is important:

  • The colon (":") is necessary. It tells python that it's the end of the condition.

Because longer conditions can span multiple lines, so Python does need to know where to stop.

Something like:

if ( traffic_light() == "green" and cars_speeding_across() == False ) 
    or (traffic_light == False and cars_in_any_direction() == False):
    cross_the_street()

Same goes for other things that take colon.

7

u/Logicalist Dec 20 '24

if 5 > 2: print("Five is greater than two!"

if 5 > 2 print("Five is greater than two!"

In the second example, how would a computer know where the if statement ends, without the colon?

5

u/Cutsa Dec 20 '24

I don't know, I've been programming for an hour :) But evidently it knows when one line ends and another begins in my second example, without a colon, so how should I know it's different when I use an if statement?

6

u/Disastrous-Team-6431 Dec 20 '24

You're asking good questions and people aren't really replying well.

In python, colons are used for a few things. One of them is control flow. Control flow is stuff like if, else, elif, try, except, for, while. You will learn about these in time, just know that they control the flow of your program - they don't assign anything, or make anything happen but they decide when and how many times things happen.

So whenever you're telling python about these things, there will be a colon and an indentation.

-4

u/Logicalist Dec 20 '24

Oh you're not here to learn anything, just ask questions.

3

u/Cutsa Dec 20 '24

Why are you being a dick?

-2

u/Logicalist Dec 20 '24

why are you wasting peoples time.

2

u/marquisBlythe Dec 21 '24

I think at this point you've already got answers to your questions above, but I'll advise you to take a proper course on the fundamentals of programming instead of W3Schools, in those courses you will learn the what, why and when of everything, you'll also learn the proper names of things like "statement", "expression", functions, loops ... .
For starter check Harvard's MOOC called CS50x as it is one of the best courses that teaches programming basics for free, (you don't need to pay for certification you get one for free at the completion of the course by Harvard itself). They have discord channel to answer your questions as well as sub-reddit by the same name.
Good luck.

3

u/Cutsa Dec 21 '24

Wow amazing! Thank you so much! Merry Christmas!!!

1

u/marquisBlythe Dec 21 '24

You are welcome.
Happy holidays!

1

u/FunnyForWrongReason Dec 20 '24

In Python the colon indicate end of the condition expression and start of the block code that will be ran if the condition is true.

The indentation indicates those lines of code are within the conditionals code block. Those lines are only ran if the condition is true. All the unindented lines that may come after are outside the condition block and will run regardless of if the condition is true.

Basics colons and indents indicate blocks of code in Python. The reason colon and indents are used was just a design choice. Other languages like C or C++ use different syntax (like using opening and closing curly brackets to mark code blocks).

1

u/Cutsa Dec 20 '24

"In Python the colon indicate end of the condition expression and start of the block code that will be ran if the condition is true.

The indentation indicates those lines of code are within the conditionals code block. Those lines are only ran if the condition is true. All the unindented lines that may come after are outside the condition block and will run regardless of if the condition is true."

Thank you, very easy to understand!

9

u/[deleted] Dec 20 '24

Syntax issue bro. That's just how the language was designed. I wouldn't think about that since you are still starting your journey.

2

u/GXWT Dec 20 '24

You’re consciously contributing to a learning sub, and this is the most upvoted comment, but if we actually take a look at the comment there’s no substance that the OP can take away.

Why not state something useful? If statements/blocks require this in Python? That would be a lot not useful to a learner than just “syntax issue bro”

1

u/ninhaomah Dec 20 '24

Why do you have weird signs like . , ? and ! at the end ? of the lines

I find them very confusing

Pls stop that

Just type

Thank you

2

u/zerokey Dec 20 '24

Good on OP for wanting to understand the whys of the language. It will make them a better programmer.

2

u/looopTools Dec 20 '24

The colon indicates the start of a scope essentially. Everything that is indented in relation to if statement is within the scope of the if statement.

In general in Python a new line in Python terminates a statement. But for things where a scope is required afterwards the : is added. It is the same for classes, functions, and so on

Also don’t use the w3c school python guide. Unless it has changed a lot since I looked at them last the quality is very low.

2

u/HunterIV4 Dec 20 '24

So, as others have pointed out, the "simple" reason is because the "if" statement starts a new block. Anything in Python that starts a new block must end with a colon; it's a visual indicator. Some examples:

if 5 > 2:
    pass

def my_function():
    pass

for element in my_list:
    pass

class MyClass:
    pass

In these cases, pass just means "don't do anything." Since Python lacks a closing block, you need a pass in these examples for the code to run.

What is a "block?" It's a section of code that runs separately from other blocks, usually based on a condition. Technically, all your code is in a block; no indentation is still a block, just at the lowest level. All code in a block is executed from top to bottom, and the statement that starts the block determines when and how the block is run. Many languages use curly braces for this; a C++ if statement would look like this:

if (5 > 2)
{
    std::cout << "Five is greater than two!" << std::endl;
}

Python uses the same logic, but treats the first indented line as the "opening" of the curly brace and the last indented line as the "ending" brace. In languages with braces, you actually don't need the indentation; the language ignores it completely, basing blocks entirely on the braces. Python, on the other hand, uses the indentation for parsing; it's not optional, and while there is some flexibility in how many spaces or tabs you use, having indentation or not has specific meanings in the language. Colons are another visible cue to make it clear that "this line starts a block," and if you end a statement with a colon, the next line should be indented every time.

The reason import sys doesn't need a colon is because it's just a statement; it's not starting a new block and has nothing to do with control flow. The print statement also doesn't need one. In fact, outside of very specific commands (if, for, while, def, and class are the most common you'll see), most lines of code you write will just end with the last part of the statement.

As to why this is needed at all, that's a bit more complicated. Some of it is just preference; the visual indicator makes it easy to see where new blocks are starting. But the actual answer is that many things that start blocks can actually span multiple lines, so it's easier to see when that happens:

if (5 > 2
    and 2 < 10) and "Strings are True":
        print(True)

Without the colon, the parser would have a hard time knowing when the actual block starts in this example. You can't just use the parentheses because they end before the second line. The parentheses are necessary; if you remove them, you'll get a syntax error, as Python can't tell if the new block is intentional, but since they end before the end of the next line, the parsing involved gets more complicated.

These problems could have been overcome when they first designed the language, sure. But it makes things easier on the parser, more clear for the readers (colons represent something specific), and it's one extra character to type per block.

The tl;dr version is this:

  • Python syntax uses colons for blocks as a visual and parsing shortcut, letting you know that the next section of code must be indented.

Hope that helps!

1

u/JamzTyson Dec 20 '24

Consider the way that this text is structured:

If it is a school day:
Get ready for school,
Go to school,
Come back home,
Do homework,
Play,
Go to bed.

The text begins with an introductory line that sets up the case that will be considered ("if it is a school day").

Following the introductory line, there is a block of (one or more) statements relating to the case that was setup in the first line.

There is a colon separating the introductory line from the block of text that follows.


In programming, "block" structures are commonly required. Python uses a syntax similar to English to write block structures:

introductory line COLON
    indented block

Other languages may use different syntax for the same purpose. One of the most common is:

introductory line OPEN_BRACE
    indented block
    CLOSE_BRACE

1

u/throwaway8u3sH0 Dec 20 '24

As others have said, it's control flow. It might help to know what the computer is "thinking" when it runs. And it might be easier to understand when the condition is false. So let's pretend the program is:

if 2 > 5:
    print("A")
print("B")

Python runs one token at a time. So it starts:

if...

I see an if statement. Let's start evaluating the condition.

2 > 5

This is false, so I will replace the condition with the boolean False and keep going. (You can do things like if 2>5 or 8>5)

if False:

A colon! Time to stop and evaluate. Because the condition is false, I'm going to skip over any indented lines (This is called control flow. You're controlling the movement of the interpreter through the code.)

    print("A")

This line is indented, so I will skip it. Next line.

print("B") 

This line is NOT indented, so I will execute it and print B to the screen

(The end of the file)

I've reach the end of the program, so I can stop

1

u/throwaway6560192 Dec 20 '24

But they don't explain why ":" is necessary. For instance, this following line of code does not require a colon:

Why did you end this sentence with a colon? To convey that the next part is related to or a continuation of this sentence, isn't it?

Python uses colons there for the same reason.

https://docs.python.org/3/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements

1

u/3thanscharlie Dec 20 '24

This guy might be onto somthin

1

u/TheRNGuy Dec 25 '24

It's Python syntax.

9

u/[deleted] Dec 20 '24

[removed] — view removed comment

-1

u/Cutsa Dec 20 '24

Thank you, that would have been explanation enough :) All prior examples were exempt from colons, but now suddenly they use one, without explaining why they suddenly use one. That was simply a little confusing <3

5

u/[deleted] Dec 20 '24

[removed] — view removed comment

1

u/Cutsa Dec 20 '24

Not really, so far they only used the if statement when describing the importance of indentation. But if I were to guess, it creates a potential conditional? As in, if 5 > 2, do x. But with code?

0

u/[deleted] Dec 20 '24

[deleted]

1

u/Cutsa Dec 20 '24

Thank you!

2

u/sylfy Dec 20 '24

Pretty sure the if (condition):, indent and code block are all part of a single construct. Without a following indent and code block, it would be invalid syntax. At minimum, you need to follow up with a “pass” statement.

1

u/[deleted] Dec 20 '24

[removed] — view removed comment

2

u/Cutsa Dec 20 '24

Okey, thank you. That makes sense. Very well explained <2