您的位置:首页 > 编程语言 > Python开发

Python入门(1):基础知识

2018-02-22 16:28 316 查看
懒癌患者说了一学期的要学python后终于开始学了...装的是python3.5...记录第一天学习过程...

0、保存及运行
文件名以.py结尾,运行程序按Ctrl+F5键。
1、输出print('Hello World!') #输出:Hello World!
print(2*2) #输出:4
print('2*2') #输出:2*2Remark: 下面默认注释#后面是运行结果。
2、变量
变量名可以包括字母、数字和下划线,不能以数字开头。
3、数字和表达式(整除//,取余%,幂**,长整数L,十六进制0x,八进制0o)x=1/2 #x=0.5
y=1.0/2.0 #y=0.5
z=1//2 #z=0
u=10%3 #u=1
v=-2**4 #v=-16
w=(-2)**4 #w=16
a=0xAF #a=175
b=0o10 #b=84、输入x=int(input('x:')) #x:2
y=int(input('y:')) #y:3
print(x*y) #6
name=input('What is your name? ')   #What is your name? Nina
print('Hello, '+name+'!')           #Hello, Nina!
5、if语句if 1==2: print('One equals two.')
if 1==1: print('One equals one.')Running results:One equals one.6、函数
pow(x,y[,z]):返回x的y次幂(所得结果对z取模),例如w=pow(-2,4)
abs():返回数的绝对值
round():把浮点数四舍五入为最接近的整数值
help():提供交互式帮助
int():将字符串和数字转换为整数
long():将字符串和数字转换为长整型数
7、模块
模块导入的两种方法:
方法一:用“import 模块”导入模块,然后按照“模块.函数()”的格式调用模块的函数,可使用变量来引用函数;
方法二:在确定自己不会导入多个同名函数(从不同模块导入)的情况下,用“from 模块 import 函数”命令,接着可直接调用函数,不需要模块名作为前缀。
简单例子:import math
a=math.floor(32.9) #a=32
b=math.ceil(32.9) #b=33
aroundup=math.ceil
c=aroundup(32.9) #c=33
from math import sqrt
r=sqrt(1) #r=1
import cmath
u=cmath.sqrt(1) #u=(1+0j)
v=cmath.sqrt(-1) #v=1j
w=(3+4j)*2j #w=(-8+6j)8、字符串
(1) 用单双引号输出字符串,没有区别。在特殊场合,可使用反斜线(\)对字符串中的引号进行转义。print("Let's go!") #Let's go!
print('Let\'s go!') #Let's go!
print('"Hello, world!"She said.') #"Hello, world!"She said.
print('\"Hello, world!\"She said.') #"Hello, world!"She said.(2) 拼接字符串print('Hello,''world!') #Hello,world!
print('Hello,'+'world!') #Hello,world!
x='Hello,'
y='world!'
print(x+y) #Hello,world!(3) 转换值为字符串的两种机制:
一种是通过str函数,把值转换为合理性是的字符串;
另一种是通过repr函数,其会创建一个字符串,以合法的Python表达式的形式来表示值。print(str("Hello, world!")) #Hello, world!
print(repr("Hello, world!")) #'Hello, world!'
print("The temperature is "+str(10)) #The temperature is 10
print("The temperature is "+repr(10)) #The temperature is 10Remark: print语句不能将字符串和数字进行相加。
(4) 长字符串、原始字符串和Unicode字符串
a. 如果需要写一个非常非常长的需要跨多行的字符串,可以使用三个单引号或三个双引号来代替普通引号。这时,可以在字符串中同时使用单双引号,不需要再使用反斜线进行转义。普通字符串也可跨行,只要一行的最后一个字符是反斜线。
b. 原始字符串以r开头,对反斜线不会特殊对待,似乎可以在原始字符串中放入任何字符。但仍然要像平常一样对引号进行转义,最后输出的字符串是包含转义所用的反斜线的。另外,不能在原始字符串结尾输入反斜线,因为如果最后一个字符是反斜线,Python就不清楚是否应该结束字符串,此种情形可把反斜线单独作为一个字符串来处理。print(r'Let\'s go!') #Let\'s go!
print(r'This is illegal''\\') #This is illegal\c. Unicode字符串使用u前缀,存储为16位Unicode字符。
Remark: 换行符可以写为\n,并可放于字符串中。例如,print('Hello, \nworld!')

以上。参考书是Magnus Lie Hetland著的《Python基础教程(第2版·修订版)》Chapter 1. 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 基础知识