首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Hello Python 教程1

Hello Python 教程1

作者头像
keyle
发布2024-11-01 12:16:59
发布2024-11-01 12:16:59
2000
举报
文章被收录于专栏:礼拜八不工作礼拜八不工作

因为我的树莓派只要开机风扇就会不停的转为了控制风扇的转速我需要写一些脚本来控制gpio接口。所以作为兴趣就学习了一下python语言,当然python的实际作用远不止此,先看看基础的再深入的了解下吧。MacOS自带的Python是2.7x,但是我使用的是3.x 。当然这两者是有差异的,即使你不懂python也可以从版本号上看出来这个差异。 The key differences between Python 2.7.x and Python 3.x with examples <-这篇博客详细说明了2.x与3.x的区别。因为本人是从3.x学习python的所以后面的博文都会以3.x作为案例。

环境相关

  1. 使用which python3查看当前python安装地址
  2. Xcode配置系列博文
    • 用VS Code写Python程序
    • Python on Visual Studio Code
  3. Python 3 Basic Syntax(原版)
  4. Python3 运算符(翻译)

基础语法

重要概念

可更改(mutable)与不可更改(immutable)对象

在 python 中,strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象。 不可变类型:变量赋值 a=5 后再赋值 a=10,这里实际是新生成一个 int 值对象 10,再让 a 指向它,而 5 被丢弃,不是改变a的值,相当于新生成了a。 可变类型:变量赋值 la=[1,2,3,4] 后再赋值 la[2]=5 则是将 list la 的第三个元素值更改,本身la没有动,只是其内部的一部分值被修改了。 python 函数的参数传递: 不可变类型:类似 c++ 的值传递,如 整数、字符串、元组。如fun(a),传递的只是a的值,没有影响a对象本身。比如在 fun(a)内部修改 a 的值,只是修改另一个复制的对象,不会影响 a 本身。 可变类型:类似 c++ 的引用传递,如 列表,字典。如 fun(la),则是将 la 真正的传过去,修改后fun外部的la也会受影响

Keyword

代码语言:javascript
复制
and	exec	not
as	finally	or
assert	for	pass
break	from	print
class	global	raise
continue	if	return
def	import	try
del	in	while
elif	is	with
else	lambda	yield
except	

Lines and Indentation

Python用缩进代表代码块,同一个代码块的语句必须包含相同的缩进空格数。

代码语言:javascript
复制
if True:
   print ("True")

else:
   print ("False")

#如果要在当前语句换行直接用\
total = item_one + \
    item_two + \
    item_three

String

代码语言:javascript
复制
import sys
print(sys.version) #查看系统版本

print('helloworld   -0');print('helloworld   -1')
print("helloworld   -2")
print("""helloworld   -3

    End .

""",end = ">>")

print("<<")

#Output:
#3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) 
#[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
#helloworld   -0
#helloworld   -1
#helloworld   -2
#helloworld   -3
#    End .
#>><<

Formate String

字符串格式化

代码语言:javascript
复制
dic = {1:"one",2:"two"} #定义字典
print(dic[1])  #取值

print("%d < %s" % (len(dic),"length")) #格式化字符串
del dic[1]   #删除一个key-value
print(len(dic)) #检测字典长度

占位符

描述

%c

格式化字符及其ASCII码

%s

格式化字符串

%d

格式化整数

%u

格式化无符号整型

%o

格式化无符号八进制数

%x

格式化无符号十六进制数

%X

格式化无符号十六进制数(大写)

%f

格式化浮点数字,可指定小数点后的精度

%e

用科学计数法格式化浮点数

%E

作用同%e,用科学计数法格式化浮点数

%g

%f和%e的简写

%G

%f 和 %E 的简写

%p

用十六进制数格式化变量的地址

字符串辅助功能符:

符号

功能

*

定义宽度或者小数点精度

-

用做左对齐

+

在正数前面显示加号( + )

在正数前面显示空格

#

在八进制数前面显示零(‘0’),在十六进制前面显示’0x’或者’0X’(取决于用的是’x’还是’X’)

0

显示的数字前面填充’0’而不是默认的空格

%

‘%%’输出一个单一的’%’

(var)

映射变量(字典参数)

m.n.

m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)

字符串的运算

代码语言:javascript
复制
#!/usr/bin/python3

str = 'HelloWorld!'

print (str)          # Prints complete string
print (str[0])       # Prints first character of the string
print (str[2:5])     # Prints characters starting from 3rd to 5th
print (str[2:])      # Prints string starting from 3rd character
print (str * 2)      # Prints string two times
print (str + "TEST") # Prints concatenated string

#HelloWorld!
#H
#llo
#lloWorld!
#HelloWorld!HelloWorld!
#HelloWorld!TEST

Number

python支持四种类型 int、float、bool、complex(复数类型)

代码语言:javascript
复制
a, b, c, d = 20, 5.5, True, 4+3j
print(type(a), type(b), type(c), type(d))
# <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

print(isinstance(a, int)) #True

int

float

complex

10

0.0

3.14j

100

15.20

45.j

-786

-21.9

9.322e-36j

080

32.3+e18

.876j

-0490

-90.

-.6545+0J

-0x260

-32.54e100

3e+26J

0x69

70.2-E12

4.53e-7j

Tips

  • type()不会认为子类是一种父类类型。
  • isinstance()会认为子类是一种父类类型。
  • 使用python3接受命令行的多个参数

Tuples(元组)

Tuples can be thought of as read-only lists. 元组是只读的

代码语言:javascript
复制
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print (tuple)           # Prints complete tuple
print (tuple[0])        # Prints first element of the tuple
print (tuple[1:3])      # Prints elements starting from 2nd till 3rd 
print (tuple[2:])       # Prints elements starting from 3rd element
print (tinytuple * 2)   # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple

#('abcd', 786, 2.23, 'john', 70.2)
#abcd
#(786, 2.23)
#(2.23, 'john', 70.2)
#(123, 'john', 123, 'john')
#('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

无关闭分隔符 任意无符号的对象,以逗号隔开,默认为元组,如下实例:

代码语言:javascript
复制
#!/usr/bin/python

print 'abc', -4.24e93, 18+6.6j, 'xyz';
x, y = 1, 2;
print "Value of x , y : ", x,y;

Dictionary

通过花括号定义一个字典

代码语言:javascript
复制
dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print (dict['one'])       # Prints value for 'one' key
print (dict[2])           # Prints value for 2 key
print (tinydict)          # Prints complete dictionary
print (tinydict.keys())   # Prints all the keys
print (tinydict.values()) # Prints all the values
#This is one
#This is two
#{'name': 'john', 'code': 6734, 'dept': 'sales'}
#dict_keys(['name', 'code', 'dept'])
#dict_values(['john', 6734, 'sales'])

Data Type Conversion(类型转换)

Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type-names as a function. 需要类型转换的时候只需要用类型名称作为一个方法就可以转换

S.No.

Function & Description

1

int(x [,base]) Converts x to an integer. The base specifies the base if x is a string.

2

float(x) Converts x to a floating-point number.

3

complex(real [,imag])Creates a complex number.

4

str(x) Converts object x to a string representation.

5

repr(x)Converts object x to an expression string.

6

eval(str)Evaluates a string and returns an object.

7

tuple(s)Converts s to a tuple.

8

list(s)Converts s to a list.

9

set(s)Converts s to a set.

10

dict(d)Creates a dictionary. d must be a sequence of (key,value) tuples.

11

frozenset(s)Converts s to a frozen set.

12

chr(x)Converts an integer to a character.

13

unichr(x)Converts an integer to a Unicode character.

14

ord(x)Converts a single character to its integer value.

15

hex(x)Converts an integer to a hexadecimal string.

16

oct(x)Converts an integer to an octal string.

流程控制

Decision Making && Loop

代码语言:javascript
复制
a = ["a","b","c",""]

for item  in a:
  if item == "" :
     print("The Item is Empty")
  else:       
    print(item)
print("over")
#a
#b 
#c
#The Item is Empty
#over

Iterator and Generator

这块是伪代码,核心是 iter() 与 next()

代码语言:javascript
复制
list = [1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object can be traversed using regular for statement
!usr/bin/python3
for x in it:
   print (x, end=" ")
or using next() function
while True:
   try:
      print (next(it))
   except StopIteration:
      sys.exit() #you have to import sys module for this

Function

使用可变参数 *args 使用星号修饰

代码语言:javascript
复制
def functionA(content,*args):
    print(content)
    for var in args:
        print (var)
    return content

functionA(1,2,3,4,5,6)

使用lambda匿名函数,后面只可以跟一句话… (我有点想吐槽)

代码语言:javascript
复制
sum = lambda arg1, arg2:arg1+arg2

print("%d %s" % (sum(2,3), " <<<"))

Package

初始化脚本在引用这个包的时候会自动被调用。只有拥有了初始化脚本才会被python认为这是一个包。

创建包的时候自动添加了__init__.py脚本

我在这个脚本里引入这个包,输出结果

异常处理

代码语言:javascript
复制
try:
    fh = open("testfile", "w")
    try:
        fh.write("这是一个测试文件,用于测试异常!!")
    finally:
        print "关闭文件"
        fh.close()
except IOError:
    print "Error: 没有找到文件或读取文件失败"
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-04-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 礼拜八不工作 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 环境相关
  • 基础语法
    • 重要概念
      • 可更改(mutable)与不可更改(immutable)对象
    • Keyword
    • Lines and Indentation
    • String
      • Formate String
      • 字符串的运算
    • Number
  • Tips
    • Tuples(元组)
    • Dictionary
    • Data Type Conversion(类型转换)
    • 流程控制
      • Decision Making && Loop
      • Iterator and Generator
    • Function
    • Package
    • 异常处理
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档