【问题标题】:How to have integer subtract from a string in python?如何从python中的字符串中减去整数?
【发布时间】:2023-03-06 16:28:02
【问题描述】:

我目前正在从头开始开发一个聊天机器人,作为我对 Python 课程的介绍的作业。在我的作业中,我需要至少有一个“数学成分”。我似乎不知道如何让我的输入整数从字符串中减去。

附件是一个屏幕截图,我的目标是让他们输入他们每周在家做饭的天数并自动从 7 中减去。

print('Hello! What is your name? ')
my_name = input ()
print('Nice to meet you ' + my_name)
print('So, ' + my_name + ' What is your favorite veggie?')
favorite_veggie = input ()
print('Thats nuts! ' +favorite_veggie + ' is mine too!')
print('How many days a week do you have cook at home? ')
day = input ()
print('So what do you do the other ' + ????? 'days?')

【问题讨论】:

  • 执行input('Hello! What is your name? ')input('So, ' + my_name + ' What is your favorite veggie?')input('How many days a week do you have cook at home? ') 以获得更好的代码

标签: python string integer chatbot


【解决方案1】:

您可以将input 的结果转换为int,然后进行减法运算。 input("") 也接受一个字符串作为参数,它会显示在提示区域的前面,这样可以更好地编写代码

my_name = input('Hello! What is your name? ')
print('Nice to meet you ' + my_name)

favorite_veggie = input('So, ' + my_name + ' What is your favorite veggie?')
print('Thats nuts! ' + favorite_veggie + ' is mine too!')

day = int(input('How many days a week do you have cook at home? '))
non_work_day = 7 - day
what_do = input('So what do you do the other ' + str(non_work_day) + 'days?')

【讨论】:

    【解决方案2】:

    你正在寻找这个

    day = input()
    required_days = 7 - int(day)
    print('So what do you do the other ' + str(required_days) + ' days?')
    

    【讨论】:

      【解决方案3】:
      day = int(input())
      print('So what do you do the other', 7-day, 'days?')
      

      【讨论】:

        猜你喜欢
        • 2014-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-10
        • 1970-01-01
        • 2017-07-30
        • 2019-03-19
        • 1970-01-01
        相关资源
        最近更新 更多