4

I add colon and semicolon after print but interpreter is not throwing error.

please run with python3.8.x(edit)

x=5
print:(x)
print;(x)
  • `print;(x)` is a function, that is not called, follow by a parenthesized expression. – thebjorn Aug 04 '20 at 18:38
  • 1
    Because it is not actually an error. What kind of error were you expecting? – wim Aug 04 '20 at 19:05
  • For semicolon: [Why is semicolon allowed in this python snippet?](https://stackoverflow.com/q/48323493/7851470) – Georgy Aug 08 '20 at 11:26

2 Answers2

5

The interpreter thinks the colon is a type annotation. Which is why it raises SyntaxError in earlier versions of Python, but is valid syntax in Python 3.6+.

In later versions of Python this is valid

a: int

As is this

import sys

def exclaim(string):
    sys.stdout.write(f"{string}!")

print = exclaim
print("Hello")

I.e. You can annotate the type of a variable. And you can reassign print.

So when you do print:(x) the interpreter just thinks you're annotating print to be of "type" 5.

Semi-colons are valid Python, and are used to put two separate statements on the same line. They're just considered to by "unpythonic". You do see them used sometimes to do things like import pdb; pdb.set_trace()

wim
  • 338,267
  • 99
  • 616
  • 750
Batman
  • 8,571
  • 7
  • 41
  • 80
  • 2
    But why? According to [PEP526](https://www.python.org/dev/peps/pep-0526/#specification) it should look like `my_var: int`. Why it still considers it to be valid? – Asocia Aug 04 '20 at 18:39
  • In 3.5, it works in a function definition, but not by itself; maybe a bug in 3.5 – user Aug 04 '20 at 18:42
  • @Pat-Laugh I get the same result in 3.7.5. – Mark Ransom Aug 04 '20 at 18:47
  • Not exactly: `print:(int)` would annotate with int. `print:(x)` annotates it with "5". – wim Aug 04 '20 at 19:03
  • @wim Yes, good point. Edited. – Batman Aug 04 '20 at 19:05
  • @RatnapalShende Type annotations don't actually affect the type. Or even restrict the values that can be assigned to it. They're really only used by type checkers like `Mypy`. – Batman Aug 04 '20 at 19:58
  • Got it bro....... Thank you so much for your breef explainantion ! – Ratnapal Shende Aug 04 '20 at 20:30
  • @Batman *"the interpreter just thinks you're annotating print to be of "type" 5"* Well, this is still wrong I guess. `5` is not a `type` but `int` is. `>>> type(int) >>> type(5) ` – Asocia Aug 11 '20 at 18:22
2

for print;(x), the interpreter treats it like 2 different statements, print and (x). The interpreter prints out "<built-in function print>" and "5". The print function is a built-in function. x is set to 5 so it prints out 5 too. print:(x) is a type annotation as said in @Batman's answer

aidan0626
  • 307
  • 3
  • 8