Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print variable inputs with operators in python

My goal is to carry out the instructions below:

Enter integer:

4

You entered: 4

4 squared is 16

And 4 cubed is 64 !!

Enter another integer: 5

4 + 5 is 9

4 * 5 is 20

Here is my code:

user_num = int(input('Enter integer:\n'))
    
print("You entered: ", user_num)
    
print(user_num, "squared is ", user_num*user_num)
    
print("And", user_num, "cubed is", user_num*user_num*user_num, "!!")
    
user_num2 = int(input("Enter another integer:\n"))
    
print(str(user_num) + str(user_num2), "is", user_num+user_num2)
    
print(str(user_num) * str(user_num2), "is", user_num*user_num2)

The problem is that the last two lines of my codes are not giving me what I want. I want the inputs for user_num and user_num2 to be printed in a non-concatenated way and without execution to read, for example, "4 + 3 is 7" and "4 * 3 is 12". Any help will be greatly appreciated. Thanks

like image 403
Nii-Baah Amoo Avatar asked Jul 10 '26 11:07

Nii-Baah Amoo


2 Answers

Take advantage of f-strings so your print construction is easier to produce.

A corrected solution would look like the following:

user_num = int(input('Enter integer:\n'))

print(f"You entered: {user_num}")
print(f"{user_num} squared is {user_num**2}")
print(f"And {user_num} cubed is {user_num**3}!!")

user_num2 = int(input("Enter another integer:\n"))

print(f"{user_num} + {user_num2} is {user_num+user_num2}")
print(f"{user_num} * {user_num2} is {user_num*user_num2}")

like image 82
Anderson Monken Avatar answered Jul 14 '26 16:07

Anderson Monken


user_num = int(input('Enter integer:\n'))
print("You entered: ", user_num)
print(user_num, "squared is ", user_num*user_num)
print("And", user_num, "cubed is", user_num * user_num * user_num, "!!")
user_num2 = int(input("Enter another integer:\n"))
print(str(user_num), "+", str(user_num2), "is", user_num+user_num2)
print(str(user_num), "*", str(user_num2), "is", user_num*user_num2)

When you want to print the operators, you have to put them in quotation marks

like image 45
Christoph S. Avatar answered Jul 14 '26 15:07

Christoph S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!