Python之路第三篇——Python入门

一、编程的仪式,第一句Python代码

 1 print("Hello World !") 


1. 第一句python

- 后缀名是可以是任意?可以是任意后缀,但是不专业,以后导入模块的时候非.py文件也会直接报错。

- 导入模块时,如果不是.py文件

==> 以后文件后缀名是 .py

2. 两种执行方式

python解释器 py文件路径

python 进入解释器:

实时输入并获取到执行结果

3. 解释器路径

#!/usr/bin/env python

4. 编码

# -*- coding:utf8 -*-  Python2.x版本在写中文的时候需要声明字符编码,Python3中默认支持中文,则不需要这个声明步骤。

二、注释

当行注视:# 被注释内容

多行注释:""" 被注释内容 """  三个单引号也可以

三、变量

变量的作用:昵称,其代指内存里某个地址中保存的内容。推荐使用下划线命名法 user_name

字母
数字
下划线

PS:

数字不能开头

不能是关键字

['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

最好不好和python内置的东西重复

四、执行脚本传入参数

Python有大量的模块,从而使得开发Python程序非常简洁。类库有包括三中:

  • Python内部提供的模块
  • 业内开源的模块
  • 程序员自己开发的模块

Python内部提供一个 sys 的模块,其中的 sys.argv 用来捕获执行执行python脚本时传入的参数

1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3   
4 import sys
5   
6 print sys.argv

五、 pyc 文件

执行Python代码时,如果导入了其他的 .py 文件,那么,执行过程中会自动生成一个与其同名的 .pyc 文件,该文件就是Python解释器编译之后产生的字节码。

ps:代码经过编译可以产生字节码;字节码通过反编译也可以得到代码。

六、输入

执行一个操作

提醒用户输入:用户和密码

获取用户名和密码,检测:用户名=root 密码=root

正确:登录成功

错误:登陆失败

input的用法,永远等待,直到用户输入了值,就会将输入的值赋值给一个东西

1 db_name = "root"
2 db_password = "123123"
3 
4 user_name = input("Please input your name:")
5 user_psw = input("Plese input your password:")
6 print("Success")

七、流程控制和缩进

if 条件语句,缩进用4个空格
a.

 1 n1 = input('>>>')
 2 
 3 if "Python" == "Python":
 4   n2 = input('>>>')
 5   if n2 == "确认":
 6     print('Python ok')
 7   else:
 8     print('Python no')
 9 else:
10   print('error')
11 
12 
13 注意:
14 n1 = "Python" 赋值
15 n1 == 'Python’ 比较

b.

 1 if 条件1:
 2   pass
 3 elif 条件2:
 4   pass
 5 elif 条件3:
 6   pass
 7 else:
 8   pass
 9 
10 print('end')

c. 条件1
and or

1 if n1 == "Python" or n2 == "Python!23":
2     print('OK')
3 else:
4     print('OK')

PS:
pass 代指空代码,无意义,仅仅用于表示代码块

八、基本数据类型

字符串 - n1 = "alex" n2 = 'root' n3 = """eric""" n4='''tony'''
数字 - age=21 weight = 64 fight = 5

加减乘除等:

字符串:
加法:

1 n1 = "hello"
2 n2 = "Python"
3 n4 = "great"
4 n3 = n1 + n2 + n4

# "helloPythongreat"

乘法:

1 a = "Python"
2 
3 print(a*3)

# PythonPythonPython

数字:

1 n1 = 9
2 n2 = 2
3                             
4 n3 = n1 + n2
5 n3 = n1 - n2
6 n3 = n1 * n2
7 n3 = n1 / n2
8 n3 = n1 % n2
9 n3 = n1 ** n2

九、循环

死循环

1 while 1==1:
2 print('ok')
1 while 条件:
2      
3     # 循环体
4  
5     # 如果条件为真,那么循环体则执行
6     # 如果条件为假,那么循环体不执行

break 用于退出所有循环

1 while True:
2     print "123"
3     break
4     print "456"

continue用于退出当前循环,继续下一次循环

1 while True:
2     print "123"
3     continue
4     print "456"
原文地址:https://www.cnblogs.com/webfuns/p/8464387.html