Python输入输出问题:购票计算代码运行结果错误如何修复
Python电影票购票计算代码修正方案
错误原因梳理
- 类型不匹配:Python中
input()函数返回值默认是字符串类型,你获取的numTickets未做整数转换,直接和SINGLE_TICKET相乘时会触发字符串重复逻辑(比如输入2会得到2222222222的错误结果),而非你预期的数值乘法。 - 变量名不匹配:初始化时定义的电影名称变量为
movieNm,实际输入时你赋值给了新变量name,不符合题目要求的变量定义规则。 - 输出逻辑不符合要求:第四条打印语句需要输出提前定义好的总费用变量
totalTicketPrice,你写的是重复计算逻辑,不符合题目要求。
具体修改内容
- 购票数量输入行增加整数类型转换,改为
numTickets = int(input("Enter the number of tickets you wish to purchase:")) - 电影名称输入的赋值对象改为初始化定义的
movieNm,对应输出第一条语句也同步使用movieNm变量 - 总费用计算时转成float类型对齐初始化的变量类型,最后一条打印语句直接输出
totalTicketPrice
修正后完整代码
##a. 3 variables — ## The name of a movie ## The number of tickets to purchase ## The total cost of tickets purchased ## ##b. 1 Constant — ## The cost of a single ticket ##2. Create four print statements that will display the values of the variables and the constant along with labels that describe them ## #Initialize movieNm = str("") numTickets = int(0) totalTicketPrice = float(0.0) SINGLE_TICKET = int(10) #input movieNm = input("Enter the name of the movie you would like to see:") numTickets = int(input("Enter the number of tickets you wish to purchase:")) #process totalTicketPrice = float(SINGLE_TICKET * numTickets) #output print("Feature Film", movieNm) print("Cost of single ticket", SINGLE_TICKET) print("Number of Tickets purchased", numTickets) print("Your Total", totalTicketPrice)
内容的提问来源于stack exchange,提问作者vexxed
相关产品推荐
相关产品推荐

