《笨方法学python》--习题5

本文通过一个Python编程实例,展示了如何定义和使用变量,以及如何使用格式化字符串进行打印输出。涉及变量定义、数学运算和字符串格式化。

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

习题5 更多的变量和打印

#!usr/bin/python
#--coding:utf-8--

name = 'Zed A. Shaw'
age = 35 #not a lie
height = 74 #inches
weight = 180 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'

print "Let's talk about %s." % name
print "He's %d inches tall." % height
print "He's %d pounds heavy." % weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." %(eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth

#this is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." %(age, height, weight, age + height + weight)

运行结果:

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.

其他:

  1. 格式化字符串(format string):
    %d 输出十进制有符号整数
    %u 输出十进制无符号整数
    %o 输出八进制无符号整数
    %x 输出十六进制无符号整数
    %f 输出小数点形式的浮点数
    %e 输出科学计数法形式的浮点数
    %g 输出浮点数(根据数值大小决定输出形式)
    %s 输出字符串
    %r 不管什么都打印出来
    %% 百分号标记,输出一个百分号
    %c 输出字符及其ASCII码
    %p 用于指针,用十六进制打印数值的内存地址
    %n 存储输出字符的数量放进参数列表的下一个变量中
  2. 将字符串定义为变量时,字符串要用单引号引起来;
    变量名下划线后不能有空格;
    变量可进行数学运算;
    多个变量可以同时输出;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值