X variable wasn't updated when you converted it to int. It should be x = int(x).

import time
x = 0

while True:
    print("")
    x = input("Please give a value for X.")
    try:
        x = int(x)
    except:
        print("")
        print("Sorry, please use an integer and try again!")
        time.sleep(1)
    else:
        x = int(x)
        break

print(abs(x))
Answer from 0x0FFF on Stack Overflow
Discussions

TypeError: bad operand type for abs(): 'NoneType' python error - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... Both f(x) or fp(x) aren't "NoneType" but however it's telling me that abs can't operate "NoneType". What seems to be the problem? abs(fp(x)) TypeError: bad operand type for ... More on stackoverflow.com
🌐 stackoverflow.com
TypeError: bad operand type for abs(): 'str'
sample.zip I'm running NIPT samples then suddenly I found this error occurred in some samples [INFO - 2021-04-29 10:19:51]: Starting CNA prediction [INFO - 2021-04-29 10:19:51]: Importing data ... More on github.com
🌐 github.com
2
August 6, 2020
python - Applying function to pandas columns yields error "bad operand type for abs(): 'str'" - Stack Overflow
1 Why builtin function abs() don't work with Python lists, but works correctly with NumPy arrays and pandas series (as it would be vectorized)? 0 Variable comes up as a string; TypeError: bad operand type for abs(): 'str' More on stackoverflow.com
🌐 stackoverflow.com
python - bad operand type for abs(): 'list' - Stack Overflow
When calculating the absolute value in each value of an array, I am getting an error related to bad operand type for abs(): 'list'. The part of source code which is failing is the next: x = amplit... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Pytut
pytut.com › abs
Python abs() Function - PyTut
The argument can't be a str, tuple, list, set, or dict. These raise TypeError. >>> abs('-3.5') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: bad operand type for abs(): 'str' >>> abs((1, -1)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ...
🌐
Python Examples
pythonexamples.org › python-absolute-value-abs
abs() - Python Examples
If we provide an argument of any non-numeric type like string, abs() function raises TypeError. x = 'hello' absVal = abs(x) print(f'Absolute value of {x} is {absVal}.') Traceback (most recent call last): File "example1.py", line 2, in <module> absVal = abs(x) TypeError: bad operand type for ...
🌐
GitHub
github.com › CenterForMedicalGeneticsGhent › WisecondorX › issues › 79
TypeError: bad operand type for abs(): 'str' · Issue #79 · CenterForMedicalGeneticsGhent/WisecondorX
August 6, 2020 - sample.zip I'm running NIPT samples then suddenly I found this error occurred in some samples [INFO - 2021-04-29 10:19:51]: Starting CNA prediction [INFO - 2021-04-29 10:19:51]: Importing data ... [INFO - 2021-04-29 10:19:51]: Normalizin...
Published   Apr 29, 2021
Find elsewhere
🌐
GitHub
github.com › HIPS › autograd › issues › 102
TypeError: bad operand type for abs(): 'FloatNode' · Issue #102 · HIPS/autograd
April 28, 2016 - def predict(self, theta, data): const = assert_arr_shape({ data.X.shape: ('batch_size', self.n_steps, self.n_input_dim), data.y.shape: ('batch_size', self.n_hidden_dim) }) h_prev = bk.repeat(theta.h_0[:, bk.newaxis], const.batch_size, axis=1).T activation = lambda x: bk.maximum(0, 1-x) to_stack = [] for i in range(self.n_steps): input2hidden = bk.dot(data.X[:, i, :], theta.W_input_to_hidden) hidden2hidden = bk.dot(h_prev, theta.W_hidden_to_hidden) before_activation = (input2hidden + hidden2hidden) h_prev = activation(before_activation) to_stack.append(h_prev) output = bk.stack(to_stack, axis=1) assert_arr_shape({output.shape: (None, self.n_steps, self.n_hidden_dim)}) return output def loss(self, theta, data): pred = self.predict(theta, data) last_step_pred = pred[:, -1, :] loss = bk.sum(bk.abs(last_step_pred - data.y)) return loss
Top answer
1 of 1
1

I don't recommend you use apply here

Use GroupBy.idxmax + DataFrame.replace

max_df = df.abs().groupby(np.arange(len(df)) // n).idxmax().replace(df)
print(max_df)

Output

           A          B          C          D
0  95.483784  72.261024  90.289008 -99.557204
1  92.303663 -92.933734  98.741863 -73.221129
2 -94.858459  91.925163  90.394739  94.129047
3  85.727608  96.168424  69.747412  74.943672

print(df)
 # df = pd.read_clipboard() # read

            A          B          C          D
0  -49.710250 -44.714960  90.289008  78.021054
1   15.779849  72.261024 -80.564941 -99.557204
2  -25.535893  44.418568  -3.654055  -4.656012
3   -1.792691  52.828214 -24.383645  54.337480
4   95.483784 -33.604944  60.210426 -68.157859
5   85.614669 -88.756766  14.634241 -73.221129
6   -1.461207  41.078068  98.741863   0.152652
7   92.303663 -77.230608  63.205845 -45.439176
8   36.255957 -92.933734  -8.668916  24.251590
9   15.387012 -17.044411 -84.098159  53.797730
10 -15.277586  91.925163  90.394739  94.129047
11 -94.858459  19.069534  62.672051  10.852176
12 -48.550836  59.084142 -22.185758 -58.797477
13 -16.430060 -26.718411 -23.169127  90.198812
14  14.495206  14.054623 -59.593696  35.043442
15  21.148221  16.673029  42.788121 -23.932640
16  74.617433 -53.114081  69.747412  74.943672
17  85.727608  96.168424  41.474511   7.672894
18  -9.282754  -0.151546  -8.765613 -26.973899
19 -39.272002  85.819052  21.355006  67.018427

The problem is that Groupby.apply apply the function to each daframe, then max receives a dataframearg... We could check it with:

def absmax(x):
    print('This is a DataFrame arg: \n', x)
    return x.apply(lambda y: max(y, key=abs))

df_max = df.groupby(np.arange(len(df))//n).apply(absmax)

This is a DataFrame arg: 
            A          B          C          D
0  23.080753  89.918599 -62.273324   0.674636
1 -61.096176  68.840583  20.359616 -82.110220
2 -86.942716  97.269852  57.320944  84.340152
3  36.632979  53.376849  95.817563  39.398515
4 -36.960907 -12.796490 -79.833804  32.708664
This is a DataFrame arg: 
            A          B          C          D
5  24.360600 -49.486819 -65.995965 -93.884078
6 -46.623600 -57.999896 -86.946372  -0.250644
7 -35.103092  61.971385  86.165203 -32.619381
8  50.155064 -38.999355  98.856747 -56.195841
9 -92.646512  94.217864 -86.628196 -55.859978
This is a DataFrame arg: 
             A          B          C          D
10 -55.846413  34.281246 -90.523268  71.148029
11  22.753896 -33.659637  74.225409  24.498337
12 -52.384172  16.169118 -10.788839 -99.874961
13  49.235215 -74.372901  11.509361 -43.676953
14  67.255287 -84.477123  12.725054 -85.892184
This is a DataFrame arg: 
             A          B          C          D
15  72.522972 -13.079824  48.973703 -87.913843
16 -64.110924 -81.324560   7.067080  97.073997
17  87.319482  76.021534  80.780322 -90.320084
18 -84.848110  70.732111  34.160013  99.269365
19 -17.924337  12.191496  46.020178  30.532568
🌐
iO Flood
ioflood.com › blog › python-absolute-value
Python Absolute Value | abs() Function and Alternatives
February 6, 2024 - string = 'Hello, Python!' try: absolute_value = abs(string) except TypeError: print('TypeError: bad operand type for abs(): str') # Output: # TypeError: bad operand type for abs(): str · In this code block, we tried to find the absolute value of a string, which resulted in a TypeError.
🌐
GitHub
github.com › dirkjanm › ldapdomaindump › issues › 51
TypeError: bad operand type for abs(): 'str' · Issue #51 · dirkjanm/ldapdomaindump
April 20, 2022 - TypeError: bad operand type for abs(): 'str'#51 · Copy link · deni · opened · on Jan 11, 2023 · Issue body actions · I am experiencing a problem that seems similar to #27. Please see below: (venv) deni@NCCBook-Pro ldapdomaindump-0.9.4 % python ldapdomaindump.py 10.129.139.146 [*] Connecting as anonymous user, dumping will probably fail.
Published   Jan 11, 2023
🌐
GitHub
github.com › spiralgenetics › truvari › issues › 24
TypeError: bad operand type for abs(): 'NoneType' · Issue #24 · ACEnglish/truvari
May 1, 2018 - It bugged as below: Traceback (most recent call last): File "/usr/local/bin/truvari", line 1047, in run(sys.argv[1:]) File "/usr/local/bin/truvari", line 788, in run sizeA = get_vcf_entry_size(base_entry) File "/usr/local/bin/truvari", line 271, in get_vcf_entry_size size = abs(entry.INFO["SVLEN"]) TypeError: bad operand type for abs(): 'NoneType'
Author   Macy-Zhao
🌐
Mozilla Discourse
discourse.mozilla.org › t › synthetic-test-sentence-typeerror-bad-operand-type-for-abs-nonetype-error › 56559
Synthetic test sentence TypeError: bad operand type for abs(): 'NoneType' error - TTS (Text-to-Speech) - Mozilla Discourse
March 25, 2020 - I’m training with the LJSpeech dataset and after about the 50th epoch I get the following error when it tries to generate the test sentences. File "train.py", line 502, in evaluate ap.save_wav(wav, file_path) File "/home/username/Audio/TTS/tts_namespace/TTS/utils/audio.py", line 58, in save_wav wav_norm = wav * (32767 / max(0.01, np.max(np.abs(wav)))) TypeError: bad operand type for abs(): 'NoneType' Traceback (most recent call last): File "train.py", line 502, in evaluate ap.save_wav(wav, file...
🌐
Reddit
reddit.com › r/learnprogramming › checking the type of data
r/learnprogramming on Reddit: Checking the type of data
September 12, 2023 -

Hey guys. I'm currently learning Python and yesterday I ran into my first hurdle. This is the practice problem:

Create a function, called distance_from_zero(), that returns the absolute value of a provided single argument and prints a statement "Not possible" if the argument provided is not a number. To solve the task, use the type() function in the body of distance_from_zero(). Call the function with the values of -10 and "cat" to verify it works correctly.

Here is the code that I created:

def distance_from_zero(d):
if type(d) == float or int:
    return abs(d)
else:
    print("Not possible")

Whenever I input an integer or float to test the code, it works. However, when I test for strings, it does not print "Not possible" but instead throws an error. This is the error that it produces:

TypeError                                 Traceback (most recent call last)

Cell In[6], line 1 ----> 1 distance_from_zero("asd")

Cell In[2], line 3, in distance_from_zero(d) 1 def distance_from_zero(d): 2 if type(d) == float or int: ----> 3 return abs(d) 4 else: 5 print("Not possible")

TypeError: bad operand type for abs(): 'str'

In my understanding, the "if type(d) == float or int:" should produce a false boolean response which should cause it to print "Not possible", but instead, I'm getting an error. Hopefully someone can point out my mistake or where I understood incorrectly? Thank you in advance!

🌐
Invent with Python
inventwithpython.com › appendixd.html
IYOCGwP, Appendix D
This error occurs when the value of an argument you pass to a function or method is of the wrong data type. In the above example, the abs() function takes an integer or floating point number. Passing a string for the argument results in an error.
🌐
Checkio
py.checkio.org › forum › post › 13102 › bad-operand-type-for-abs-how-do-i-solve-this
'Bad operand type for abs', how do i solve this
'Bad operand type for abs', how do i solve this ?: def checkio(numbersarray: tuple) -> list: result = sorted([numbersarray], key=lambda x:abs(x)) return result · task.absolute-sorting · Created: March 3, 2019, 9:51 p.m. Updated: March 3, 2019, 11:02 p.m. 0 · 6 · matdibobe ·
🌐
Quora
quora.com › How-do-you-fix-the-TypeError-bad-operand-problem-in-Python-3
How to fix the TypeError: bad operand problem in Python 3 - Quora
Answer (1 of 2): Probably b is a string. Do print( type(b)) and Python will tell you its type. If it is a string representation of a number, you could do b = float(b), after that b is a float and unary minus will work on that. But if b is not guaranteed to be represent a number that line will gi...
🌐
Quora
quora.com › How-do-I-debug-this-TypeError-bad-operand-type-for-unary-str-in-python
How to debug this 'TypeError: bad operand type for unary -: 'str' in python - Quora
... Look for a leading minus: -, e.g. -value, -item, -(a-b), or inside comprehensions/lamdba ... The error "TypeError: bad operand type for unary -: 'str'" means Python tried to apply the unary minus operator (-x) to a string value.