【问题标题】:Admission Price based on age and coupons入场价格基于年龄和优惠券
【发布时间】:2017-02-21 16:51:25
【问题描述】:

我试图编写一个代码,如果提示用户输入今天的日期和他们的生日,以确定他们的年龄。年龄将决定他们的票价将是多少。如果他们 14 岁及以下,价格将是 5 美元。如果他们是 15 到 64 岁,价格将是 9 美元,如果他们是 65 岁及以上,价格将是 7.50。它会询问客户是否有优惠券,这会从他们的价格中扣除一美元。到目前为止我所拥有的:

print ("Hello, welcome to Hopper's Computer Museum! To determine your     enterance fee, please enter the following:")

print ('Your Date of Birth (mm dd yyyy)')
Date_of_Birth = input("--->")

print ('Todays Date: (mm dd yyyy)')
Todays_Date = input("--->")


age = (tYear-bYear)
if (bMonth > tMonth):
    age == age-1
if (bMonth == tMonth and
    bDay > tDay):
    age == age-1

if age < 14:
    price==5.00
elif age > 15 and age < 64:
    price==9.00
elif age > 65:
    price==7.50

print ('Do you have a coupon (y/n)?')
Discount = input("--->")
if Discount == "y" or Discount == "Y":
    price = price-1
elif Discount == "n" or Discount == "N":
    price = price

print ('Your admission fee is $4.00 enjoy your visit!')

我知道我需要定义变量,例如 tYear、bYear、bDay 等,但我不确定应该将它们分配给什么。

【问题讨论】:

  • 您应该使用 Danny W. Adair 在 Kumar 链接中的回答中的技术。要将 'mm dd yyyy' 格式的日期字符串转换为 date 对象,您可以执行 from datetime import datetime ... dob = datetime.strptime(dob_string, '%m %d %Y').date()
  • 你的年龄if 测试不太对。那应该是if age &lt;= 14:。此外,您可以在 Python 中链接比较,因此您可以执行elif 15 &lt; age &lt; 64: 之类的操作。最后一个elif 是多余的,只需将其设为else:。同样,在折扣测试中无需同时测试是和否的响应。

标签: python price


【解决方案1】:

您可以使用 map 将值分配给 tYear、bYear 等。您可以执行以下操作而不是 Date_of_birth = input('--->')

    bDay,bMonth,bYear = map(int,raw_input('--->').split())

如果输入格式为“dd mm yyyy”,这将根据要求分配 bDay、bMonth 和 bYear。同样,对于今天的日期,您可以这样写:

    tDay,tMonth,tYear = map(int,raw_input('--->').split())

替代选项是使用日期时间计算年龄。关注这个 - Age from birthdate in python

【讨论】:

  • 如果说“raw_input”没有定义怎么办?
  • 如果您使用的是 python 3.x,则使用 input()。 raw_input 在 python 3.x 中被重命名为 input()。 raw_input() 对 python 2.x 有效
猜你喜欢
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-19
  • 2013-12-18
  • 2019-04-19
相关资源
最近更新 更多