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

Python基础教程 第1章: 基础知识 学习笔记

2015-12-15 16:56 1161 查看
Python除法,一个整数被另一个整数除,计算结果的小数部分会被截除,只留下整数部分,如果参与除法的两个数中有一个为浮点数,运算结果亦为浮点数:

>>> 1 / 2
0
>>> 1.0 / 2
0.5
>>> 1 / 2.0
0.5
>>> 1.0 / 2.0
0.5


如果希望Python只执行普通的除法,可以加上:

>>> from __future__ import division
>>> 1 / 2
0.5


乘法也一样,如果参与乘法的两个数中有一个为浮点数,运算结果亦为浮点数。

跟Perl一样,Python也有乘幂运算符:

>>> 2 ** 3
8


Python中长整数和普通整数一样,但结尾需要加L,大小写l都可以,为了l和1区分,建议使用大写L。

>>> 1000000000000000000
1000000000000000000L
>>> 10000000000
10000000000L
>>> 1000000
1000000


Python中的变量赋值语句跟其他语言都一样,第一章暂时没有好整理的。

获取用户输入:

x = input("Please Input: ")
print x


使用input接收用户输入,默认接收数字输入,如果需要输入字符串,需要使用“”包含,否则报错:


>>> ================================ RESTART ================================
>>>
Please Input: 2
2
>>> ================================ RESTART ================================
>>>
Please Input: hello

Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\hello.py", line 1, in <module>
x = input("Please Input: ")
File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
>>> ================================ RESTART ================================
>>>
Please Input: "hello"
hello


如果不想输入字符串的时间不想加""号,可以使用raw_input接收用户的输入:

x = raw_input("Please Input: ")
print x



Please Input: 2
2
>>> ================================ RESTART ================================
>>>
Please Input: hello
hello
>>> ================================ RESTART ================================
>>>
Please Input: "hello"
"hello"


Python函数调用跟其他语言也一样:

print abs(-4)
print pow(2, 3)


模块:

#导入模块
import math

#调用模块中的函数
print math.floor(32.9)

'''
这里是块注释
块注释
注释
'''

#这种导入方法,如果不加模块名,会报错
#print sqrt(9)

#如果不希望报错,可以使用这种导入方法
from math import sqrt
print sqrt(9)


Python中的注释:


行注释使用: #开头

块注释使用:

'''

code

'''


Python中字符串:

#字符串使用'号或"号都可以
str1 = 'hello'
str2 = "hello"

#字符串的拼接
str3 = str1 + str2
str4 = 'hello' 'world'

#数字转换成字符串
#print "hello" + 2    这样写会报错

'''
str函数会把数值转换为合理形式的字符串
repr函数会创建一个字符串,以合法的Python表达式的形式来表示数值
'''
print "hello" + str(2)
print "hello" + repr(3)
print 'hello' + `4`



hello2
hello3
hello4



#长字符串
str = '''abcdefg123123
qwertyuiop123
355ghbbbffff
3322134444'''
print str

#原始字符串,前缀加r
path = 'c:\nfc'
print path
path = r'c:\nfc'
print path
path = r'c:\nfc' '\\'
print path

#Unicode字符串,前缀加u
str1 = u'Hello World'
print str1



>>>
abcdefg123123
qwertyuiop123
355ghbbbffff
3322134444
c:
fc
c:\nfc
c:\nfc\
Hello World

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: