简单计算
r=25
area=3.1415*r*r
print(area)
print("{:.2f}".format(area))
函数和while循环
def get_formatted_name(first_name,last_name):
full_name=first_name+' '+last_name
return full_name.title()
while True:
print("\nPlease tell me your name:")
f_name=input("First name: ")
l_name=input("Last name: ")
formatted_name=get_formatted_name(f_name,l_name)
print("\nHello,"+formatted_name+"!")
for循环和输入
#TempConvert_loop.py
for i in range(3):
val=input("请输入带温度表示符号的温度值(例如:32C):")
if val[-1] in ['C','c']:
f=1.8 * float(val[0:-1])+32
print("转换后的温度为:%.2fF"%f)
elif val[-1] in['F','f']:
c=(float(val[0:-1])-32)/1.8
print("转换后的温度为:%.2fC"%c)
else:
print("输入有误")
列表和字典
cars=['bnw','audi','toyota','subaru']
#cars.sort()
print(sorted(cars))
print(cars)
favorite_language={
'jen':'python',
'sarach':'c',
'edward':'ruby',
'phil':'python',
}
print("Sarah's favorite lanuage is "+
favorite_language['sarach'].title()+".")
类的示例
class Car():
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
def get_descriptive_name(self):
long_name=str(self.year)+' '+self.make+' '+self.model
return long_name.title()
my_new_car=Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())