This is the code:
import time
import os
os.system("cls")
a=1
while True:
if a>512:
a=1
print (a + " kb")
if a<1024:
print (a + " bytes")
a *= 2
time.sleep(.5)
But it gives me this error:
> Traceback (most recent call last):
> File "Sequence1.py", line 10, in <module>
> print (a + " bytes")
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
If I changed it to a string then my if statements wouldn't work. Sorry if this question has been asked before. Thanks.
While you need a to be integer for you logic you need it as string just for presentational purposes. So convert it only when printing it. You have several ways to do that, as you certainly know. Some of them:
print('{0} bytes'.format(a))
print('%s bytes' % a)
print(str(a) + ' bytes')
Related
this is the error which i am getting. In the previous post i forget to put both function . In the first function i'm reading csv file and removing punctuation and send the string to second function to calculate the sentimentel score. this code give output for few row of csv file and then show this error i'm new in python
Traceback (most recent call last):
File "C:/Users/Public/Downloads/Hotelsurvey.py", line 116, in <module>
Countswordofeachsyntax()
File "C:/Users/Public/Downloads/Hotelsurvey.py", line 92, in Countswordofeachsyntax
print(findsentimentalscore(nopunct))
File "C:/Users/Public/Downloads/Hotelsurvey.py", line 111, in findsentimentalscore
ss =ss + weight
TypeError: unsupported operand type(s) for +: 'int' and 'list'
def Countswordofeachsyntax():
nopunct = ""
with open('dataset-CalheirosMoroRita-2017.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter='|')
for sys in csv_reader:
for value in sys:
nopunct = ""
for ch in value:
if ch not in punctuation:
nopunct = nopunct + ch
print(findsentimentalscore(nopunct))
def findsentimentalscore(st):
ss = 0
count = len(st.split())
mycollapsedstring = ' '.join(st.split())
print(str(mycollapsedstring.split(' ')) + " := " + str(len(mycollapsedstring.split())))
for key, weight in keywords.items():
if key in mycollapsedstring.lower():
ss =ss + weight
#print(key, weight)
res = (ss / count * 100)
return math.ceil(res)
I would like to import the list from the file, read it line by line (already works). Each line containing a string representing a list.
I have to execute couple of tasks on it, however I got twisted and I dont know why below doesn't work. It gives me the following error :
ErrorCode:
Traceback (most recent call last):
File "main.py", line 8, in <module>
if len(n) != len(str(n + 1)):
TypeError: must be str, not int
f = open('listy.txt', 'r')
content = f.read().split('\n')
for n in content:
n.split(',')
## checking lengh
if len(n) != len(str(n + 1)):
print('Different lengh')
else:
print('All fine.')
Change
n.split(',')
if len(n) != len(str(n + 1)):
to:
n = n.split(',')
len(n[0]) != len(n[1]):
and don't forget to close your file with a f.close()
Better even, use with, example:
with open('listy.txt', 'r') as f:
content = f.read().split('\n')
you do not need a close() method when using with
I am new to this python coding.So,please can someone find what is the problem with this code.
def factorial(n):
sum=1
for i in range(1..n+1):
sum=sum*i
print(sum)
return sum
v=int(input("enter the number:"))
factorial(v)
the error i get:
enter the number:4
Traceback (most recent call last):
File "C:/Users/Ramakrishnar/AppData/Local/Programs/Python/Python36/fact.py",line 9, in <module>
factorial(v)
File "C:/Users/Ramakrishnar/AppData/Local/Programs/Python/Python36/fact.py", line 3, in factorial
for i in range(1..n+1):
AttributeError: 'float' object has no attribute 'n'
There are two ways you can write your program. To reformat your code so that it is in good form, you might organize your program like so:
def main():
variable = int(input('Enter the number: '))
print(factorial(variable))
def factorial(number):
total = 1
for integer in range(1, number + 1):
total *= integer
return total
if __name__ == '__main__':
main()
If instead you are trying to accomplish the same thing using the least amount of code, the following two lines will do the exact same thing for you:
import math
print(math.factorial(int(input('Enter the number: '))))
I have a SOAP server with pysimplesoap in Python 3.
Code
from wsgiref.simple_server import make_server
application = WSGISOAPHandler(dispatcher)
wsgid = make_server('', 8008, application)
wsgid.serve_forever()
I don't know why am I get the following error.
Error
Traceback (most recent call last):
File "/usr/lib/python3.4/wsgiref/handlers.py", line 138, in run
self.finish_response()
File "/usr/lib/python3.4/wsgiref/handlers.py", line 180, in finish_response
self.write(data)
File "/usr/lib/python3.4/wsgiref/handlers.py", line 266, in write
"write() argument must be a bytes instance"
AssertionError: write() argument must be a bytes instance
It's all because of WSGI is made for Python 2, so you can face some troubles using it in Python 3. If you dont want to change library's behavior like in first answer, workaround is to encode() all text data like:
def application(environ,start_response):
response_body = 'Hello World'
return [response_body.encode()]
Wsgi framework is built around Python 2. Therefore, if there is stuff in your program that does not include Python 3 dependencies, run the app with Python 2.
in "handlers.py" line 180
self.write(data.encode()) instead of self.write(data)
In my case the problem turned out to be that I was unintentionally outputting an object instead of a string. Fixed by encoding my result as a string via json.dumps(obj).
+++ pysimplesoap/server.py
e['name'] = k
if array:
e[:] = {'minOccurs': "0", 'maxOccurs': "unbounded"}
- if v in TYPE_MAP.keys():
- t = 'xsd:%s' % TYPE_MAP[v]
- elif v is None:
+
+ # check list and dict first to avoid
+ # TypeError: unhashable type: 'list' or
+ # TypeError: unhashable type: 'dict'
+ if v is None:
t = 'xsd:anyType'
elif isinstance(v, list):
n = "ArrayOf%s%s" % (name, k)
n = "%s%s" % (name, k)
parse_element(n, v.items(), complex=True)
t = "tns:%s" % n
+ elif v in TYPE_MAP.keys():
+ t = 'xsd:%s' % TYPE_MAP[v]
else:
raise TypeError("unknonw type v for marshalling" % str(v))
e.add_attribute('type', t)
hi im trying to create a Caesar cipher using Python 3, the question is in the text, chapter 5 question 7, I have this so far but i keep getting this error message when i try to run the program and cant figure out why.
program:
def main():
print("This program executes a Caesar cipher for a string")
word = input("Please enter word: ")
key = input("Please enter the number of positions in the alphabet you wish to apply: ")
message=""
for ch in word:
word= chr(ord(ch)+key)
newWord =(message + word)
print (newWord)
main()
Error:
Traceback (most recent call last):
File "/Users/krissinger/Documents/programing /my graphics/delete.py", line 14, in <module>
main()
File "/Users/krissinger/Documents/programing /my graphics/delete.py", line 10, in main
word= chr(ord(ch)+key)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
word= chr(ord(ch)+key)
ord(ch) gives the integer value for that chr. Adding it with a string gives a TypeError, since the + operator is used differently for integers and strings. If you want key to be an int, you must do:
key = int(input("....")
Then, you can add them together.