Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help
#1
hello in my pyton home work i was asked to write a function  Which receives a real number (type float) called num and returns the number hop
Before and after a decimal point. for exemple 56.43 will retuen 43.56
the code I wrote is:
def parts(num):
    a=str(num)

    for i in range(len(a)):

        if a[i]=='.':

            return float(a[i+1:]+'.'+a[:i])

parts(343.4) 
and it didnt gave me back anything
can u please define my problem?         

Moderator zivoni: please use code tags for future posts
Reply
#2
you need to "show" the result, e.g. print it.

Please, next time use code tags when posting code snippet
Reply
#3
so I need to use print instead of return?
Reply
#4
No, return from function, but print when you call it e.g.:

def parts(num):
   a=str(num)
    for i in range(len(a)):
       if a[i]=='.':
           return float(a[i+1:]+'.'+a[:i])

print(parts(343.4)) # that is assuming python3
Reply
#5
great it worked
thank u!!!:)
Reply
#6
while your code does what it is expected to do (i.e. delivers the desired result) there are some issues with it.

using for i in range(len(a)): is not the accepted pythonic way to do it (i.e. we don't use range(len(a))). one should use enumerate instead
def parts(num):
   a = str(num)
   for i, n in enumerate(a):
       if n == '.':
           return float(a[i+1:]+'.'+a[:i])
and here is an alternative solution:
def parts(num):
   num_parts = str(num).split('.')
   num_parts.reverse()
   return '.'.join(num_parts)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020