How to set default value for variable?

user3619165

Imagine I have the following code in javascript

function test(string) {
    var string = string || 'defaultValue'
}

What is the python way of initiating a variable that may be undefined?

kindall

In the exact scenario you present, you can use default values for arguments, as other answers show.

Generically, you can use the or keyword in Python pretty similarly to the way you use || in JavaScript; if someone passes a falsey value (such as a null string or None) you can replace it with a default value like this:

string = string or "defaultValue"

This can be useful when your value comes from a file or user input:

string = raw_input("Proceed? [Yn] ")[:1].upper() or "Y"

Or when you want to use an empty container for a default value, which is problematic in regular Python (see this SO question):

def calc(startval, sequence=None):
     sequence = sequence or []

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

Set default value of a variable in PHP

How to set default value in function

How can I set a default variable value before select action in JavaScript

How to set a default value in a dropdown javascript

How to set default value in materialize autocomplete input?

how to set initial(default) value in dropdownButton?

How to set default value of <p:selectOneMenu

How to set default value in laravel collective form

How to set default value for radio button in react?

how to set column in GridView to default value?

Jinja2 template variable if None Object set a default value

Set exported environment variable in Bash to default value if unset, mention it once

How to set my first value (default value) in spinner as empty

How to set the value of mountPath in an env variable in kubernetes?

Set default value of validation

How do I set the value of a variable based on another variable?

How to set the default value of dropdown-menu base on URL param?

how can i set object list in default input value

PHP: How can I set a default value for $_POST array?

How to set Django model date field default value to future date?

How to set default value as blank in dropdown along with items tag

How to set a default value to ng-options (multiple select)

How to set a default value for an optional positional parameter of type Function?

Symfony 3 forms: how to set default value for a textarea widget

How to set an initial/default value for the array used by <FieldArray/>?

how to set default initial value on nz-autocomplete

How to set default value using SqlAlchemy_Utils ChoiceType

How can I set a default for column B to be the value in column A in PostgreSQL?

How to set default value of ion-datetime element?

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo