详解Python中的变量及其命名和打印

yipeiwu_com5年前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 "There are", cars, "cars available." 
print "There are only", drivers, "drivers available." 
print "There will be", cars_not_driven, "empty cars today." 
print "We can transport", carpool_capacity, "people today." 
print "We have", passengers, "to carpool today." 
print "We need to put about", average_passengers_per_car, "in each car." 


提示:下划线一般用在变量名中表示假想的空格。让变量名的可读性高一点。

运行结果:

root@he-desktop:~/mystuff# python ex4.py 
There are 100 cars available.
There are only 30 drivers available.
There will be 70 empty cars today.
We can transport 120.0 people today.
We have 90 to carpool today.
We need to put about 3 in each car.
root@he-desktop:~/mystuff# 


更多的变量和打印
现在我们输入更多的变量并打印他们,通常我们用""引住的叫字符串。

字符串是相当方便的,在练习中我们将学习怎么创建包含变量的字符串。有专门的方法将变量插入到字符串中,相当于告诉Python:“嘿,这是一个格式化字符串,把变量放进来吧。”

输入下面的程序:

# -- coding: utf-8 -- 
my_name = 'Zed A. Shaw' 
my_age = 35 # 没撒谎哦 
my_height = 74 # 英寸 
my_weight = 180 # 磅 
my_eyes = 'Blue' 
my_teeth = 'White' 
my_hair = 'Brown' 

  

print "let's talk about %s." % my_name 
print "He's %d inches tall." % my_height 
print "He's %d pounds heavy." % my_weight 
print "Actually that's not too heavy." 
print "He's got %s eyes and %s hair." % (my_eyes, my_hair) 
print "His teeth are usually %s depending on the coffee." % my_teeth 


# 下面这行比较复杂,尝试写对它。 
print "If I add %d, %d, and %d I get %d." % ( 
  my_age, my_height, my_weight, my_age + my_height + my_weight) 


提示:如果有编码问题,记得输入第一句。

运行结果:

root@he-desktop:~/mystuff# python ex5.py
let's talk about Zed A. Shaw.
He's 74 inches tall.
He's 180 pounds heavy.
Actually that's not too heavy.
He's got Blue eyes and Brown hair.
His teeth are usually White depending on the coffee.
If I add 35, 74, and 180 I get 289.
root@he-desktop:~/mystuff# 

相关文章

使用Python制作简单的小程序IP查看器功能

使用Python制作简单的小程序IP查看器功能

前言 说实话,查看电脑的IP,也挺无聊的,但是够简单,所以就从这里开始吧。IP地址在操作系统里就可以直接查看。但是除了IP地址,我们也想通过IP获取地理地址和网络运营商情况。IP地址和地...

python接口自动化测试之接口数据依赖的实现方法

在做自动化测试时,经常会对一整套业务流程进行一组接口上的测试,这时候接口之间经常会有数据依赖,那么具体要怎么实现这个依赖呢。 思路如下: 抽取之前接口的返回值存储到全局变量字典中...

详解Django的model查询操作与查询性能优化

1 如何 在做ORM查询时 查看SQl的执行情况 (1) 最底层的 django.db.connection 在 django shell 中使用  python manag...

Python装饰器实现几类验证功能做法实例

最近新需求来了,要给系统增加几个资源权限。尽量减少代码的改动和程序的复杂程度。所以还是使用装饰器比较科学 之前用了一些登录验证的现成装饰器模块。然后仿写一些用户管理部分的权限装饰器。 比...

python实现简易数码时钟

python实现简易数码时钟

最近迷上了Python,要说为什么呢?Python语法简单,功能强大,有广泛的第三方库能快速编程实现自己的想法(无需重复去造轮子)。就像某位前辈说的:“人生苦短,学会偷懒…”,配置好su...