Use of colon character ":" in Python

Asked

Viewed 4,285 times

7

In Python there is the character colon :, therefore, what I understand of this character is that it is used in functions def soma(x,y):, conditional commands if soma > 100: and for classes class Carro(object):, to indicate the end of the header and so on. However, is there any purpose for it other than the ones mentioned above? If there is another purpose, the colon : becomes some kind of operator?

A small practical example of the use of colon : for illustration:

def soma(x,y):
    return x + y

x = input("Valor de x:")
y = input("Valor de y:")

soma = soma(x,y)

if soma > 100:
    print("Resultado maior que 100")
  • 1

    Slices. I can’t remember another.

  • 1

    In some other scripting languages like php and javascript it can be used to define a tenario operator on this site has a very simple example: http://aprenda-python.blogspot.com.br/2010/11/operador-ternario.html now in python as Voce said it indicates the end of the header. on the website of python brasil has a more elaborate introduction on the subject http://wiki.python.org.br/AspectosFormaisDaLinguagemPython

  • 1

    It’s a very strange question - I don’t think it helps to understand the language, keep asking "all the contexts in which the character X" is used. If it takes a use you don’t understand, ask. I myself did not remember at first the use in dictionaries and in slices of indexes (Slices) - but when we need to write these expressions the ":" occurs naturally.

3 answers

2

The operator : is also used in the construction of dictionaries or Dictionary. Dictionaries use the concept of hash tables, in which each value has a key that can be a String, a tuple, or anything that is immutable. Keys are separated from values by :

Example:

dic_pessoa = {"nome":"zézinho","Idade":10,"Cidade":"Patopólis"};
print(dic_pessoa['nome']); #imprime 'zézinho'

2


As I commented above, I don’t think it’s a very helpful kind of question - but come on, there are four uses that I’m remembering now, and one that doesn’t happen that’s worth mentioning:

: indicates the beginning of a block. As you pointed out in the question, these commands are not, but anyone who starts a code block has a : at the end of the line. In this sense it is similar to the { of C and derived languages with the difference that it is never optional: In C (or its syntactic descendants, like C++, Java, Javascript, PHP, C# , objective C, etc.), after a flow control command, it is generally optional to open a key - you can put a single expression (ending with ;).

In Python is always required : and more, it is always mandatory that in the sequence comes a block of code with greater identation than that of the line in which was the : - even though you didn’t want to do anything in this block (for example, a clause except and that you just want to silence an error. If you want a block that does nothing, it should contain the command pass properly devised:

a = 0
try:
    a = valor/ valor2
except ZeroDivisionError:
    pass

: is used in the construction of dictionaries - as well as reminded @Ironman in his reply. The syntax is similar to that of Javascript dictionaries - dados = {"chave": "valor", "chave2": "valor2"}. Dictionaries can also be created with direct calling of the built-in function dict, using function call syntax with keyword arguments, which dispenses with the :: dados = dict(chave="valor", chave2="valor2") - note that in this case, the language automatically transforms the name of the parameters passed as keyword into strings that will be keys in the dictionary. Using the dictionary builder with { }, Quotes are required to indicate that keys are strings, and in addition keys can a wide variety of Python objects, not just strings. These are differences for the Javascript dictionary.

Moreover, the construction with keys, but with values separated by ,, without key and value pairs, create another Python object: sets (sets): meu_conjunto = {"dado1", "dado2", "dado3"}. It is a very different type of object from a dictionary that only has in common with the same algorithm to know if a given item is part of the same or not (in the case of Python the continence is in relation to the keys, not the values).

: serves to declare "slices" (Slices), as @Pablo recalled, while retrieving items from sequences. Virtually any modern language allows you to retrieve a single item from a sequence with a number in brackets. a = "overflow"; a[0]; -> 'o' - but Python allows you to specify [inicio:fim] inside the brackets a = "overflow"; a[1:5]; -> 'verf', or [inicion:fim:passo]. Just this week I explained well how slices work in this other answer: How list assignment works using range?

: can create annotations about parameters of a function in Python 3.x, so optional.

Python is a dynamic language, and any parameter or variable always references any type of object. However, often in large systems, frameworks, working methodologies, or to help static testing tools and even Ides can help you have some information about what kind of data a parameter should be, or what kind of parameters it should return. In Python 3 they created a syntax for "annotations" -

We usually declare a function like this:

>>> def soma2(a, b):
...     return a + b
... 

But it can be done like this:

>>> def soma(a: int, b: int) -> int:
...     return a + b
... 

This syntax does nothing by itself, only creates a function either has as one of its attributes a dictionary name __annotations__, which stores the information placed in the creation of the function:

>>> soma.__annotations__
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

This syntax is valid since Python 3.0 in 2008 - but does nothing, nor modifies any behavior - and values after the : They don’t have to be classes, they can be any valid expression. This does not prevent the programmer from creating a decorator, or another way of analyzing the code both before use and at runtime to do things with these annotated values. But it was only in 2015, with PEP 484, that the language declared a preferred way to use these annotations, and tools that help or benefit from this use. Check out the PEP 484 who speaks of this.

Needless to say, while the first three uses of : are part of the everyday life of any programmer beginner or fluent in Python, this fourth type has still incipient use and you will hardly find code that uses these markings. It is possible that some large projects, or internal team work, start using annotations after PEP 484, in code made from this year.

: do not work, finally, as he reminded @ӝin the comments, as part of the ternary operator of if, as in languages derived from C. On C and off-line, it works: condicao? valor1: valor2 - the expression in condition is evaluated - if true, the whole expression is valid valor1, otherwise is used valor2. In Python, this one if as an expression is written in full, in a way reminiscent of the spoken language: valor1 if condicao else valor2 - in this case, the expression "valor1", as in "?:" of C, is evaluated only if the condition is true - otherwise the expression is evaluated in "valor2".

  • Her answer helped me to understand other features of the language that I didn’t even know, and that will be useful in my day, I’m sure that any beginner in programming and even more in Python, will learn from her question and her answer, since the research concerning the : in Python did not return concrete results. Thank you :D

2

The character : indicates that we will start a subblock of code. The equivalent of { in Javascript and Java.

Next lines must be indented. It is used in function statements def, class, instructions if, for, etc..

Note that it is allowed (although not compliant with PEP8) that a one-line sub-block is written on the same line of code. Using your example, we could also write.

if soma > 100: print("Resultado maior que 100")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.