Não perca seu tempo lendo esse post!

Não perca seu tempo lendo esse post!

por Vitor Hugo Vieira de Lima -
Número de respostas: 7

Pessoal, que mesmo com o aviso veio aqui dar uma lida, eu gostaria de saber a opinião de vocês sobre as palavras reservadas.

Eu estava fazendo o trecho do código para retirar variáveis e para isso estava utilizando a lista keyword.kwlist (mostrada pelo Feliz em um post anterior), então percebi que os nomes das funções len, print, input etc, não são consideradas palavras nativas.

por exemplo:

def main():

   '''Este programa recebe uma frase e imprime letra a letra 

   '''

frase = input('digite uma frase:')

n = len(frase)

i = 0

while i<len(frase):

        print(frase[i])

        i+=1

 

main()

 

Nesse programa, eu poderia trocar len por n numa boa, mas print e input não podem ser substituidos por nada(ou podem?).

Então gostaria de saber o que pensam sobre esses nomes de funções? deve trata-los como variáveis ou não? e caso trate quando for substitui-los por um nome genérico o que seria melhor fazer?

print(outras_variaveis) ---> var1(var2)

ou 

print(outras_variáveis) ---> var() ou var

 

 

 

 

Anexo Capturar.PNG
Em resposta à Vitor Hugo Vieira de Lima

Re: Não perca seu tempo lendo esse post!

por Sergio Silva -

É possível obter a lista das funções internas (built-in functions) do python através da função dir:

>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

>>> help(dir)

Help on built-in function dir in module builtins:

dir(...)
dir([object]) -> list of strings

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.

Em resposta à Vitor Hugo Vieira de Lima

Re: Não perca seu tempo lendo esse post!

por Danilo de Paula Perl -

Eu vi essa aqui:

>>> import __builtin__
>>> dir(__builtin__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning',
 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError',
 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
 'NotImplementedError', 'OSError', 'OverflowError',
 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
 'UserWarning', 'ValueError', 'Warning', 'WindowsError',
 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
 '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer',
 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile',
 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview',
 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set',
 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

acho que ela mais a keyword ajudam bastante :)
Em resposta à Vitor Hugo Vieira de Lima

Re: Não perca seu tempo lendo esse post!

por Vitor Hugo Vieira de Lima -

Vlw pessoal, essas listas vão ajudar muito! tem uns 100 nomes ai que eu nem conhecia.

 

E quanto a tirar ou não essas funções, qual o opinião de vocês?

 

Em resposta à Vitor Hugo Vieira de Lima

Re: Não perca seu tempo lendo esse post!

por Pedro Felipe Higa Felizatto -

Então

Eu pessoalmente não tirei as funções, mas tirei seu conteúdo e as 'tokenizei' como funções propriamente ditas

Assim tenho que meu EP13 faz:

  • len(lista) --> len(), cujo token é função
  • type=tipo('len()') --> type,=,tipo(), onde type é variavel, = é = e tipo() é função
  • mat [0 ]  . append (int ('3')) --> mat[]append(), cujo token é função

Notemos que é possível colocar uma quantidade absurda de espaços dentro desse código, e que é possível fazer algo como:

       mat[0].append\

                        (2)

Que realmente adiciona 2 na primeira linha da matriz

Em resposta à Pedro Felipe Higa Felizatto

Re: Não perca seu tempo lendo esse post!

por Vitor Hugo Vieira de Lima -

vlw Feliz!

Eu acabei trocando tudo por um mesmo nome, e quanto ao que aparece dentro de '()'  ou '[]' eu apago.