How to call the same user input in different location in a print()

Viewed 175

I am a beginner in python and i just want to get a number as user input and print the cube of it using a single line code. so i tried following line and it is asking for the number twice. is there any method to access the user input in different location in print()?

print("The cube of ", input("Please enter a Number"), "is", pow(int(input("Please enter a Number")), 3))
6 Answers

You can do like below:

print ((lambda x: x ** 3)(int(input("Please enter a Number"))))

If you don't assign input() value to a variable, you cannot retrieve it again.

Python 3.8

You can assign variables inside print statement.

print("The cube of " + (a := input("Please enter a Number")) + " is " + pow(a, 3))

Python < 3.8

You cannot do this in one statement only. Or maybe something like this:

print('{}\nThe cube of {} is {}'.format(exec('a=int(input("Please enter a Number"))'), a, pow(a, 3)))

You could assign the input value to a variable like this:

def main():

    enteredNumber = input("Please enter a Number")
    print("The cube of ", enteredNumber, "is", pow(int(enteredNumber), 2)) 


if __name__== "__main__":
  main()

You are getting the input prompt twice since you are using 'input' keyword twice.

The solution for that is, by getting input from user first and then printing cube:

num = int(input("Please enter a Number: "))
print("The cube of ", num, "is ", pow(num, 3))

This might come in handy for simple cases. But there are a lot more ways to get the desired output which helps a lot in complex cases.

Using % Formatting

print("The cube of %d is %d" %(num, pow(num, 3)))

Using str.format

print("The cube of {} is {}".format(num, pow(num,3)))

Using f-strings

print(f"The cube of {num} is {pow(num,3)}")

All the above methods will give you the same result. You can read more about them in a simpler way here.

If you really want to do this in a single line of code, you can use a lambda function with f-strings to achieve it like this:

print((lambda num: f"The cube of {num} is {pow(num,3)}")(int(input("Please enter a Number: "))))

All the best in learning and mastering Python.

You can use assignment expressions to capture and pass-on the input:

print("The cube of ", (num := input("Please enter a Number")), "is", pow(int(num), 3))

Note that one would usually do that with multiple lines:

num = input("Please enter a Number")
print("The cube of ", num, "is", pow(int(num), 3))

Since you are insisting on "single" line of code, my following suggestion is somewhat close. This will work on Python 3.x

print(list(map(lambda x:x**3,[x for x in [int(input())]])))

Ideally you should split this into two lines.

Edit inspired by Vijesh's answer

Vijesh, in this post, has given a very succinct answer to accomplish the same. Below is the same code but omitting any use of variable name.

print((lambda _ : _**3)(int(input())))
Related