Python Forum
Function for returning absolute numbers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Function for returning absolute numbers
#1
Hi, I am just beginning to learn python, this was an exercise I got from a resource online and tried to solve.

The code below is supposed to take an argument, check whether it is an integer or float in which case it should return the absolute value of the number, otherwise it returns a "Nope" string.

When I run the code below, I just get a "Nope" even when i input an integer or a float. I use the atom text editor and run it from windows powershell...


num = raw_input('Enter a number: ')

def distance_from_zero(num):
if type(num) == int or type(num) == float:
print abs(num)
else:
print 'Nope'

distance_from_zero(num)
Reply
#2
It run as expected here: Python 3.6. On 2.7 runs also.

sinstance(object, type or type tuple)

In your case isinstance(num, (int, float)) will return what you want

Repost your code in code tags so we can see the proper indentation
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
raw_input() always returns a string.  So your type checking will always fail, since a string is never an int or a float.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Random Generator: From Word to Numbers, from Numbers to n possibles Words Yamiyozx 2 1,427 Jan-02-2023, 05:08 PM
Last Post: deanhystad
  Convert list of numbers to string of numbers kam_uk 5 3,013 Nov-21-2020, 03:10 PM
Last Post: deanhystad
  Can anyone spot why this function is returning an empty list? hhydration 2 1,856 Nov-18-2020, 06:16 AM
Last Post: deanhystad
  HELP - Returning self numbers lower or equal to my argument Kokuzuma 4 2,735 Nov-01-2018, 06:35 PM
Last Post: Kokuzuma
  Why is this function returning none? wlsa 2 5,809 Sep-30-2018, 01:36 PM
Last Post: gruntfutuk
  Regular Expressions in Files (find all phone numbers and credit card numbers) Amirsalar 2 4,111 Dec-05-2017, 09:48 AM
Last Post: DeaD_EyE
  Function not returning correct value TsG009 4 4,140 Nov-24-2017, 09:07 PM
Last Post: sparkz_alot
  PyCharm Tutorial Links/Videos For Absolute Beginner? pyJim 3 5,238 Jan-24-2017, 10:40 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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