Перейти к содержимому

Что такое name python

  • автор:

names 0.3.0

The script is available on PyPI. To install with pip:

sudo pip install names

Usage

Names can be used as a command line utility or imported as a Python package.

Command Line Usage

To use the script from the command line:

$ names Powell
Python Package Usage

Here are examples of all current features:

License

This project is released under an MIT License.

Data in the following files are public domain (derived from 1990 Census data):

  • dist.all.last
  • dist.female.first
  • dist.male.first

Changes

0.3.0 (2013-05-14)

  • Fixed Python 3 support
  • Improved tests and fixed minor bugs

0.2 (2013-02-17)

  • Initial release

Contributing

Please file bugs to the Github issue tracker. Pull requests are welcome.

Hacking and Pull Requests

Please try to conform to PEP8 for code contributions and ensure that the tests continue to function.

Please include new tests with your pull requests when appropriate.

Running the tests

You will need tox and coverage installed to run the tests on your code:

$ pip install tox coverage

To run the tests and generate a coverage report:

$ ./runtests.sh

The coverage output should look similar to this:

_____________________ summary _____________________ py27: commands succeeded py32: commands succeeded py33: commands succeeded pypy: commands succeeded flake8: commands succeeded congratulations :) Name Stmts Miss Branch BrMiss Cover -------------------------------------------------- names/__init__ 25 0 8 0 100% names/main 4 0 0 0 100% -------------------------------------------------- TOTAL 29 0 8 0 100%

Ошибка NameError в Python

NameError — одна из самых распространенных ошибок в Python. Начинающих она может пугать, но в ней нет ничего сложного. Это ошибка говорит о том, что вы попробовали использовать переменную, которой не существует.

В этом руководстве поговорим об ошибке «NameError name is not defined». Разберем несколько примеров и разберемся, как эту ошибку решать.

Что такое NameError?

NameError возникает в тех случаях, когда вы пытаетесь использовать несуществующие имя переменной или функции.

В Python код запускается сверху вниз. Это значит, что переменную нельзя объявить уже после того, как она была использована. Python просто не будет знать о ее существовании.

Самая распространенная NameError выглядит вот так:

NameError: name 'some_name' is not defined

Разберем частые причина возникновения этой ошибки.

Причина №1: ошибка в написании имени переменной или функции

Для человека достаточно просто сделать опечатку. Также просто для него — найти ее. Но это не настолько просто для Python.

Язык способен интерпретировать только те имена, которые были введены корректно. Именно поэтому важно следить за правильностью ввода всех имен в коде.

Если ошибку не исправить, то возникнет исключение. Возьмем в качестве примера следующий код:

What’s in a (Python’s) __name__?

What’s in a (Python’s) __name__?

You’ve most likely seen the __name__ variable when you’ve gone through Python code. Below you see an example code snippet of how it may look:

if __name__ == '__main__': main()

In this article, I want to show you how you can make use of this variable to create modules in Python.

Why is the _ _name_ _ variable used?

The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script.

Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.

Thanks to this special variable, you can decide whether you want to run the script. Or that you want to import the functions defined in the script.

What values can the __name__ variable contain?

When you run your script, the __name__ variable equals __main__ . When you import the containing script, it will contain the name of the script.

Let us take a look at these two use cases and describe the process with two illustrations.

Scenario 1 — Run the script

Suppose we wrote the script nameScript.py as follows:

def myFunction(): print 'The value of __name__ is ' + __name__
def main(): myFunction()
if __name__ == '__main__': main()

If you run nameScript.py, the process below is followed.

PljpjxnM1OMMW7IkexNxVfwrKhP0RH-isapH

Before all other code is run, the __name__ variable is set to __main__. After that, the main and myFunction def statements are run. Because the condition evaluates to true, the main function is called. This, in turn, calls myFunction. This prints out the value of __main__ .

Scenario 2 — Import the script in another script

If we want to re-use myFunction in another script, for example importingScript.py , we can import nameScript.py as a module.

The code in importingScript.py could be as follows:

import nameScript as ns
ns.myFunction()

We then have two scopes: one of importingScript and the second scope of nameScript . In the illustration, you’ll see how it differs from the first use case.

k9OxzvJAP-s5qeZg88jUCOCVy1syrQu4oKds

In importingScript.py the __name__ variable is set to __main__. By importing nameScript, Python starts looking for a file by adding .py to the module name. It then runs the code contained in the imported file.

But this time it is set to nameScript. Again the def statements for main and myFunction are run. But, now the condition evaluates to false and main is not called.

In importingScript.py we call myFunction which outputs nameScript. NameScript is known to myFunction when that function was defined.

If you would print __name__ in the importingScript, this would output __main__ . The reason for this is that Python uses the value known in the scope of importingScript.

Conclusion

In this short article, I explained how you can use the __name__ variable to write modules. You can also run these modules on their own. This can be done by making use of how the values of these variables change depending on where they occur.

Python — Variable Names

Variable names with more than one word can be difficult to read.

There are several techniques you can use to make them more readable:

Camel Case

Each word, except the first, starts with a capital letter:

myVariableName = «John»

Pascal Case

Each word starts with a capital letter:

MyVariableName = «John»

Snake Case

Each word is separated by an underscore character:

my_variable_name = «John»

Get Certified

COLOR PICKER

colorpicker

Get your server with W3Schools Spaces

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

https://kapelnicza.vyvod-iz-zapoya-v-stacionare-samara12.ru/