python初学

来源:互联网 发布:武汉淘宝图片拍摄 编辑:程序博客网 时间:2024/06/06 12:41

python初学

在学习python的前面学过C语言,现在学习python的目的是学习opencv,使用python会相对简单
python的安装一般步骤就不写了直接进入主题

python的数字

python可以直接当成一个计算器,c语言中的一些计算规则都是一样的,在3.6版本中一些规则得到了优化

>>> 2**38>>> 3/50.6>>> 3%63>>> 9/33.0#自动为3.0并不是3

长整型

Python能处理很大的数值

>>> 1235659678952135889598*6658975512123556982282275434607289883157386830734711262

八进制和十六进制

>>> 0o108>>> 0xff255

变量

很神奇python不用声明,直接就可以使用

>>> a,b=1,2>>> a+b3>>> type(a)<class 'int'>

最常用语句

用户输入和打印

>>> a=input("please input a:")please input a:5>>> print(a)5

在3.0的版本中print()是一个函数,因此要加括号,还有一个比较神奇的是打印加一个“,”可以避免换行

>>> print(a,b,)5 2#在.py中可以看到

if语句

>>> if b==2:print("hello world!")...hello world!>>> b=input("please input b:")please input b:3>>> if b==2:print("hello world!")...

模块

python中很重要的是模块
理解模块可以以这样的:相当于在原有的基础上加上扩展功能,需要用特殊命令import导入模块

>>> import math>>> math.floor(12.3)12

平方根

>>> from math import sqrt>>> sqrt(9)3.0>>> sqrt(-9)Traceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: math domain error>>>

竟然还能计算虚数

>>> import cmath>>> cmath.sqrt(-1)1j>>> cmath.sqrt(-9)3j

保存执行程序

新建文本文档后缀名改为.py即可
双击运行
最简单的程序

print("hello world!")

执行程序还可以用CMD执行,cd到指定文件夹下输入文件名就可以执行了

C:\Users\xf\Desktop>text.pyThis program is being run by itself

注释

注释很简单
在注释行前加上#就可以了
但是多行注释整么办呢,python没有多行注释,但我们可以这样

#file name:hello# coding:utf-8if __name__=='__main__':    print('This program is being run by itself')else:    print('I am being imported from another module')if 0:    print ("hello")    print ("hello")    print ("hello")    print ("hello")    print ("hello")    print ("hello")print ("hello")print ("hello")print ("hello")

打印结果

C:\Users\xf\Desktop>text.pyThis program is being run by itselfhellohellohello

字符串

python很好用的是它能想到程序员需要的一切操作,并提供解决方法
我们需要把一串数转化为字符串在python中我们只需这样就可以了

>>>str(12.3)'12.3'

其他的一些不多说理解起来很简单如:

>>> a="qwertyu">>> b="tqweqiowdj">>> a+b'qwertyutqweqiowdj'

好用有时尚

转义字符

“\”直接使用就行

>>> 'let's go!'  File "<stdin>", line 1    'let's go!'         ^SyntaxError: invalid syntax>>> 'let\'s go!'"let's go!"

python的简单初学就写这么多了,还要加快点学习进度,学习太慢了

原创粉丝点击