Printing a tuple instead of text - python-2.7

x= input('What is your name? ')
print('Heloo',x)
The above code is giving an output ('Heloo', 5) for the input as 5.
The above code is giving an output ('Heloo', 'shubham') for the input as 'shubham'.
The above code is giving an error for the input as shubham without quotes.
Traceback (most recent call last):
File "C:/Users/SHUBHAM/Desktop/Python1.py", line 1, in <module>
x= input('What is your name? ')
File "<string>", line 1, in <module>
NameError: name 'shubham' is not defined
Can anyone suggest me what is the error with my code?
Thank You.

shubham is not defined. It works for x because you are asking the user to define x, which is why when you call on it to print it works. It works in quotes because you are telling Python that it is a string but when you leave it without quotes it assumes it is a variable, but since you have not assigned anything to it, it gives you this error.

Related

Why isdigit is working but isdecimal is not for a simple age code

This is the part of code I am talking about:
while True:
print 'What is your age(only numeric):'
age = raw_input()
if age.isdigit():
break
print 'Please try again. We take only numeric value.'
When I replace isdigit with isdecimal, I get this error no matter what value i enter.
Traceback (most recent call last):
File "test.py", line 4, in <module>
if age.isdecimal():
AttributeError: 'str' object has no attribute 'isdecimal'
Although it runs fine with isdigit.
Also, when I replace raw_input with input, it give this error.
Traceback (most recent call last):
File "test.py", line 4, in <module>
if age.isdigit():
AttributeError: 'int' object has no attribute 'isdigit'
Am I doing something wrong which I am not able to catch? I am new to python and did my research about isdigit, is decimal, input and raw_input before putting down question here. It may be very minute error but I am not sure what is it.
For the first part:
In Python 2, isdecimal is a method of the unicode class, not of str (i.e. bytes). Hence:
>>> '3.2'.isdecimal()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'isdecimal'
>>> u'3.2'.isdecimal()
For the second part, input tries to guess what kind of input it gets, and will properly cast "1" into an int, while raw_input will always return the raw string. Since isdigit is a method defined in the str class, you get the error.

UTF-8 error with the python open() function

I wrote a simple code in python the only opens and read a file
def read_text():
quotes = open("‪C:/Users/Matteo/Desktop/quotes.txt")
contents_of_file = quotes.read()
print(contents_of_file)
quotes.close()
read_text()
When i try to execute it this is what appears
Traceback (most recent call last):
File "C:\Python27\read.py", line 6, in <module>
read_text()
File "C:\Python27\read.py", line 2, in read_text
quotes = open("‪C:/Users/Matteo/Desktop/quotes.txt")
IOError: [Errno 22] invalid mode ('r') or filename: '\xe2\x80\xaaC:/Users /Matteo/Desktop/quotes.txt'
Searching on the internet i understood that the problem is that IDLE recognizes an Unicode character before C, \xe2\x80\xaa, that is a "LEFT-TO-RIGHT EMBEDDING". I have no idea of what is this and how to remove from my code.
Your code contains an invisible character (probably because you copy/pasted the filename from somewhere). Try deleting the "C: part and retyping it.

Accessing a csv file in python

I keep getting an "invalid keyword" error when i try to read from a csv file in python. Any ideas for a work around for this?
C:\Python27\python.exe C:/Users/User_Name/PycharmProjects/untitled/car.py
Traceback (most recent call last): File
"C:/Users/User_Name/PycharmProjects/untitled/car.py", line 122, in <module> d = handle_refugee_data.DataTable(csvformat="generic", data_directory="car2014", start_date="2013-12-01") File
"C:\Users\User_Name\PycharmProjects\untitled\handle_refugee_data.py", line 78, in __init__ with open("%s/%s" % (data_directory, data_layout), newline='') as csvfile:
TypeError: 'newline' is an invalid keyword argument for this function
Process finished with exit code 1
========================================================================
newline is a valid keyword argument to open() in Python 3, but not in Python 2, which appears to be what you are using.
One solution, if possible, would be to execute the script with Python 3 instead. Alternatively, as pointed out by #dhke in the comments, you could use io.open() instead, which does accept a newline keyword argument.
Of course, you could probably use the csv module instead, depending on your use case (which is not clear from the original question).

%matplotlib inline ValueError

When I use %matplotlib inline in my program, I get a ValueError. What does this error mean, and how can I resolve it?
Here is the error:
Traceback (most recent call last):
File "main.py", line 40, in <module>
ct.iloc[:-1,:-1].plot(kind='bar',stacked=True,color=['red','blue'],grid='false')
File "/usr/lib/python2.7/dist-packages/pandas/tools/plotting.py", line 1735, in plot_frame
plot_obj.generate()
File "/usr/lib/python2.7/dist-packages/pandas/tools/plotting.py", line 907, in generate
self._adorn_subplots()
File "/usr/lib/python2.7/dist-packages/pandas/tools/plotting.py", line 1012, in _adorn_subplots
ax.grid(self.grid)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 2176, in grid
b = _string_to_bool(b)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 54, in _string_to_bool
raise ValueError("string argument must be either 'on' or 'off'")
ValueError: string argument must be either 'on' or 'off'
When asking a question you should follow these guidlines: https://stackoverflow.com/help/mcve
instead of just posting a traceback.
That said tracebacks can be very useful and following yours you'll be able to figure out the problem.
Using the final line of your traceback can be very useful. One of the string arguments you are passing should only be 'on' or 'off'. Based on this we can then look at the grid option as this is a boolean option.
I tested this like so:
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([23,4],[4,6])
plt.grid('false')
giving the same error you got.
To fix this you should use either grid = 'off' or grid = False as options. In my example above I would change that to plt.grid('off')

Django-Adaptors TypeError: "delimiter" must be an 1-character string

I am getting an error when trying to import some data into my model. The error I'm getting is TypeError: complaining about the delimiter I'm using.
Below is my model for the CSV import, I am using the default delimiter suggested by the documentation.
class SkuCsvModel(CsvModel):
sku_num = models.CharField()
sku_category = models.ForeignKey(SkuCategory)
short_desc = models.CharField()
class Meta:
delimiter = ";"
dbModel = Sku
The CSV file I'm trying to use is below:
1365400;9;3/8 BALL VALVE
1401901;9;BRASS ELBOW
1406300;9;HOSE BARB, NPT
The code I'm testing in the manage.py shell is:
>>> from core.models import SkuCsvModel
>>> my_csv_list = SkuCsvModel.import_data(data = open("labconco.csv"))
And finally the error I'm getting is:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "E:\bin\Python27\lib\site-packages\adaptor\model.py", line 197, in import_data
return importer.import_data(data)
File "E:\bin\Python27\lib\site-packages\adaptor\model.py", line 466, in import_data
for line in csv.reader(data, delimiter=self.delimiter):
TypeError: "delimiter" must be an 1-character string
So I've been fiddling around with the django-adaptor tools, and this error is coming from the import_data() method of the CsvImporter, when I try and put a delimiter directly into the csv.reader(data, delimiter=';') this works fine and I'm able to see the file correctly. But no matter how I try and enter this import_data method sending in a ';' will generate an error.
Look at the snippet below. If I provide an integer as a delimiter, it fails with the same exception as in your example. If I provide a semicolon as a delimiter to csv.reader it works. This is basically what is done in model.CsvImporter.import_data() as you already found out.
>>> import csv
>>> import StringIO
>>> io = StringIO.StringIO('name;surname\nsascha;gottfried')
>>> for line in csv.reader(io, delimiter=10):
... print line
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: "delimiter" must be an 1-character string
>>> for line in csv.reader(io, delimiter=';'):
... print line
...
['name', 'surname']
['sascha', 'gottfried']
To debug the situation dump the current value of 'self.delimiter' to the console or similar before it will be passed as a delimiter to csv.reader(). It must be a different value and/or type than ';'. Looking at the code of django-adaptors you can validate your django-adaptors model definition with this base class method as well to debug. This call should print out what you defined as Meta.delimiter.
>>> from core.models import SkuCsvModel
>>> SkuCsvModel.has_class_delimiter()
But it is pretty fine to omit a delimiter definition and call 'import_from_file' on the model. Make sure there is no class delimiter defined. If so the importer runs a CSV sniff to detect the delimiter from the file you passed. If you provide the file you mentioned, the sniffer will detect a ';' and sets self.delimiter.
>>> from core.models import SkuCsvModel
>>> SkuCsvModel.has_class_delimiter()
None
>>> my_csv_list = SkuCsvModel.import_from_file(file = open("labconco.csv"))