How to define a variable inside the print function?

前端 未结 2 487
轮回少年
轮回少年 2021-01-24 03:28

I am a newbie in this field, and I am trying to solve a problem (not really sure if it is possible actually) where I want to print on the display some information plus some inpu

相关标签:
2条回答
  • 2021-01-24 04:12

    Starting from Python 3.8, this will become possible using an assignment expression:

    print("Your name is: " + (name := input("Tell me your name: ")))
    print("Your name is still: " + name)
    

    Though 'possible' is not the same as 'advisable'...


    But in Python <3.8: you can't. Instead, separate your code into two statements:

    name = input("Tell me your name: ")
    print("Your name is: " + name)
    

    If you often find yourself wanting to use two lines like this, you could make it into a function:

    def input_and_print(question):
      s = input("{} ".format(question))
      print("You entered: {}".format(s))
    
    input_and_print("What is your name?")
    

    Additionally you could have the function return the input s.

    0 讨论(0)
  • 2021-01-24 04:13

    no this is not possible. well except something like

     x=input("tell me:");print("blah %s"%(x,));
    

    but thats not really one line ... it just looks like it

    0 讨论(0)
提交回复
热议问题