Why does print('\n') * 100 not work in Python 3.3? - python-3.x

I am attempting to clear lines of code in Python and came across a post at Any way to clear python's IDLE window? on how to do so however when I run the function below in IDLE 3.3 I get the error below. It does however work in version 2.7.3.
ERROR
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
cls()
File "<pyshell#6>", line 2, in cls
print('\n') * 100
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
CODE
def cls():
print('\n') * 100

You probably mean
print('\n' * 100)
When you multiply a string by an int, it is repeated:
>>> 'ha' * 3
'hahaha'
But what you do is multiply the value of print('\n') by 100. But print() doesn't return anything (read: returns None), hence the error: you can't multiply None and int.
In Python 2 there is no difference, because there are no parentheses:
print '\n' * 100
Still, it's interpreted by Python the same way as in Python 3 (and not the same way you seem to iterpret it).

Related

%s error when trying to put a variable into a string python

Trying to build a "launcher" type thing for youtube-dl(program that lets you download youtube videos), and getting an error. I understand what the error means but it makes no sense as I am(I think) doing exactly what python wants.
This is my code:
import os
import sys
x = input('Enter link for youtube Video you would like to download: ')
ytdp = open('C:\\Games\\ytdp.bat', 'w')
ytdp.write('cd C:\\Users\Jake\Music')
ytdp.write('\n')
ytdp.write('youtube-dl %s')% (x)
ytdp.close()
os.startfile('C:\\Games\ytdp.bat')
sys.exit()
This is the error I get when running the code
Traceback (most recent call last):
File "C:\Users\Jake\Desktop\Youtube video downloader.py", line 8, in <module>
ytdp.write('youtube-dl %s')% (xx)
TypeError: unsupported operand type(s) for %: 'int' and 'str'
ytdp.write('youtube-dl %s')% (xx)
Should be
ytdp.write('youtube-dl %s'% (xx))
Here is some more info on it

Keep getting error `TypeError: 'float' object is not callable' when trying to run file using numpy library

I intend to perform a Newton Raphson iteration on some data I read in from a file. I use the following function in my python program.
def newton_raphson(r1, r2):
guess1 = 2 * numpy.log(2) / (numpy.pi() * (r1 + r2))
I call this function as so:
if answer == "f": # if data is in file
fileName = input("What is the name of the file you want to open?")
dataArray = extract_data_from_file(fileName)
resistivityArray = []
for i in range(0, len(dataArray[0])):
resistivity_point = newton_raphson(dataArray[0][i], dataArray[1][i])
resistivityArray += [resistivity_point]
On running the program and entering my file, this returns `TypeError: 'float' object is not callable'. Everything I've read online suggests this is due to missing an operator somewhere in my code, but I can't see where I have. Why do I keep getting this error and how do I avoid it?
numpy.pi is not a function, it is a constant:
>>> import numpy
>>> numpy.pi
3.141592653589793
Remove the () call from it:
def newton_raphson(r1, r2):
guess1 = 2 * numpy.log(2) / (numpy.pi * (r1 + r2))
as that is causing your error:
>>> numpy.pi()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not callable

MPI_Send(100): Invalid rank has value 1 but must be nonnegative and less than 1

I am learning MPI in python by myself. I just started from the basic documentation of MPI4py. I started with this code:
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
data = {'a': 7, 'b': 3.14}
comm.send(data, dest=1, tag=11)
elif rank == 1:
data = comm.recv(source=0, tag=11)
When I ran this program, I got following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "MPI/Comm.pyx", line 1175, in mpi4py.MPI.Comm.send (src/mpi4py.MPI.c:106424)
File "MPI/msgpickle.pxi", line 211, in mpi4py.MPI.PyMPI_send (src/mpi4py.MPI.c:42120)
mpi4py.MPI.Exception: Invalid rank, error stack:
MPI_Send(174): MPI_Send(buf=0x10e137554, count=25, MPI_BYTE, dest=1, tag=11, MPI_COMM_WORLD) failed
MPI_Send(100): Invalid rank has value 1 but must be nonnegative and less than 1
I didn't find any working solution for this problem. I am using Mac OS X El Capitan.
Thanks in Advance!
The program complains that 1 is not a valid rank for MPI_Send(): it means that your program is running on a single process.
Are you running it by using python main.py ? Try to use mpirun -np 2 python main.py, where 2 is the number of processes. The latter is the usual way to run mpi programs.

TypeError: len() of unsized object when comparing and I cannot make sense of it

I am trying to select sensors by placing a box around their geographic coordinates:
In [1]: lat_min, lat_max = lats(data)
lon_min, lon_max = lons(data)
print(np.around(np.array([lat_min, lat_max, lon_min, lon_max]), 5))
Out[1]: [ 32.87248 33.10181 -94.37297 -94.21224]
In [2]: select_sens = sens[(lat_min<=sens['LATITUDE']) & (sens['LATITUDE']<=lat_max) &
(lon_min<=sens['LONGITUDE']) & (sens['LONGITUDE']<=lon_max)].copy()
Out[2]: ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-7881f6717415> in <module>()
4 lon_min, lon_max = lons(data)
5 select_sens = sens[(lat_min<=sens['LATITUDE']) & (sens['LATITUDE']<=lat_max) &
----> 6 (lon_min<=sens['LONGITUDE']) & (sens['LONGITUDE']<=lon_max)].copy()
7 sens_data = data[data['ID'].isin(select_sens['ID'])].copy()
8 sens_data.describe()
/home/kartik/miniconda3/lib/python3.5/site-packages/pandas/core/ops.py in wrapper(self, other, axis)
703 return NotImplemented
704 elif isinstance(other, (np.ndarray, pd.Index)):
--> 705 if len(self) != len(other):
706 raise ValueError('Lengths must match to compare')
707 return self._constructor(na_op(self.values, np.asarray(other)),
TypeError: len() of unsized object
Of course, sens is a pandas DataFrame. Even when I use .where() it raises the same error. I am completely stumped, because it is a simple comparison that shouldn't raise any errors. Even the data types match:
In [3]: sens.dtypes
Out[3]: ID object
COUNTRY object
STATE object
COUNTY object
LENGTH float64
NUMBER object
NAME object
LATITUDE float64
LONGITUDE float64
dtype: object
So what is going on?!?
-----EDIT------
As per Ethan Furman's answer, I made the following changes:
In [2]: select_sens = sens[([lat_min]<=sens['LATITUDE']) & (sens['LATITUDE']<=[lat_max]) &
([lon_min]<=sens['LONGITUDE']) & (sens['LONGITUDE']<=[lon_max])].copy()
And (drumroll) it worked... But why?
I'm not familiar with NumPy nor Pandas, but the error is saying that one of the objects in the comparison if len(self) != len(other) does not have a __len__ method and therefore has no length.
Try doing print(sens_data) to see if you get a similar error.
I found a similar issue and think the problem may be related to the Python version you are using.
I wrote my code in Spyder
Python 3.6.1 |Anaconda 4.4.0 (64-bit)
but then passed it to someone using Spyder but
Python 3.5.2 |Anaconda 4.2.0 (64-bit)
I had one numpy.float64 object (as far as i understand, similar to lat_min, lat_max, lon_min and lon_max in your code) MinWD.MinWD[i]
In [92]: type(MinWD.MinWD[i])
Out[92]: numpy.float64
and a Pandas data frame WatDemandCur with one column called Percentages
In [96]: type(WatDemandCur)
Out[96]: pandas.core.frame.DataFrame
In [98]: type(WatDemandCur['Percentages'])
Out[98]: pandas.core.series.Series
and i wanted to do the following comparison
In [99]: MinWD.MinWD[i]==WatDemandCur.Percentages
There was no problem with this line when running the code in my machine (Python 3.6.1)
But my friend got something similar to you in (Python 3.5.2)
MinWD.MinWD[i]==WatDemandCur.Percentages
Traceback (most recent call last):
File "<ipython-input-99-3e762b849176>", line 1, in <module>
MinWD.MinWD[i]==WatDemandCur.Percentages
File "C:\Program Files\Anaconda3\lib\site-packages\pandas\core\ops.py", line 741, in wrapper
if len(self) != len(other):
TypeError: len() of unsized object
My solution to his problem was to change the code to
[MinWD.MinWD[i]==x for x in WatDemandCur.Percentages]
and it worked in both versions!
With this and your evidence, i would assume that it is not possible to compare numpy.float64 and perhaps numpy.integers objects with Pandas Series, and this could be partly related to the fact that the former have no len function.
Just for curiosity, i did some tests with float and integer objects (please tell the difference with numpy.float64 object)
In [122]: Temp=1
In [123]: Temp2=1.0
In [124]: type(Temp)
Out[124]: int
In [125]: type(Temp2)
Out[125]: float
In [126]: len(Temp)
Traceback (most recent call last):
File "<ipython-input-126-dc80ab11ca9c>", line 1, in <module>
len(Temp)
TypeError: object of type 'int' has no len()
In [127]: len(Temp2)
Traceback (most recent call last):
File "<ipython-input-127-a1b836f351d2>", line 1, in <module>
len(Temp2)
TypeError: object of type 'float' has no len()
Temp==WatDemandCur.Percentages
Temp2==WatDemandCur.Percentages
Both worked!
Conclusions
In another python version your code should work!
The problem with the comparison is specific for numpy.floats and perhaps numpy.integers
When you include [] or when I create the list with my solution, the type of object is changed from a numpy.float to a list, and in this way it works fine.
Although the problem seems to be related to the fact that numpy.float64 objects have no len function, floats and integers, which do not have a len function either, do work.
Hope some of this works for you or someone else facing a similar issue.

SyntaxError: unexpected EOF while parsing in Python 3

Code :
n,X=input(),0
for t in range(int(n)):
eval(input())
print(X)
Traceback (most recent call last):
File "prog.py", line 3, in <module>
eval(input())
File "<string>", line 1
X++
^
SyntaxError: unexpected EOF while parsing
Using raw_input instead of input() in the only solution I am able to find but in python 3.x input is raw_input(): How do I use raw_input in Python 3
any other method?
FYI; I am trying to solve: http://codeforces.com/problemset/problem/282/A
Remove the eval() call.
input() in Python 2 is the equivalent of eval(input()) in Python 3, and if you need to use raw_input() in Python 2 then in Python 3 you need to remove the eval() call.
You'll have to parse the input yourself; ++ is not a valid Python operator, you cannot use eval() to solve that Codeforces problem.
The simplest way to solve the posted problem is to read the input line by line:
import sys, itertools
count = int(next(sys.stdin))
x = 0
for line in itertools.islice(sys.stdin, count):
x += 1 if '++' in line else -1
print(x)

Resources