码迷,mamicode.com
首页 > 编程语言 > 详细

python基础语法

时间:2015-08-20 12:45:05      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

1.输入输出循环判断

num=10
bingo=False
while bingo==False:         #False的写法要注意
     answer=input()
     if  answer<num:
           print too small
     if  answer>num:
           print too big
     if  answer==num:
           print BINGO
           bingo=True
for i in range(1,21):                  #从1循环到20
    print i                             #注意必须有首行缩进

格式化输出:

>>> num=18
>>> print My age is %d %num
My age is 18
>>> print Today is %s.%Friday
Today is Friday.
>>> print "%s ‘score is %f" %(Lily,90.2)
Lily score is 90.200000
>>> print "%s ‘score is %.2f" %(Lily,90.2)
Lily score is 90.20
for i in range(0,5):
    for j in range(0,i+1):
        print *,                 #要想在同一行输出,后面要打上逗号
    print                       #输出空时,会换行

 

2.主要记录一下与C语言不同的地方和特别需要注意的地方:

// 整除

** 乘方

整数没有长度限制,浮点数长度限制(小数点后16位)

复数: 

>>> 1j*1j
(-1+0j)

 

3.导入模块:

import

①import math     #导入math中所有函数 使用时要用 math.sqrt()的形式

②from math import *  #导入math中的所有函数, 可直接使用sqrt()

③from math import sqrt, tan  #只导入sqrt和tan两个函数 推荐使用

技术分享
>>> import math
>>> math.sqrt(5)
2.23606797749979
>>> math.sqrt(2)*math.tan(22)
0.012518132023611912
>>> from math import *
>>> log(25+5)
3.4011973816621555
>>> sqrt(4)*sqrt(100)
20.0
>>> from math import sqrt, tan
>>> tan(20)*sqrt(4)
4.474321888449484
技术分享

 

4.字符串: ‘ ’, “ ”, “““ ”””

len(): 求字符串长度 返回的是整形 不像C有个‘\0’ 返回的是字符串本身的长度

+:字符串拼接

*:多次拼接

技术分享
>>> len("""No No No""")
8
>>> "No"*10
‘NoNoNoNoNoNoNoNoNoNo‘
>>> "No"+‘ Yeah!‘
‘No Yeah!‘
>>> 
技术分享
>>> ‘‘‘
"What‘s your name?" I asked.
"I‘m Han Meimei."
‘‘‘
\n"What\‘s your name?" I asked.\n"I\‘m Han Meimei."\n
>>> ‘‘‘this is the same line‘‘‘
this is the same line
str=‘‘‘
"What‘s your name?" I asked.
"I‘m Han Meimei."
‘‘‘
print str

得到的结果:

"What‘s your name?" I asked.
"I‘m Han Meimei."

 

5.帮助:

dir():括号中是导入模块后的模块名,列出模块的所有函数

dir(__builtins__):查看Python内置函数清单

help():括号中是函数名,查看函数的文档字符串

print():打印函数文档字符串

如:print(math.tanh.__doc__)

      print(bin.__doc__)

 

6.类型转换:

float(): 把整数和字符串转换为浮点数

str(): 把整数和浮点数转换为字符串

int():把浮点数和字符串转换为整数 舍弃小数部分  字符串必须长得像整数 “123.5”是不可以的  int(‘325‘)是可以的

round(): 浮点数转整数 四舍六入五成双 不支持字符串

技术分享
>>> str(3.1415)
‘3.1415‘
>>> float(‘3‘)
3.0
>>> int("123")
123
>>> int("123.5")
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    int("123.5")
ValueError: invalid literal for int() with base 10: ‘123.5‘
>>> int(123.5)
123
>>> round("123"ArithmeticError)
SyntaxError: invalid syntax
>>> 
技术分享

 

7.多重赋值:

技术分享
>>> x,y,z=1,"r",1.414
>>> x
1
>>> y
‘r‘
>>> z
1.414
技术分享

交换变量的值

>>> y,x=x,y
>>> x
‘r‘
>>> y
1

 

8.random

from random import randint
i=randint(5,10)
print i

 

python基础语法

标签:

原文地址:http://www.cnblogs.com/wy1290939507/p/4744431.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!