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

Python基础语法--一些例子

2017-06-02 17:51 489 查看
1.
>>> print(7//2)
3
>>> print(7/2)
3.5
>>> my_list=[1,2,3,4]
>>> A=my_list*3
>>> A
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
>>> my_list[2]=45
>>> A
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
>>> my_list = [1,2,3,4]
>>> A = [my_list]*3
>>> print(A)
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
>>> my_list[2]=45
>>> print(A)
[[1, 2, 45, 4], [1, 2, 45, 4], [1, 2, 45, 4]]
>>> A=[1,2,3,4]
>>> A.reverse()
>>> A
[4, 3, 2, 1]
>>> (54).__add__(21)
75


2.range

>>> range(10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5,10)
range(5, 10)
>>> list(range(5,10))
[5, 6, 7, 8, 9]
>>> list(range(5,10,2))
[5, 7, 9]
>>> list(range(10,1,-1))
[10, 9, 8, 7, 6, 5, 4, 3, 2]


3.strings

>>> "David"
'David'
>>> my_name="David"
>>> my_name[3]
'i'
>>> my_name*2
'DavidDavid'
>>> len(my_name)
5
>>> my_name
'David'
>>> my_name.upper()
'DAVID'
>>> my_name.center(10)
'  David   '
>>> my_name.find('v')
2
>>> my_name.split('v')
['Da', 'id']


4.strings的不可变性

>>> my_list
[1, 3, True, 6.5]
>>> my_list[0]=2**10
>>> my_list
[1024, 3, True, 6.5]
>>> my_name
'David'
>>> my_name[0]='X'
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
my_name[0]='X'
TypeError: 'str' object does not support item assignment


5.元组(同样具有不可变性)

>>> my_tuple = (2,True,4.96)
>>> my_tuple
(2, True, 4.96)
>>> len(my_tuple)
3
>>> my_tuple[0]
2
>>> my_tuple*3
(2, True, 4.96, 2, True, 4.96, 2, True, 4.96)
>>> my_tuple[0:2]
(2, True)
>>> my_tuple[1]=False
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
my_tuple[1]=False
TypeError: 'tuple' object does not support item assignment


6.set无序,不允许重复

>>> {3.6,3.6,"cat",4.5,False}
{3.6, False, 4.5, 'cat'}
>>> my_set={3.6,3.6,"cat",4.5,False}
>>> my_set
{3.6, False, 4.5, 'cat'}
>>> len(my_set)
4
>>> False in my_set
True
>>> "dog" in my_set
False
>>> your_set={3.6,100,99}
>>> my_set.union(your_set)
{False, 99, 4.5, 100, 3.6, 'cat'}
>>> my_set.intersection(your_set)
{3.6}
>>> my_set & your_set
{3.6}
>>> my_set.difference(your_set)
{False, 4.5, 'cat'}
>>> my_set - your_set
{False, 4.5, 'cat'}
>>> {3.6,100}.issubset(your_set)
True
>>> {3.6,100} <= your_set
True
>>> my_set.add("house")
>>> my_set
{False, 4.5, 3.6, 'house', 'cat'}
>>> my_set.remove(4.5)
>>> my_set
{False, 3.6, 'house', 'cat'}
>>> my_set.pop()
False
>>> my_set
{3.6, 'house', 'cat'}
>>> my_set.clear()
>>> my_set
set()


7.字典:

>>> capitals = {'Iowa':'DesMoines','Wisconsin':'Madison'}
>>> capitals
{'Iowa': 'DesMoines', 'Wisconsin': 'Madison'}
>>> print(capitals['Iowa'])
DesMoines
>>> capitals['Utah']='SaltLakeCity'
>>> print(capitals)
{'Iowa': 'DesMoines', 'Wisconsin': 'Madison', 'Utah': 'SaltLakeCity'}
>>> print(len(capitals))
3
>>> for k in capitals:
print(capitals[k]," is the captial of ",k)

DesMoines  is the captial of  Iowa
Madison  is the captial of  Wisconsin
SaltLakeCity  is the captial of  Utah
>>> del capitals['Utah']
>>> capitals
{'Iowa': 'DesMoines', 'Wisconsin': 'Madison'}


>>> phone_ext={'david':1410, 'brad':1137}
>>> phone_ext
{'david': 1410, 'brad': 1137}
>>> phone_ext.keys
<built-in method keys of dict object at 0x03EA7C90>
>>> phone_ext.keys()
dict_keys(['david', 'brad'])
>>> list(phone_ext.keys())
['david', 'brad']
>>> "brad" in phone_ext
True
>>> 1137 in phone_ext
False
>>> phone_ext.values()
dict_values([1410, 1137])
>>> list(phone_ext.values())
[1410, 1137]
>>> phone_ext.items()
dict_items([('david', 1410), ('brad', 1137)])
>>> list(phone_ext.items())
[('david', 1410), ('brad', 1137)]
>>> phone_ext.get("brad")
1137
>>> phone_ext.get("kent")
>>> phone_ext.get("kent","NO ENTRY")
'NO ENTRY'
>>> del phone_ext
>>> phone_ext
Traceback (most recent call last):
File "<pyshell#96>", line 1, in <module>
phone_ext
NameError: name 'phone_ext' is not defined
>>> phone_ext={'david':1410, 'brad':1137}
>>> del phone_ext["david"]
>>> phone_ext
{'brad': 1137}


8.input()

>>> user_name = input('Please enter your name: ')
Please enter your name: ZXM
>>> user_name
'ZXM'
user_radius = input("Please enter the radius of the circle ")
radius = float(user_radius)
diameter = 2 * radius


9.string format

>>> print("Hello","World", sep="***")
Hello***World
>>> print("Hello","World", end="***")
Hello World***
>>> print("Hello", end="***"); print("World")
Hello***World
>>> name="zxm"
>>> age=27
>>> print(name," is ",age," years old.")
zxm  is  27  years old.
>>> print("%s is %d years old." %(name,age))
zxm is 27 years old.
>>> price=24
>>> item="banana"
>>> print("The %s cost %d cents." %(item,price))
The banana cost 24 cents.
>>> print("The %+10s cost %5.2f cents." %(item,price))
The     banana cost 24.00 cents.
>>> item_dict={"item":"banana","cost:"24}
SyntaxError: invalid syntax
>>> item_dict={"item":"banana","cost":24}
>>> print("The %(item)s costs %(cost)7.1f cents"%item_dict)
The banana costs    24.0 cents
>>> print("The %+10s cost %10.2f cents." %(item,price))
The     banana cost      24.00 cents.
>>> price=214455667
>>> print("The %+10s cost %10.2f cents." %(item,price))
The     banana cost 214455667.00 cents.

10.

>>>[ch.upper() for ch in 'comprehension' if ch not in 'aeiou']
['C', 'M', 'P', 'R', 'H', 'N', 'S', 'N']


11.

>>> a_number = int(input("Please enter an integer "))
Please enter an integer -23
>>> import math
>>> try:
print(math.sqrt(a_number))
except:
print("Bad Value for square root")
print("Using absolute value instead")
print(math.sqrt(abs(a_number)))

Bad Value for square root
Using absolute value instead
4.795831523312719
>>>
>>> if a_number < 0:
raise RuntimeError("You can't use a negative number")
else:
print(math.sqrt(a_number))

Traceback (most recent call last):
File "<pyshell#145>", line 2, in <module>
raise RuntimeError("You can't use a negative number")
RuntimeError: You can't use a negative number


12.覆盖方法:

class Fraction:
def __init__(self,top,bottom):
self.num = top
self.den = bottom


def __str__ (self):
return str(self.num) + "/" + str(self.den)
>>> my_f = Fraction(3, 5)
>>> print(my_f)
3/5
>>> print("I ate", my_f, "of the pizza")
I ate 3/5 of the pizza
>>> my_f.__str__()
'3/5'
>>> str(my_f)
'3/5'
def __add__(self, other_fraction):
new_num = self.num*other_fraction.den +
self.den*other_fraction.num
new_den = self.den * other_fraction.den
return Fraction(new_num, new_den)
>>> f1 = Fraction(1, 4)
>>> f2 = Fraction(1, 2)
>>> f3 = f1 + f2
>>> print(f3)
6/8
>>>
def __eq__(self, other):
first_num = self.num * other.den
second_num = other.num * self.den
return first_num == second_num
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: