通过例子学python(1)

第一章 基础知识

1.4 数字和表达式

# -*- coding: cp936 -*-
# 1.4 数字和表达式

# ** 表示幂(乘方)运算
print(2 ** 3)   #8
print(3 ** 3)   #27


#1.4.1  长整型数
print(999999999999999999999999999999999)

#1.4.2  十六进制和八进制
print(0x10, 010) #16 8

 

1.5 变量

#1.5 变量


#变量可以由数字、字母、下划线构成,但是首字母不能是数字

x5_5x5 = 100    #合法
_x55_x55 = 200  #合法
55xx = 300      #非法

 

1.7 获取用户输入

1.7 获取用户输入

x = input("x:")

y = input("y:")

print(x + y)

 

1.8 函数

1.8 函数

import math

#pow()幂函数
print(pow(3, 3))

#abs()绝对值函数
print(abs(-5))

#round()四舍五入函数
print(round(5.3), round(8.9))

#floor()向下取整
print(math.floor(5.3), math.floor(8.9))


#ceil()向上取整
print(math.ceil(5.3), math.ceil(8.9))


#sqrt()求开方
print(math.sqrt(9), math.sqrt(8.8))

 

1.9 模块

1.9 模块


#用import 导入了模块,然后按照“模块.函数”的格式使用这个模块的函数

import math
print(math.floor(5.99))


#from 模块 import 函数,便可以直接使用函数了
from math import sqrt
print(sqrt(9.9))


#1.9.1 cmath和复数

import cmath
print(cmath.sqrt(-4))

 

1.11 字符串
#1.11 字符串

#1.11.1 单引号字符串和转义引号
#转义符号,使用反斜杠对字符进行转义
print('let\'s go!');


#1.11.2 字符串的拼接
#同时写下两个字符串时可以自动拼接,必须要一个紧接着另一个
print("let's say " '"Hello"')

#使用加号进行拼接

print("hello " + "world")

x = "hello"
y = " python, i love you"
print( x + y)


#1.11.3 字符串表示 str和repr
#str函数:它会把值转换为合理形式的字符串,以便用户理解
#repr   :它会创建一个字符串,以合法的python表达式来表示值
print repr("hello, world!")
print repr(10000L)
print str("hello, wordld!")
print str(10000L)


#1.11.4 input 和 raw_input的比较
#input()假设输入的是合法的表达式,字符串需要加上双引号
#raw_input函数会把所有的输入当作原始数据,然后将其放入字符串中
#name = input("what is your name?")  #"zhangxin"
#print"Hello " + name + " !"

#name = raw_input("what is your name?") #zhangxin
#print "hello " + name + " !"

#1.11.5 长字符串、原始字符串和Unicode
# 长字符串 : 三个单(双)引号代替普通引号
#最后一个字符是反斜线,换行符本身被转义了
print '''we are chinese
you are a good man
she is a girl'''

print "we \
are"

#原始字符串:以r开头,则反斜线不再进行转义
print r"c:\n"

#Unicode 使用u前缀
print u"hello python"

 

posted on 2014-01-10 00:45  cv_ml_张欣男  阅读(610)  评论(1编辑  收藏  举报

导航