【问题标题】:How do I put a statement and input on the same line如何将语句和输入放在同一行
【发布时间】:2020-12-01 06:06:24
【问题描述】:

我是编码和学习基础知识的新手,我正在创建我的第一个项目,但我遇到了问题 我的代码是

name = input('what is your name? ')
print('hi ' + name)
yea =input('what is your birth year? ')
age = 2020 - int(yea)
print(age)

我希望输出是

你叫什么名字? 棕褐色 你的出生年份是? 2000 你20岁了

但我找不到一种方法来将“你是 --- 岁”与年龄相提并论

我的代码如何获得我需要的输出

【问题讨论】:

    标签: python


    【解决方案1】:

    使用 f 字符串

    print(f'You are {age} years old')
    

    或者普通的字符串连接:

    print('You are ' + str(age) + ' years old')
    

    注意:您只能将 + 字符串与其他字符串连接,这就是为什么需要 str(age) 的原因

    【讨论】:

      【解决方案2】:
      print("Your name is %s and your age is %d." %(name,int(age)))
      

      【讨论】:

      • 您不必将年龄转换为整数。它已经 int
      【解决方案3】:

      字符串格式

      旧版本:

      name = input('what is your name? ')
      print('hi ' + name)
      yea =input('what is your birth year? ')
      age = 2020 - int(yea)
      print('You are %d years old' % age)
      

      使用.format

      name = input('what is your name? ')
      print('hi ' + name)
      yea =input('what is your birth year? ')
      age = 2020 - int(yea)
      print('You are {0} years old'.format(age))
      

      升级 python 3.6 版:

      name = input('what is your name? ')
      print('hi ' + name)
      yea =input('what is your birth year? ')
      age = 2020 - int(yea)
      print(f'You are {age} years old')
      

      其他

      或将print(), 一起使用:

      name = input('what is your name? ')
      print('hi ' + name)
      yea =input('what is your birth year? ')
      age = 2020 - int(yea)
      print('You are', age 'years old')
      

      或将print()+ 一起使用:

      name = input('what is your name? ')
      print('hi ' + name)
      yea =input('what is your birth year? ')
      age = 2020 - int(yea)
      print('You are '+age+' years old')
      

      【讨论】:

        猜你喜欢
        • 2015-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-14
        • 2012-01-08
        • 1970-01-01
        • 1970-01-01
        • 2018-02-16
        相关资源
        最近更新 更多