Skip to content

Files

Latest commit

6ac86f5 · Jun 26, 2020

History

History
119 lines (75 loc) · 3.1 KB

5.md

File metadata and controls

119 lines (75 loc) · 3.1 KB

运行 python 程序

原文: https://thepythonguru.com/running-python-programs/


于 2020 年 1 月 7 日更新


您可以通过两种方式运行 python 程序,首先通过直接在 python shell 中键入命令或运行存储在文件中的程序。 但是大多数时候您想运行存储在文件中的程序。

让我们在记事本目录中创建一个名为hello.py的文件,即使用记事本(或您选择的任何其他文本编辑器)创建一个C:\Users\YourUserName\Documents,记住 python 文件具有.py扩展名,然后在文件中编写以下代码。

print("Hello World")

在 python 中,我们使用print函数将字符串显示到控制台。 它可以接受多个参数。 当传递两个或多个参数时,print()函数显示每个参数,并用空格分隔。

print("Hello", "World")

预期输出

Hello World

现在打开终端,并使用cd命令将当前工作目录更改为C:\Users\YourUserName\Documents

CHANGE-CURRENT-WORKING-DIRECTORY.png

要运行该程序,请键入以下命令。

python hello.py

RUNNING-HELLO-WORLD-PROGRAM.png

如果一切顺利,您将获得以下输出。

Hello World

获得帮助


使用 python 迟早会遇到一种情况,您想了解更多有关某些方法或函数的信息。 为了帮助您,Python 具有help()函数,这是如何使用它。

语法

要查找有关类别的信息:help(class_name)

要查找有关方法的更多信息,属于类别:help(class_name.method_name)

假设您想了解更多关于int类的信息,请转到 Python shell 并键入以下命令。

>>> help(int)

Help on class int in module builtins:

class int(object)
| int(x=0) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.

如您所见,help()函数使用所有方法吐出整个int类,它还在需要的地方包含说明。

现在,假设您想知道str类的index()方法所需的参数,要找出您需要在 python shell 中键入以下命令。

>>> help(str.index)

Help on method_descriptor:

index(...)
S.index(sub[, start[, end]]) -> int

Like S.find() but raise ValueError when the substring is not found.

在下一篇文章中,我们将学习 python 中的数据类型和变量。