views:

54

answers:

3

Let's say there is a parameter n. Can n be any numbers? For example, question like this: Given a non-negative number num, return True if num is within 2 of a multiple of 10. This is what I am thinking:

def near_ten(num):
    n = int #So I assume n can be any integer
    if abs(num - n*10) <=2:
        return True
    Return False

However, there are two problems. First, in n*10, * is a unsupported operand type cuz I thought I could use Python as a calculator. 2nd, I cannot just simply say n = int, then n can be viewed as a variable as any number (or integer) in a math function. If there is a way that I could use n in that way, then life would be so much easier.

Finally I figure it out in another way which doesn't include "n" as a parameter:

def near_ten(num):

if num%10<=2:
    return True
if (num+2)%10<=2:
    return True
return False

However, I'm still curious about "n" as a parameter mentioned before. Since I'm just a starter, so this is really confusing.

+1  A: 

In Python, int is a type. Types are first-class objects in Python, and can be bound to names. Of course, trying to multiply a type by a number is usually meaningless, so the operation is not defined by default. It can be referred to by the new name though.

n = int
print(n(3.4))
print(n('10') == 10)
Ignacio Vazquez-Abrams
A: 

i am not sure if you have ran your code or not, but python is a high level interpreted language, python CAN distinguish between variable types and therefore you do not need to explicitly declare them, your function header is valid. you can also do operations between integers and floats/doubles without the need of casting, python already handles that for you

your function will raise an error in any compiler, ur n variable is declared, you have defined it, but you have not initialized it

NetSkay
No, `n` is initialized to `int`.
Matthew Flaschen
even so, the object has no stored value, therefore he cannot do operations on that objects, its an empty object; itd call that a declaration; for example in C++ doing int x; defines the objects, but only when you do x = (integer value); then the object becomes initialized because now it holds a space in memory... correct me if my understanding is wrong
NetSkay
Yes, the object has a stored value. That value is the type `int`, which is an object in Python.
kindall
ohhh ok, so it defaults to NULL
NetSkay
No, the value is not NULL (or rather `None`); it's the type `int`.
Matthew Flaschen
ok, thank you for the clarification :)
NetSkay
A: 

Here is a much simpler solution:

def near_mult_ten(num):
    return abs(num - (num+5) // 10 * 10) <= 2

Edit: Fixed.

kindall
No, that will return False for 9.
Matthew Flaschen
You're right. Believe it or not, I realized that just before I fell asleep last night. Fixed it.
kindall