python3 入门(1)20201021

it2025-02-03  9

在 Python 中 我们不需要为变量指定数据类型。所以你可以直接写出 abc = 1 ,这样变量 abc 就是整数类型。如果你写出 abc = 1.0 ,那么变量 abc 就是浮点类型。一,初了解

0.交互模式

在Linux环境中

输入python3进入交互模式,可直接输入代码

ctrl+d退出交互模式

1.创建文本

vim helloworld.py

2.执行

#!/usr/bin/env python3 print("Hello World!")

执行:

chmod +x helloworld.py       #为文件添加可执行权限

./helloworld.py

print("Hello World!")

这里需要注意如果程序中没有 #!/usr/bin/env python3 的话,应该使用 python3 helloworld.py 来执行,否则使用 ./helloworld.py 程序会被当作 bash 脚本来执行,最终报错。

执行:无第一行

chmod +x helloworld.py

python3 helloworld.py

3.代码风格之——空格

建议遵守以下约定:

使用 4 个空格来缩进永远不要混用空格和制表符在函数之间空一行在类之间空两行字典,列表,元组以及参数列表中,在 , 后添加一个空格。对于字典,: 后面也添加一个空格在赋值运算符和比较运算符周围要有空格(参数列表中除外),但是括号里则不加空格:a = f(1, 2) + g(3, 4)

4.注释

以#开始,应该   #加空格加注释

5.模块

模块是包含了我们能复用的代码的文件,包含了不同的函数定义,变量。模块文件通常以 .py 为扩展名。

Python 本身在默认安装时就带有大量的模块。我们之后将会用到其中的一部分。在使用模块前先导入它。

>>> import math # 导入math模块 >>> print(math.e) 2.71828182846

二,变量&数据类型

1.关键字和标识符

下列的标识符是 Python3 的关键字,并且不能用于通常的标识符。关键字必须完全按照下面拼写:

False def if raise None del import return True elif in try and else is while as except lambda with assert finally nonlocal yield break for not class from or continue global pass

可以通过一下步骤在Linux中查看

1.python3 2.help() 3.keywords >>> 'hello world' 'hello world' >>> 'she\'s best' "she's best" >>> "Hello World!" 'Hello World!' >>> a = 13 >>> b = 23 >>> a + b 36

在 Python 中 我们不需要为变量指定数据类型。所以你可以直接写出 abc = 1 ,这样变量 abc 就是整数类型。如果你写出 abc = 1.0 ,那么变量 abc 就是浮点类型。

2.从键盘读取输入

#!/usr/bin/env python3 amount = float(input("Enter amount: ")) # 输入数额 inrate = float(input("Enter Interest rate: ")) # 输入利率 period = int(input("Enter period: ")) # 输入期限 value = 0 year = 1 while year <= period: value = amount + (inrate * amount) print("Year {} Rs. {:.2f}".format(year, value)) amount = value year = year + 1 #运行程序 $ cd /home/shiyanlou $ chmod +x investment.py $ ./investment.py Enter amount: 10000 Enter Interest rate: 0.14 Enter period: 5 Year 1 Rs. 11400.00 Year 2 Rs. 12996.00 Year 3 Rs. 14815.44 Year 4 Rs. 16889.60 Year 5 Rs. 19254.15

while year <= period: 的意思是,当 year 的值小于等于 period 的值时,下面的语句将会一直循环执行下去,直到 year 大于 period 时停止循环。

Year {} Rs. {:.2f}".format(year, value) 称为字符串格式化,大括号和其中的字符会被替换成传入 str.format() 的参数,也即 year 和 value。其中 {:.2f} 的意思是替换为 2 位精度的浮点数。

最新回复(0)