lx86 发表于 2018-8-10 11:46:57

Python基础-循环及模块

  循环:
  1.While循环
  while 条件:
  语句
  eg:重试3次错误后退出
count = 0  
_number=15
  
while count <3:
  
    guess_age = int(input(&quot;Guess age:&quot;))
  
    ifguess_age ==_number:
  
      print(&quot;Yes&quot;)
  
      break
  
    elifguess_age > _number:
  
      print(&quot;Think Smaller&quot;)
  
    else:
  
   print(&quot;Think Bigger&quot;)
  
   count+=1
  
else:
  
    print(&quot;Too Many Times&quot;)
  2.For 循环
  continue是返回到循环开始
  for i in range(&quot;下限,上限,步长&quot;):
  执行语句
  eg:程序优化,在Count=count+1后面加入判断输入
if count == 3:  
   try =input(&quot;do you want to try &quot;)
  
   if try !=&quot;n&quot;
  
   count=0
  模块:
  1.主要分为标准库与第三方库(需要下载及安装)
  2.导入库名与文件名不要相同
  一般标准库路径:Python_path----base----Lib
  第三方库的路径:……Lib---Site-packages
  sys模块-->import sys
  sys.path:Python环境变量
  sys.argv:相对路径
  os模块:import os
  os.system:调用系统cmd,结果直接输出在屏幕上,无法保存
  os.popen:调用系统命令,可保存
  eg:
cmd_res=os.popen(&quot;dir&quot;).read()  
print(&quot;-->&quot;,cmd_res)
  os.mkdir:创建目录
  eg:
  os.mkdir(&quot;new dir&quot;)
  可以自己写模块放在目录或者环境变量中方便其他程序调用
  pyc:
  Python和Java一样是编译加解释型的语言。当程序运行时,结果会保存在pyc文件中,当第二次程序运行的时候会优先查找pyc文件是否存在,如果存在则无需编译直接解释,提高效率。
页: [1]
查看完整版本: Python基础-循环及模块