详解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# 

相关文章

PyCharm 设置SciView工具窗口的方法

PyCharm 设置SciView工具窗口的方法

1、下载安装好PyCharm 专业版后打开或者新建一个Python项目,找到View导航栏, 如下图: 在Tool Windows下可以找到SciView按钮,但是每次打开PyChar...

学习python处理python编码问题

概括、从python1.6开始就可以处理unicode字符了。 一、几种常见的编码格式。 1.1、ascii,用1个字节表示。 1.2、UTF-8,用1个至三个字节表示,表示ascii码...

Python的Flask框架中实现登录用户的个人资料和头像的教程

Python的Flask框架中实现登录用户的个人资料和头像的教程

用户资料页面 在用户资料页面,基本上没有什么特别要强调和介绍的新概念。只需要创建一个含有HTML的新视图函数模板页面即可。 下面是视图函数(项目目录/views.py):  ...

使用Python3+PyQT5+Pyserial 实现简单的串口工具方法

使用Python3+PyQT5+Pyserial 实现简单的串口工具方法

练手项目,先上图 先实现一个简单的串口工具,为之后的上位机做准备 代码如下: github 下载地址 pyserial_demo.py import sys import seri...

python利用正则表达式排除集合中字符的功能示例

前言 我们在之前学习过通过集合枚举的功能,把所有需要出现的字符列出来,保存在集合里面,这样正则表达式就可以根据集合里的字符是否存在来判断是否匹配成功,如果在集合里,就匹配成功,否则不成功...