设为首页 收藏本站
查看: 1028|回复: 0

[经验分享] Python随笔(一)、python基础

[复制链接]

尚未签到

发表于 2018-8-4 13:55:18 | 显示全部楼层 |阅读模式
  在pycharm下设置自己的模板:
  在File---settings---File and Code Templates---Python script 脚本里添加:
  #!usr/bin/env python
  #-*- coding:utf-8 _*-
  """
  @author:${USER}
  @file: ${NAME}.py
  @time: ${YEAR}/${MONTH}/${DAY}
  """
  一、第一个python程序:
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: HelloWorld.py
  @time: 2017/11/{DAY}
  """
print("HelloWorld!!!")  print("你好,世界")
  二、变量和赋值:
  #!usr/bin/env python
  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: bianliang.py
  @time: 2017/11/18
  """
  #赋值
  name = "chenjisong"
  age = 30
  print(name,age)
  字符串类型的必须要加引号
a = 3  b = a
  a = 5
  print(a,b)
  返回结果为(5,3)
  解析:a = 3,内存地址指向3,b = a,则b = 3,此时a 和 b 都指向内存地址3,当 a = 5的时候,a 的内存地址指向了5,则a = 3 这个内存地址被回收了,但是b的内存地址未被回收,b仍然等于3,所以最后返回的结果是(5,3)
  变量起名的原则:
  1、显示,通俗易懂
  2、驼峰写法(首字母大写)          例如:NumsOfJackGf
  3、下横线写法(不能为中横线)   例如:nums_of_jack_gf
  4、不能数字开头,但是可以在中间和结尾
  5、命名中不能有特殊字符
  6、变量的命名不能有空格
  7、关键字不能声明为变量
  内存地址的验证:
  C:\Users\Administrator>python
  Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
  on win32
  Type "help", "copyright", "credits" or "license" for more information.
  >>> import keyword
  >>> a = 5
  >>> b = a

  >>>>  (1363763552, 1363763552)
  a 和 b的内存地址完全一样
  >>> a = 10

  >>>>  >>> (1363763712, 1363763552)
  当a的值改变之后,a的内存地址也发生了变化(是python中的内存地址,不是物理机器的内存地址)
  三、用户交互
  [root@python3 ~]# python
  Python 3.6.3 (default, Nov 12 2017, 04:07:16)
  [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
  Type "help", "copyright", "credits" or "license" for more information.
  >>> name = input("please input your name:")
  please input your name:chenjisong
  >>> print(name)
  chenjisong
>>> a = 5  >>> eval('a')
  5
  四、条件判断与缩进
  IF....ELSE和缩进
  伪代码:
  如果   你是富二代
  我们俩就拍拖
  或者   你很努力上进
  我们可以接触试试
  否则
  免谈
  缩进要一致:
  sex = input ("plsase input your gender:")
  if sex == "gril":
  print("I would like to have a baby")
  elif sex == "man":
  print("going to homesexual!")
  else:
  print("Pervert!!!")
  游戏:猜幸运数字:
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: lucky_number.py
  @time: 2017/11/18
  """
lucky_number = 18guess_number = int(input("can you guess my lucky_number:"))  if guess_number > lucky_number:
print("guess_number is bigger then lucky_number")  elif guess_number < lucky_number:
  print("guess_number is smaller then lucky_number:")
  else:
  print("congratulations,you guess it,but no prize")
  五、循环控制:
  break结束循环:(猜对即跳出循环,没猜对就一直猜)
while True:lucky_number = 18guess_number = int(input("can you guess my lucky_number:"))  if guess_number > lucky_number:
print("guess_number is bigger then lucky_number")  elif guess_number < lucky_number:
  print("guess_number is smaller then lucky_number:")
  else:
  print("congratulations,you guess it,but no prize")
  break
while lucky_number != input_num:input_num = int(input("input the guess num:"))  if input_num > lucky_number:
print("the real number is smaller")  elif input_num < lucky_number:
  print("the real number is bigger")
  else:
  print("bingo")
  六、循环次数限制:
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: lucky_number.py
  @time: 2017/11/18
  """
  lucky_number = 18
  input_num=-1
  guess_count = 0
  #while lucky_number != input_num:
  while guess_count < 3:
  input_num = int(input("input the guess num:"))
  print("guess count:",guess_count)
  if input_num > lucky_number:
  print("the real number is smaller")
  elif input_num < lucky_number:
  print("the real number is bigger")
  else:
  print("Bingo!")
  break
  guess_count += 1
  else:
  print("try too many times")
  两重判断:
  第一重:三次猜不对直接退出(guess_count>3),打印“try too many times”
  第二重:猜对了直接打印bingo,退出
  for循环猜数字游戏:
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: lucky_number.py
  @time: 2017/11/18
  """
  #while True:
lucky_number = 18input_num=-1for i in range(5):input_num = int(input("input the guess num:"))  if input_num > lucky_number:
print("the real number is smaller")  elif input_num < lucky_number:
  print("the real number is bigger")
  else:
  print("Bingo!")
  break
  else:
  print("try too many times")
  七、常用数据类型
  数据类型:
  数字:
  int(整型)
  float(浮点型)
  long(长整型)
  布尔:(True(1) 和  False(0))  真和假
  字符串    str
  列表        list
  元祖       tuple
  字典       dict
  type可以查看数据类型:
  >>> type(2**10)
  <class 'int'>
  >>> type(2.99)
  <class 'float'>
  八、字符串格式化
  第一种写法会开辟很多内存空间,对内存资源是一种浪费,所以不建议
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: string_format.py
  @time: 2017/11/18
  """
name = input("name:")  age = input("age:")
  job = input("job:")
  print("Information of "+ name +"\nName:" + name +"\nAge:"+ age +"\nJob:"+ job +"")
  第二种写法只开辟了一块内存空间,可以有效节省内存资源,效率更优
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: string_format.py
  @time: 2017/11/18
  """
name = input("name:")  age = input("age:")
  job = input("job:")
  print
("Information of %s:\nName:%s\nAge:%s\nJob:%s" %(name,name,age,job))  %s要与后面的值一一对应,否则会报错
  第三种写法:
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: string_format.py
  @time: 2017/11/18
  """
name = input("name:")  age = input("age:")
  job = input("job:")
  msg = '''
  Information of %s:
  Name:%s
  Age :%s
  Job :%s
  '''
%(name,name,age,job)  print(msg)
  '''
  '''的妙用
  九、列表常用操作:
  strip:去掉,拿掉空格:以下例子去掉了前面的空格,但是中间的没法去掉
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: string_format.py
  @time: 2017/11/18
  """
name = input("name:").strip()  age = input("age:").strip()
  job = input("job:").strip()
  msg = '''
  Information of %s:
  Name:%s
  Age :%s
  Job :%s
  '''
%(name,name,age,job)  print(msg)
  输入
  name:          chen    jisong
  age:     22
  job:                 IT
  输出:
  Information of chen    jisong:
  Name:chen    jisong
  Age :22
  Job :IT
  也可以去掉字符:如下
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: string_format.py
  @time: 2017/11/18
  """
name = input("name:").strip("chen")  age = input("age:").strip()
  job = input("job:").strip()
  msg = '''
  Information of %s:
  Name:%s
  Age :%s
  Job :%s
  '''
%(name,name,age,job)  print(msg)
  输入
  name:           chen    jisong
  age:     22
  job:                 IT
  输出:
  Information of jisong:
  Name:jisong
  Age :30
  Job :IT
  列表索引(下标)取值:   []
  [root@python3 ~]# python
  Python 3.6.3 (default, Nov 12 2017, 04:07:16)
  [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
  Type "help", "copyright", "credits" or "license" for more information.
  >>> name_list = ["65brother","87brother","99brother"]
  >>> name_list
  ['65brother', '87brother', '99brother']
  >>> name_list[0]
  '65brother'
  >>> name_list[1]
  '87brother'
  >>> name_list[2]
  '99brother'
  >>> dir(name_list)
  ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
  index        索引:
  count       计数:
  append    追加:
  insert       插入:
  pop          删除最后一个索引值
  remove    删除固定的值
  reverse     反转
  sort           排序
  extend      列表的扩展
  >>> name_list
  ['65brother', '87brother', '99brother']
  >>> name_list.append("Eric")
  >>> name_list
  ['65brother', '87brother', '99brother', 'Eric']
  >>> name_list.append("87brother")
  >>> name_list
  ['65brother', '87brother', '99brother', 'Eric', '87brother']
  >>> name_list.index("87brother")
  1
  >>> name_list.count("87brother")
  2
  >>> name_list.insert(2,"66brother")      在索引2之后加66brother
  >>> name_list
  ['65brother', '87brother', '66brother', '99brother', 'Eric', '87brother']
  >>> name_list.remove("66brother")
  >>> name_list
  ['65brother', '87brother', '99brother', 'Eric', '87brother']
  >>> name_list.pop()
  '87brother'
  >>> name_list
  ['65brother', '87brother', '99brother', 'Eric']
  >>> name_list.reverse()
  >>> name_list
  ['Eric', '99brother', '87brother', '65brother']
  >>> name_list.sort()
  >>> name_list
  ['65brother', '87brother', '99brother', 'Eric']
  >>> name_list.append("87brother")
  >>> name_list.append("87brother")
  >>> name_list
  ['65brother', '87brother', '99brother', 'Eric', '87brother', '87brother']
  要一次删除3个87brother,应当怎么做???
  >>> for i in range(name_list.count('87brother')):
  ...    name_list.remove("87brother")
  ...
  >>> name_list
  ['65brother', '99brother', 'Eric']
  十、列表的后续操作
  [root@python3 ~]# python
  Python 3.6.3 (default, Nov 12 2017, 04:07:16)
  [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
  Type "help", "copyright", "credits" or "license" for more information.
  >>> a = [1, 2, 4, 3, 'a', 'b']
  >>> a
  [1, 2, 4, 3, 'a', 'b']
  >>> a.insert(1,8)     ---在索引一处插入数字
  >>> a
  [1, 8, 2, 4, 3, 'a', 'b']
  正向切片:
  >>> a[3:5]
  [4, 3]
  >>> a[0:7]
  [1, 8, 2, 4, 3, 'a', 'b']
  反向切片:
  >>> a[-4:]
  [4, 3, 'a', 'b']
  >>> a[-4:-1]
  [4, 3, 'a']
  >>> a[0:7]
  [1, 8, 2, 4, 3, 'a', 'b']
  >>> a.sort()
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  TypeError: '<' not supported between instances of 'str' and 'int'  字符串和整型不能进行排序
  >>> a[0:7]
  [1, 2, 3, 4, 8, 'a', 'b']
  >>> a.pop()
  'b'
  >>> a.pop()
  'a'
  >>> a.sort()
  >>> a
  [1, 2, 3, 4, 8]
  拿掉字符串后即可进行排序
  列表可以相加:
  >>> a = [1,2,3,4,5,6,7,8,9]
  >>> b = ["a","b","c","d","e","f","g","h","i"]
  >>> a + b
  [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
  >>> a.extend(b)
  >>> a
  [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
  十一、二进制位运算
  元祖:
  >>> t = (1,2,3,4)
  >>> dir(t)
  ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
  元祖改列表,用list方法:
  >>> type(t)
  <class 'tuple'>
  >>> list(t)
  [1, 2, 3, 4]
  >>> type(t)
  <class 'tuple'>
  >>> a = list(t)
  >>> type(a)
  <class 'list'>
  二进制运算:
  >>> A = 10
  >>> B = 50
  >>> A & B              两者都真才为真
  2
  >>> A | B                两者有一真就为真
  58
  >>> A ^ B              一真一假则为真
  56
  >>> A >> 1            整体往右移一位
  5
  >>> A << 1            整体往左移一位
  20
  >>> B >> 1
  25
  >>> B << 1
  100
  逻辑运算符:与(and)  或(or)  非(not)
  >>> sex = "man"
  >>> age = 26
  >>> if sex == "man" and age > 25:
  ...    print("time to get married")
  ...
  time to get married
  >>> sex = "man"
  >>> age = 26
  >>> if sex == "man" or age < 23:
  ...     print("do not worried")
  ...
  do not worried
  >>> name_list=["oldboy","alex","eric"]
  >>> if "jack" not in name_list:
  ...      print("sorry")
  ...
  sorry
  身份运算符(is    is not)
  >>> name_list=["oldboy","alex","eric"]
  >>> type(name_list) is tuple
  False
  >>> type(name_list) is list
  True
  >>> type(name_list) is not list
  False
  >>> type(name_list) is not tuple
  True
  十二、简单的嵌套循环
  continue  跳出本次循环,继续下一次循环:
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: cotinue.py
  @time: 2017/11/19
  """
for i in range(10):if i < 5:continueprint(i)  执行结果如下:
  E:\Python36\python.exe C:/Users/Administrator/PycharmProjects/S12/2017-11-18/cotinue.py
  5
  6
  7
  8
  9
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: cotinue.py
  @time: 2017/11/19
  """
for j in range(5):for i in range(10):if i < 5:continue  if
j> 3:breakprint(i)  执行结果:
  5
  6
  7
  8
  9
  5
  6
  7
  8
  9
  5
  6
  7
  8
  9
  5
  6
  7
  8
  9
  十三、文件的基本操作
  读取文件的内容:
  一次性加载所有内容到内存
  obj.read()
  一次性加载所有内容到内存,并根据行分割成字符串
  obj.readlines()
  每次仅读取一行数据:
  for line in obj:
  print line
  写入文件内容:
  obj.write(“内容”)
  关闭文件句柄:
  obj.close()
  打开文件:
  file_obj = file("文件路径","模式")
  file_obj = open("文件路径","模式")
  打开文件的模式有:
  r          以只读方式打开文件。
  w         打开一个文件只用于写入。
  a          打开一个文件用于追加。
  w+       打开一个文件用于读写。
  写文件的操作:
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: file_opr.py
  @time: 2017/11/19
  """
f = open("test.log","w")  f.write("this is the first line\n")
  f.write("this is the second line\n")
  f.write("this is the third line\n")
  f.write("this is the fourth line\n")
  f.close()
  test.log下面的文字:
this is the first line  this is the second line
  this is the third line
  this is the fourth line
  读文件的操作,循环逐行读取:
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: file_opr.py
  @time: 2017/11/19
  """
f = open("test.log","r")  #f.write("this is the first line\n")
  #f.write("this is the second line\n")
  #f.write("this is the third line\n")
  #f.write("this is the fourth line\n")
for line in f:print (line),  f.close()
  执行结果:
  this is the first line
  this is the second line
  this is the third line
  this is the fourth line
  判断:
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: file_opr.py
  @time: 2017/11/19
  """
f = open("test.log","r")  #f.write("this is the first line\n")
  #f.write("this is the second line\n")
  #f.write("this is the third line\n")
  #f.write("this is the fourth line\n")
for line in f:if "third" in line:print ("this is 3 line")  else:
  print(line)
  f.close()
  追加文件操作:
#!usr/bin/env python  #-*- coding:utf-8 _*-
  """
  @author:Administrator
  @file: file_opr.py
  @time: 2017/11/19
  """
f = open("test.log","a")  #f.write("this is the first line\n")
  #f.write("this is the second line\n")
  #f.write("this is the third line\n")
  #f.write("this is the fourth line\n")
  #for line in f:
  #   if "third" in line:
  #       print ("this is 3 line")
  #   else:
  #       print(line)
f.write("8\n")  f.write("9\n")
  f.write("5\n")
  f.write("6\n")
  f.write("7\n")
  f.close()
  test.log输出结果:
this is the first line  
this is the second line
  
this is the third line
  
this is the fourth line
  
8
  
9
  
5
  
6
  
7

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-546547-1-1.html 上篇帖子: Python 学习笔记 - 操作MySQL 下篇帖子: mac 部署python环境
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表