• python 笔记2:python语法基础


     python语法学习笔记:

    1 输入输出 input(),print()。

    name = input('input your name : ')
    print('hello ,'+name)
    print(" I'm python "*3)
    print('{}+{}={}'.format(1,2,1+2))
    print(1,2,['x','y'],'a')
    print(type('1'),type(1))
    print(len(name))

    运行结果:

    2 打开文件,写入数据。

    file=open('D:/Program Files/dinghanhua/file.txt','w')
    file.write('this is a file. the second line.')
    file.close
    print('Done!')

    with open('Path/file1.txt','r') as f1:

      for line in f1:

        print(line)

     运行结果:

    3 字符串切片,查找,按空格分离

    name='My name is Mike'
    print(name[0])
    print(name[-4])
    print(name[11:14])
    print(name[5:])
    print(name[:5])
    print(name[-3:-1])

    account='13800001234'
    hiding_number=account.replace(account[:7],'*'*7)
    print(hiding_number)

    num1='13588823888'
    search='23'
    print(num1.find(search))

    import string
    list='where is your bag? I am finding it.'

    print(list.split())
    print([word.strip(string.punctuation).lower() for word in list.split()])

    运行结果:

    4 函数

    def third(a=1,b=1):

      c=(a**2+b**2)**(1/2)
      return(c)

    print(third(3,4))

    5 条件判断 if ... elif... else:

    n=input('your choice: 1,2,3')
    if n in ['1','2','3']:
      if int(n)==1:
        print('service 1')
      elif int(n)==2:
        print('service 2')
      else:
        print('service 3')
    else:
      print('invalid input.')

    6 循环 for,while

    显示乘法口诀表:

    for i in range(1,10):
      for j in range(1,i+1):
        print( '{}*{}={} '.format(j,i,i*j),end='')
      print()

     

    7 其他:

    程序包含中文,在最上面加上注释:# -*- coding=utf-8 -*-

    列表:list=[1,2,'a',['x']]  列表和字符串一样可以切片

    list=[1,2,'a',['x']]
    print(list[0],list[2:],list[:3])

    字典:

    dict={'key1':'value1','key2':'value2'}

    print(dict['key1'])

    集合:元素无重复,不能用索引

    set={1,3,2,3,4,5,'1'}
    print(set)

    元祖:tuple

    tuple=(1,'a','b',2)

    tuple=(1,'a','b',2)
    print(tuple[0])

  • 相关阅读:
    Linux查看当前系统的发行版信息
    用 CentOS 7 打造合适的科研环境
    消息队列的使用场景
    RabbitMQ几种Exchange 模式
    JMS规范概览
    消息队列的学习
    springMVC参数传递实例
    java8时间处理实例
    windows电脑常用必备软件
    http后台json解析实例
  • 原文地址:https://www.cnblogs.com/dinghanhua/p/6251212.html
Copyright © 2020-2023  润新知