文章目录
- 一、多行代码语句
- 二、Escape序列
- 三、字符串格式
- 四、数值运算
- 课后作业
一、多行代码语句
🥞使用反斜杠\来表示在下一行中继续使用一条语句。
subject_code = "CSCI111"
subject_mark = 80
subject_grade = "D"
result = "Subject result: " \
+ subject_code \
+ " mark " + str(subject_mark) \
+ " grade " + subject_grade
print(result)
🍗当语句在括号内时,行延续是自动的
subject_code = "CSCI111"
subject_mark = 80
subject_grade = "D"
print(
"Subject result: "
+ subject_code
+ " mark " + str(subject_mark)
+ " grade " + subject_grade
)
🍔有时,我们应该把一长串代码分解成多行代码,使它更清晰
二、Escape序列
我们如何为这个输出编写程序:
Thursday: “Inside Out”
print("Thursday: \"Inside Out\"")
转义序列含义
\:后间隙(\)
‘:单引号(’)
\“:双引号(”)
\n:新行
\t:选项卡
print("Your details:\n")
print("\tName: \"John Smith\"")
print("\tSN: \"2012345\"")
print("\nEnrolment record:\n")
print("\tMATH101")
print("\tCSCI201")
运行结果如下
Your details:
Name: "John Smith"
SN: "2012345"
Enrolment record:
MATH101
CSCI201
三、字符串格式
fname = "John"
lname = "Smith"
age = 20
gpa_score = 3.2
print("Hi {0} {1}!".format(fname, lname))
print("{1} {2} is {0} years old".format(age, fname, lname))
print("His GPA score is {0:.2f}".format(gpa_score))
带对齐的字符串格式
{0:<15} —— 左对齐,使用15个空格
{1:<10} —— 左对齐,使用10个空格
{2: ^25} —— 中心对齐,使用25个空间
{3:>15} —— 右对齐,使用15个空格
print("{0} x {1} = {2}".format(1, 5, 1*5))
print("{0} x {1} = {2}".format(2, 5, 2*5))
print("{0} x {1} = {2}".format(3, 5, 3*5))
print("{0} x {1} = {2}".format(4, 5, 4*5))
print("{0} x {1} = {2}".format(5, 5, 5*5))
print("{0} x {1} = {2}".format(6, 5, 6*5))
print("{0} x {1} = {2}".format(7, 5, 7*5))
print("{0} x {1} = {2}".format(8, 5, 8*5))
print("{0} x {1} = {2}".format(9, 5, 9*5))
print("{0} x {1} = {2}".format(10, 5, 10*5))
print("{0:>2} x {1:>1} = {2:>2}".format(1, 5, 1*5))
print("{0:>2} x {1:>1} = {2:>2}".format(2, 5, 2*5))
print("{0:>2} x {1:>1} = {2:>2}".format(3, 5, 3*5))
print("{0:>2} x {1:>1} = {2:>2}".format(4, 5, 4*5))
print("{0:>2} x {1:>1} = {2:>2}".format(5, 5, 5*5))
print("{0:>2} x {1:>1} = {2:>2}".format(6, 5, 6*5))
print("{0:>2} x {1:>1} = {2:>2}".format(7, 5, 7*5))
print("{0:>2} x {1:>1} = {2:>2}".format(8, 5, 8*5))
print("{0:>2} x {1:>1} = {2:>2}".format(9, 5, 9*5))
print("{0:>2} x {1:>1} = {2:>2}".format(10, 5, 10*5))
四、数值运算
算术运算符
课后作业
一家商店出售的产品售价为10美元,但折扣是3件商品只需要20美元。编写一个程序,要求用户输入他们想要购买的物品的数量。然后,该程序将显示成本。
item_price = 10 # 商品单价
discount_quantity = 3 # 折扣适用的商品数量
discount_price = 20 # 折扣后的价格
# 用户输入购买的物品数量
quantity = int(input("请输入您想购买的物品数量:"))
# 计算总成本
if quantity < discount_quantity:
cost = item_price * quantity # 不满足折扣条件,按单价计算成本
else:
# 计算折扣后的商品数量和单价
discounted_quantity = quantity // discount_quantity * discount_quantity
remaining_quantity = quantity % discount_quantity
cost = (discounted_quantity / discount_quantity * discount_price) + (remaining_quantity * item_price)
# 显示成本
print("购买", quantity, "件商品的成本为", cost, "美元。")