Python基础语法--一些例子

本文深入浅出地介绍了Python的基础语法,包括整数除法、列表操作、字符串处理、元组使用、集合运算、字典操作等核心内容,并通过实例演示了输入输出、字符串格式化、列表推导式的用法,还探讨了异常处理及简单的类定义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


### Python 面向对象编程基础语法 #### 创建类与实例化对象 Python 是一门从设计之初就支持面向对象特性的语言,因此创建类和对象非常简单。定义一个新类型的语句即 `class` 关键字[^1]。 ```python class Dog: """A simple example class""" def __init__(self, name): # 构造函数 self.name = name def bark(self): return f"{self.name} says woof!" ``` 在此例子中,`Dog` 类有一个构造函数 `__init__()` 和一个名为 `bark` 的方法。当创建一个新的 `Dog` 对象时,会自动调用该构造函数来初始化对象属性[^2]。 #### 继承机制 子类可以继承父类的功能并扩展或修改其行为。这允许代码重用以及建立清晰的关系层次结构。 ```python class Animal: def speak(self): raise NotImplementedError("Subclasses must implement this method") class Cat(Animal): def speak(self): return "Meow" ``` 这里展示了如何让 `Cat` 类继承自 `Animal` 基础类,并实现了自己的版本的 `speak` 方法。 #### 不同类型的方法 在 Python 中有三种主要类型的方法:实例方法、类方法和静态方法。每种都有不同的用途: - **实例方法**: 接受第一个参数作为当前实例(`self`)。 - **类方法**: 使用装饰器 `@classmethod` 定义;接收的第一个参数是代表类本身的 `cls` 参数而不是具体的实例。 - **静态方法**: 利用 `@staticmethod` 装饰符声明;既不接受 `self` 也不接受 `cls` 参数,它们就像普通的函数一样工作,只是逻辑上属于某个特定类别[^3]。 ```python from datetime import date class Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def from_birth_year(cls, name, birthYear): return cls(name, date.today().year - birthYear) @staticmethod def is_adult(age): return age >= 18 ``` 在这个例子中,`Person.from_birth_year` 是一个类方法,它提供了一种替代的方式来构建 `Person` 实例。而 `is_adult` 则是一个静态方法,用于判断给定年龄是否成年。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值