zoukankan      html  css  js  c++  java
  • 习题 5:更多的变量和打印


      我们现在要键入更多的变量并且把它们打印出来。这次我们将使用一个叫 “格式化字符串”(format string)的东西。每一次你使用双引号(")把一些文本括起来,就创建了一个字符串。字符串是程序向人展示信息的方式。你可以打印它们,可以将它们存入文件,还可以将它们发送给 Web 服务器,很多事情都是通过字符串交流实现的。

      字符串是非常好用的东西,所以在这个习题中你将学会如何创建嵌入变量内容的字符串。要在字符串里嵌入变量,你需要使用 { } 特殊符号,把变量放到里边。你的字符串还必须以 f引号 } 的组合相当于告诉 Python:“ 嘿,这是一个格式化字符串,把这些变量放到那几个位置。”

      和之前一样,即使你读不懂这些内容,只要一字不差地录入就可以了。


     ex5.py

    # 我的名字 'Zed A. Shaw'
    my_name = 'Zed A. Shaw'
    # 我的年龄 35岁
    my_age = 35 # not alie(不真实,假的)
    # 我的身高 74英寸
    my_height = 74 # inches(英寸)
    # 我的体重 180磅
    my_weight = 180 # lbs(是英文pounds(磅) )
    # 我的眼睛 蓝色
    my_eyes = 'Blue'
    # 我的牙齿 白色
    my_teeth = 'white'
    # 我的头发 棕色
    my_hair = 'Brown'
    
    print(f"Let's talk about {my_name}.")
    print(f"He's {my_height} inches tall.")
    print(f"He's {my_weight} pounds heavy.")
    print("Actually that's not too heavy.")
    print(f"He's got {my_eyes} eyes and {my_hair} my_hair.")
    print(f"His teeth are usually {my_teeth} depending on the coffee.")
    
    # this line is tricky, try to get it exactly rigth
    total = my_age + my_height + my_weight
    print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")

     结果:

      巩固练习

    修改所有变量的名字,把他们前面的 my_ 去掉。确认每一个地方都改掉,不只是使用 = 设置的地方。

    # 名字 'Zed A. Shaw'
    name = 'Zed A. Shaw'
    # 年龄 35岁
    age = 35 # not alie(不真实,假的)
    # 身高 74英寸
    height = 74 # inches(英寸)
    # 体重 180磅
    weight = 180 # lbs(是英文pounds(磅) )
    # 眼睛 蓝色
    eyes = 'Blue'
    # 牙齿 白色
    teeth = 'white'
    # 头发 棕色
    hair = 'Brown'
    
    print(f"Let's talk about {name}.")
    print(f"He's {height} inches tall.")
    print(f"He's {weight} pounds heavy.")
    print("Actually that's not too heavy.")
    print(f"He's got {eyes} eyes and {hair} hair.")
    print(f"His teeth are usually {teeth} depending on the coffee.")
    
    # this line is tricky, try to get it exactly rigth
    # 总计=年龄+身高+体重
    total = age + height + weight
    # 如果我加上35、74和180,我得到289。
    print(f"If I add {age}, {height}, and {weight} I get {total}.")

     结果:

      常见问题

    • 变量名命名规则

    Python 需要使用标识符给变量命名,其实标识符就是用于给程序中变量、函数、类、方法命名的符号(简单来说,标识符就是合法的名字)。(注意不要与关键字重名 

    #导入keyword 模块
    import keyword
    #显示所有关键字
    keyword.kwlist

     Python 语言的标识符必须以字母、下画线(_)开头,后面可以跟任意数目的字母、数字和下画线(_)。此处的字母并不局限于 26 个英文字母,可以包含中文字符、日文字符等。(注意 Python 中的 标识符 是 区分大小写的,如:Andy !=  andy

    如:

    合法的:abc,abc_xyz,asd123

    不合法:1abc,asd#qaz

    • 如何将浮点数四舍五入

    可以使用 round( ) 函数,如round(17.333) 。

  • 相关阅读:
    2018.7.26笔记(变量的数据类型,if语句)
    id(),is 和 ==的区别,编码和解
    2018.7.31笔记(列表的基本操作)
    阅读与感悟如何高效学习
    说说设计模式 单例模式
    简单说说Java知识点 多线程
    阅读与感悟联盟
    阅读与感悟非暴力沟通
    简单说说Java知识点 HashMap
    MySQL知识树存储引擎
  • 原文地址:https://www.cnblogs.com/llr211/p/11439070.html
Copyright © 2011-2022 走看看