We help IT Professionals succeed at work.
Private
Troubleshooting Question

python script assistance

nav2567
nav2567 asked
on
26 Views
Last Modified: 2020-11-06
Hello,

I have written the below to find factorial of a number.  But the printing part is not great.  For example, instead of 3! is 6, I am getting 3 ! is 6 (with a space before !).  

May someone advise how I could fix this?  

Thanks

def factorial(n):
    total = 1
    for i in range(1, n+1):
        print(i)
        total = total * (i)
    return total

num = int(input("Please enter a number "))
print(num,"! is ",factorial(num))
Comment
Watch Question

Infrastructure Services
CERTIFIED EXPERT
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
NorieAnalyst Assistant
CERTIFIED EXPERT

Commented:
Try this.
def factorial(n):
    total = 1
    for i in range(1, n+1):
        print(i)
        total = total * (i)
    return total

num = int(input('Please enter a number '))
print(f'{num}! is {factorial(num)}')

Open in new window

Author

Commented:
Thanks All.  

Norie, would you explain what does print(f'{...}...{....}') do? 
nociSoftware Engineer
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
f'.....'  is a format string.
{xxx}   mean variable xxx should be inserted.
{yyy(xxx)}  means the return value of  function yyy with argument xxx should be printed.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions