详解Python中的变量及其命名和打印
在程序中,变量就是一个名称,让我们更加方便记忆。
cars=100 space_in_a_car=4.0 drivers=30 passengers=90 cars_not_driven=cars-drivers cars_driven=drivers carpool_capacity=cars_driven*space_in_a_car average_passengers_per_car=passengers/cars_driven
print"Thereare",cars,"carsavailable." print"Thereareonly",drivers,"driversavailable." print"Therewillbe",cars_not_driven,"emptycarstoday." print"Wecantransport",carpool_capacity,"peopletoday." print"Wehave",passengers,"tocarpooltoday." print"Weneedtoputabout",average_passengers_per_car,"ineachcar."
提示:下划线一般用在变量名中表示假想的空格。让变量名的可读性高一点。
运行结果:
root@he-desktop:~/mystuff#pythonex4.py
Thereare100carsavailable. Thereareonly30driversavailable. Therewillbe70emptycarstoday. Wecantransport120.0peopletoday. Wehave90tocarpooltoday. Weneedtoputabout3ineachcar. root@he-desktop:~/mystuff#
更多的变量和打印
现在我们输入更多的变量并打印他们,通常我们用""引住的叫字符串。
字符串是相当方便的,在练习中我们将学习怎么创建包含变量的字符串。有专门的方法将变量插入到字符串中,相当于告诉Python:“嘿,这是一个格式化字符串,把变量放进来吧。”
输入下面的程序:
#--coding:utf-8-- my_name='ZedA.Shaw' my_age=35#没撒谎哦 my_height=74#英寸 my_weight=180#磅 my_eyes='Blue' my_teeth='White' my_hair='Brown'
print"let'stalkabout%s."%my_name print"He's%dinchestall."%my_height print"He's%dpoundsheavy."%my_weight print"Actuallythat'snottooheavy." print"He'sgot%seyesand%shair."%(my_eyes,my_hair) print"Histeethareusually%sdependingonthecoffee."%my_teeth
#下面这行比较复杂,尝试写对它。 print"IfIadd%d,%d,and%dIget%d."%( my_age,my_height,my_weight,my_age+my_height+my_weight)
提示:如果有编码问题,记得输入第一句。
运行结果:
root@he-desktop:~/mystuff#pythonex5.py
let'stalkaboutZedA.Shaw. He's74inchestall. He's180poundsheavy. Actuallythat'snottooheavy. He'sgotBlueeyesandBrownhair. HisteethareusuallyWhitedependingonthecoffee. IfIadd35,74,and180Iget289. root@he-desktop:~/mystuff#