Python-01快速入门

Python-01快速入门

Python有两种主要的方式来完成你的要求:语句表达式(函数、算数表达式等)

输入输出

基本输入输出

第一个程序:Hello World!

1
2
3
4
5
6
7
8
9
10
11
12
13
# 直接输出
print (Hello World!)
## 先赋值给变量,后输出
myString = Hello World!
print myString # 该语句会输出Hello World!
myString # 该语句会输出'Hello World!',注意这样的输出带有的单引号
# 使用字符串格式操作符 %
print ("%s is number %d!" %("Python", 1)) # %s 字符串; %d 整形; %f 浮点型
print ("His height is %.2f m"%(1.83)) # 指定位数
print ("Name:%10s Age:%8d Height:%8.2f"%("Aviad",25,1.83)) # 指定占位符宽度
print ("Name:%-10s Age:%-8d Height:%-8.2f"%("Aviad",25,1.83)) # 指定占位符宽度(左对齐)

输出重定向
将输出内容重定向输出到文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 最简单的方法
all_the_text = 'hello python'
open('d:/text.txt', 'w').write(all_the_text)
all_the_data = b'abcd1234'
open('d:/data.txt', 'wb').write(all_the_data)
# 更好的办法
file_object = open('d:/text.txt', 'w')
file_object.write(all_the_text)
file_object.close()
# 分段写入
list_of_text_strings = ['hello', 'python', 'hello', 'world']
file_object = open('d:/text.txt', 'w')
for string in list_of_text_strings:
file_object.writelines(string)
list_of_text_strings = ['hello', 'python', 'hello', 'world']
file_object = open('d:/text.txt', 'w')
file_object.writelines(list_of_text_strings)

input()内建函数

获取用户输入

1
2
num = int(input("Please input your number!"))
print("Your input is %d" %num)

注释

1.使用井号注释:

1
2
# one comment
print("Hello World!")

2.使用文档字符串:

1
2
3
def foo():
"This is a doc string!"
return True

操作符

1.标准算术操作符:

操作符 说明
+
-
*
/
// 浮点除法
% 取余
** 乘方

2.标准比较操作符:

操作符 说明
< 小于
<= 小于等于
> 大于
>= 大于等于
== 左右相等
!= 不等于
<> 不等于(废弃)

3.逻辑操作符:

操作符 说明
and
or
not

数字

  • 有符号整形
    • 长整形
    • 布尔型
  • 浮点型
  • 复数

增量赋值

支持n *= 10 # n = n * 10
不支持自加和自减

####字符串;

1
2
3
4
5
6
7
pystr = 'python'
iscool = 'iscool'
pystr[0] #
pystr[2:5] #
iscool[:2] #
iscool[3:] #

Ethan wechat
欢迎扫一扫关注~
坚持原创技术分享,您的支持将鼓励我继续创作!