python学习之路

一、安装python

WINDOWS

1 1、下载安装包
2     https://www.python.org/downloads/
3 2、安装
4  默认安装路径:C:\python36 5 3、配置环境变量 6 【右键计算机】--》【属性】--》【高级系统设置】--》【高级】--》【环境变量】--》【在第二个内容框中找到 变量名为Path 的一行,双击】 --> 【Python安装目录追加到变值值中,用 ; 分割】 7 如:原来的值;C:\python36,切记前面有分号

LINUX

 1 1、原系统自带python2.7.5,建议更换为python3.0
 2 2、下载安装包
 3     https://www.python.org/downloads/
 4 3、安装pythhon  5 tar -xvzf Python-3.6.5.tgz  6 cd Python-3.6.5/  7 ./configure --prefix=/usr/python  8 make && make install  9 ln -s /usr/python/bin/python3 /usr/bin/python3 10 ln -s /usr/python/bin/pip3 /usr/bin/pip3

二、HELLO WORLD

  这个是仪式感~

  1、编辑文件helloworld.py

    vim helloworld.py

1 #!/usr/bin/env python
2   
3 print ("hello,world")

    chmod 755 helloworld.py

    ./helloworld.py

  2、交互模式

1 python
2 >>>print ("hello world") 3 hello world 4 >>>

三、变量

1 #_*_coding:utf-8_*_
2  
3 name = "Breeze"

上述代码声明了一个变量,变量名为: name,变量name的值为:"Breeze"

变量定义的规则:

      • 变量名只能是 字母、数字或下划线的任意组合
      • 变量名的第一个字符不能是数字
      • 以下关键字不能声明为变量名
        ['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']
 1 name = "Marry"
 2  
 3 name2 = name  4 print(name,name2)  5  6 name = "Jack"  7  8 print(name,name2)  9 10 结果为 11 12 Marry Marry 13 14 Jack Marry

四、字符编码

设置字符编码为utf-8

1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*- 3 4 print "你好,世界"

PS:当行注视:# 被注释内容

   多行注释:""" 被注释内容 """

五、数据类型

1、数字:int(整型)、long(长整型)、float(浮点型)、complex(复数)

2、布尔值:真或假、1 或 0

3、字符串

4、列表

5、元组(不可变列表)

6、字典(无序)

六、用户输入

1 #!/usr/bin/env python
2 #_*_coding:utf-8_*_ 3 4 name = input("What is your name?") 5 print("Hello " + name )

七、if......else

# 提示输入用户名和密码
  
# 验证用户名和密码
# 如果错误,则输出用户名或密码错误 # 如果成功,则输出 欢迎,XXX! #!/usr/bin/env python#_*_coding:utf-8_*_ import getpass name = input('请输入用户名:') pwd = getpass.getpass('请输入密码:') if name == "Breeze" and pwd == "123": print("欢迎,Breeze!") else: print("用户名和密码错误")

八、for循环

#如果i小于5进入循环,否则直接进入下一个过程

for i in range(10): if i<5: continue #不往下走了,直接进入下一次loop print("loop:", i )
#如果i大于5退出循环,否则直接进入下一个过程
for i in range(10): if i>5: break #不往下走了,直接跳出整个loop print("loop:", i )

九、while循环

1 i = 0
2 while True:
3 print (i) 4 i +=1
 #三次机会猜年龄
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 5 my_age = 26 6 7 count = 0 8 while count < 3: 9 user_input = int(input("input your guess num:")) 10 11 if user_input == my_age: 12 print("Congratulations, you got it !") 13 break 14 elif user_input < my_age: 15 print("Oops,think bigger!") 16 else: 17 print("think smaller!") 18 count += 1 #每次loop 计数器+1 19 else: 20 print("game over.")

猜你喜欢

转载自www.cnblogs.com/breeze-24/p/9065612.html