您的位置:首页 > 编程语言 > Python开发

《Python编程-从入门到实践》第2章习题选练

2018-03-08 12:34 831 查看
本章主要学习的知识:
1. 字符串类型及其常用操作
2. 整数和浮点数的常用运算
3. 注释的使用

以下是课后练习:
2-2. Simple Messages: Store a message in a variable, and print that message. Then change the value of your variable to a new message, and print the new message.
知识点分析:print函数的使用、变量及其修改
代码:#March 8th, 2018
#By Zachary

message = "Zack"
print(message)
message = "Zachary"
print(message)

2-3. Personal Message: Store a person’s name in a variable, and print a message to that person. Your message should be simple, such as, “Hello Eric, would you like to learn some Python today?”
知识点分析:字符串类型变量的连接(+)运算
代码:#March 8th, 2018
#By Zachary

name = "Zachary"
print("Hello "+name+", would you like to learn some Python today?")
2-4. Name Cases: Store a person’s name in a variable, and then print that person’s name in lowercase, uppercase, and titlecase.知识点分析:字符串的大小写转换方法:
    title(): 将字符串中每个单词的首字母改成大写
    upper(): 将字符串中的所有字母都改为大写
    lower():将字符串中的所有字母都改为大写

代码:#March 8th, 2018
#By Zachary

name = "Zachary lei" #just designed to test the functions
print(name.lower())
print(name.upper())
print(name.title())

2-5&2-6 Famous Quote: Find a quote from a famous person you admire. Print the quote and the name of its author. Your output should look something like the following, including the quotation marks:
Albert Einstein once said, “A person who never made a mistake never tried anything new.”
store the famous person’s name in a variable called famous_person. Then compose your message and store it in a new variable called message. Print your message.
知识点分析:
Python,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号,这种灵活性让你能够在字符串中包含双引号和单引号。
代码:#March 8th, 2018
#By Zachary

famous_person = "J.Ruskin"
message = "Living without an aim is like sailing without a compass."
print(famous_person+' once said, "'+message+'"')
2-7. Stripping Names: Store a person’s name, and include some whitespace characters at the beginning and end of the name. Make sure you use each character combination, "\t" and "\n", at least once. Print the name once, so the whitespace around the name is displayed. Then print the name using each of the three stripping functions, lstrip(), rstrip(), and strip().
知识点分析:字符串前后空白
    lstrip(): 删除字符串前面的空白字符
    rstrip(): 删除字符串后面的空白字符
    strip(): 删除字符串前后的空白字符
    空白字符除了空格外,也包含换行符制表符等

代码:#March 8th, 2018
#By Zachary

name = "\n\tZachary Lei \n"
print(name)
print(name.lstrip())
print(name.rstrip())
print(name.strip())2-9. Favorite Number: Store your favorite number in a variable. Then, using that variable, create a message that reveals your favorite number. Print that message.
知识点分析:强制类型转换
代码:#March 8th, 2018
#By Zachary

number = 0
message = "My favourite number is " + str(number)
print(message)

Reference: 中山大学林瀚老师《高级编程技术》课件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python