Add two number and variable datatype is int8 - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Add two number and variable datatype is int8 (/thread-20296.html) |
Add two number and variable datatype is int8 - ift38375 - Aug-04-2019 Hi, Write a simple python program to add two numbers and variables datatype should be int8. How can I do this ? Actually by default variables take only 'int' here I am confused.and after getting your reply, I will put value in variable of int8 datatype to check range -128 to 127. Ex, val1 = 130 and error should be come due to out of range , I think. RE: Add two number and variable datatype is int8 - scidam - Aug-05-2019 Is it allowed for you to use NumPy? Numpy has int8 data type.
RE: Add two number and variable datatype is int8 - ift38375 - Aug-05-2019 (Aug-05-2019, 01:35 AM)scidam Wrote: Is it allowed for you to use NumPy? Numpy has how can we do it without numpy ? RE: Add two number and variable datatype is int8 - DeaD_EyE - Aug-05-2019 import numpy as np value_int8 = np.int8(127) value_uint8 = np.uint8(255)Or you make your own type in Python: class Int8(int): def __init__(self, value): if not -128 <= value <= 127: raise ValueError('-128 <= int8 <= 127')But this still allows to get bigger or smaller values than allowed, after a calculation. If there is a limit, just use if-statements to check if the value is in range. If you need to be flexible with size, you can make a validator closure (function in a function). def in_range(min_val, max_val): """ Closure to create a new function to check if the given value is in range. """ def check(value): # min_val and max_val is from the first call return min_val <= value <= max_val # <- this is the second call return check # <- returns the inner function, without calling it def in_range_exc(min_val, max_val): """ Closure to create a new function to check if the given value is in range. If not, a ValueError is raised. """ def check(value): if not min_val <= value <= max_val: raise ValueError(f'{min_val} <= {value} <= {max_val}') return check voltage_ok = in_range(-10, +10) current_ok = in_range(-0.02, +0.02) power_ok = in_range(10, 11) print(voltage_ok(0)) print(voltage_ok(1)) print(voltage_ok(10)) print(voltage_ok(-10)) print(voltage_ok(-10.00000000000000000000000001)) # < this is True, try to find out why print(voltage_ok(-10.001)) voltage_ok_exc = in_range_exc(5, 5.1) current_voltage = 5.10001 try: voltage_ok_exc(current_voltage) except ValueError: print(f'The voltage {current_voltage}V is not in range')Usually you need this data types (int8, int16 ...) if you want to interact with C. In this case ctypes is the right module for it. If you want to handle data over network/serial or in general binary data, you sould look for the struct and binascii module. |