How to convert an input to string - python

while n == 1:
w = inputs.append(input('Enter the product code: '))
with open('items.txt') as f:
found = False
for line in f:
if w in line:
So this is the part of the code with the issue. After the last line a bunch of stuff happens which is irrelevant to the question. When i run it, i get the error:
if w in line:
TypeError: 'in ' requires string as left operand, not NoneType
I know it's because i need to convert w to a string somehow but i don't know what to do. Any help is appreciated.

input() already returns a string, so there is no need to convert it.
You have this:
w = inputs.append(input('Enter the product code: '))
You should be doing this in two steps, since you are assigning w to the return value of append(), rather than the return value of input() in this case. append() will always return None regardless of the user input, so w in your program will be assigned to None. Instead, try:
w = input('Enter the product code: ')
inputs.append(w)

Related

What causes this return() to create a SyntaxError?

I need this program to create a sheet as a list of strings of ' ' chars and distribute text strings (from a list) into it. I have already coded return statements in python 3 but this one keeps giving
return(riplns)
^
SyntaxError: invalid syntax
It's the return(riplns) on line 39. I want the function to create a number of random numbers (randint) inside a range built around another randint, coming from the function ripimg() that calls this one.
I see clearly where the program declares the list I want this return() to give me. I know its type. I see where I feed variables (of the int type) to it, through .append(). I know from internet research that SyntaxErrors on python's return() functions usually come from mistype but it doesn't seem the case.
#loads the asciified image ("/home/userX/Documents/Programmazione/Python projects/imgascii/myascify/ascimg4")
#creates a sheet "foglio1", same number of lines as the asciified image, and distributes text on it on a randomised line
#create the sheet foglio1
def create():
ref = open("/home/userX/Documents/Programmazione/Python projects/imgascii/myascify/ascimg4")
charcount = ""
field = []
for line in ref:
for c in line:
if c != '\n':
charcount += ' '
if c == '\n':
charcount += '*' #<--- YOU GONNA NEED TO MAKE THIS A SPACE IN A FOLLOWING FUNCTION IN THE WRITER.PY PROGRAM
for i in range(50):#<------- VALUE ADJUSTMENT FROM WRITER.PY GOES HERE(default : 50):
charcount += ' '
charcount += '\n'
break
for line in ref:
field.append(charcount)
return(field)
#turn text in a list of lines and trasforms the lines in a list of strings
def poemln():
txt = open("/home/gcg/Documents/Programmazione/Python projects/imgascii/writer/poem")
arrays = []
for line in txt:
arrays.append(line)
txt.close()
return(arrays)
#rander is to be called in ripimg()
def rander(rando, fldepth):
riplns = []
for i in range(fldepth):
riplns.append(randint((rando)-1,(rando)+1)
return(riplns) #<---- THIS RETURN GIVES SyntaxError upon execution
#opens a rip on the side of the image.
def ripimg():
upmost = randint(160, 168)
positions = []
fldepth = 52 #<-----value is manually input as in DISTRIB function.
positions = rander(upmost,fldepth)
return(positions)
I omitted the rest of the program, I believe these functions are enough to get the idea, please tell me if I need to add more.
You have incomplete set of previous line's parenthesis .
In this line:-
riplns.append(randint((rando)-1,(rando)+1)
You have to add one more brace at the end. This was causing error because python was reading things continuously and thought return statement to be a part of previous uncompleted line.

Python; Encode to MD5 (hashlib) shows error: "NoneType"

I wrote a code that will generate random password for 5 times, and I would like to encode that passwords to MD5, but when I try to encode it, it will show an error that 'NoneType' object has no attribute 'encode' and I dont know how to change the code to avoid this error. Sorry I'm beginner in python... My Code is below. Thanks for help
import random, string
import hashlib
length = 6
chars = string.ascii_letters + string.digits
def ff():
rnd = random.SystemRandom()
a = (''.join(rnd.choice(chars) for i in range(length)))
c = a
return(c)
def ff2():
for i in range(5):
print(ff(),' ')
str = ff2()
result = hashlib.md5(str.encode())
print("The hexadecimal equivalent of hash is : ", end ="")
print(result.hexdigest())
The function ff2 doesn’t return anything so str will be of type NoneType.
IIUC, your ff2() function should call ff() five times but it should not print out the result. It should accumulate them in a string and return the string. Something like this perhaps:
def ff2():
l = []
for i in range(5):
l.append(ff())
return " ".join(l)
Here we accumulate the results of the five calls to ff() in a list l and then
use the string method join() to join them together.
The above returns a string that is the concatenation of the five strings that the calls to ff() returned, with spaces separating them. If you want commas as separators, just replace the return " ".join(l) with return ",".join(l).

Within a simple finite state machine, Error : 'int' object is not iteratable

Im trying to create a finite state machine that reads in the states, transitions, and the strings. I am trying to create it without objects. Everything works up till my for loops. However, as soon as the loop begins I get the error message:
line 42, in <module>
for I in len (Strings):
TypeError: 'int' object is not iterable
Why is this happening? Any tips would be appreciated.
Sfile = open("states.txt","r")
States = []
ReadLine = Sfile.readline()
while ReadLine != "":
A, B, C = ReadLine.split(",")
States.append((A, bool(int(B)), bool(int(C))))
ReadLine = Sfile.readline()
print States, "\n"
Sfile.close()
Tfile = open("transistions.txt","r")
Transitions = []
ReadLine = Tfile.readline()
while ReadLine != "":
ReadLine = ReadLine.rstrip()
Tran4, Tran5, Tran6 = ReadLine.split(",")
Transitions.append((Tran4, Tran5, Tran6))
ReadLine = Tfile.readline()
print Transitions
Tfile.close()
Strfile = open("strings2.txt","r")
Strings = []
ReadLine = Strfile.readline()
while ReadLine != "":
Readline = ReadLine.rstrip()
Strings.append(Readline)
ReadLine = Strfile.readline()
print Strings, '\n'
Strfile.close()
for I in len (Strings):
for C in Strings[I]:
Start = '0'
Current = Start
if C in Strings == '0':
Current = A
else:
Current = State
print Current...
My different text files contain:
states.txt
State2,1,0
State3,0,1
State4,1,0
transitions.txt
State1,0,State2
State2,1,State3
State3,0,State4
strings2.txt
10100101
1001
10010
You can't iterate over an integer. I think you meant to iterate over a range object range(len(Strings)). This will work because the range object is an iterable and the int is not.
You want i in range(len(Strings)). Len returns a whole number, like 13 -- in wants something like a vector. range(13) gives you a vector [0,1,2,3,4,5,6,7,8,9,10,11,12].
Quiz question: why is the last number 12?
You're trying to iterate over an integer, it should be
for I in range(len(Strings))
You will need to turn the number to a string as you cant pick out the first digit of an int. So str(1234)='1234' '1234'[0]='1'
len(s) gives you an integer, and you can't iterate over that. If you want to iterate over a collection of strings, use for s in strings.
you can't iterate over a number or any other singular object, you need a composite object like a list, to do that. In this case look like you want this
for words in Strings:
for C in words:
...

String to integer implicit change when not called for?

I'm trying to create a simple encryption/decryption code in Python like this (maybe you can see what I'm going for):
def encrypt():
import random
input1 = input('Write Text: ')
input1 = input1.lower()
key = random.randint(10,73)
output = []
for character in input1:
number = ord(character) - 96
number = number + key
output.append(number)
output.insert(0,key)
print (''.join(map(str, output)))
def decrypt():
text = input ('What to decrypt?')
key = int(text[0:2])
text = text[2:]
n=2
text = text
text = [text[i:i+n] for i in range(0, len(text), n)]
text = map(int,text)
text = [x - key for x in text]
text = ''.join(map(str,text))
text = int(text)
print (text)
for character in str(text):
output = []
character = int((character+96))
number = str(chr(character))
output.append(number)
print (''.join(map(str, output)))
When I run the decryptor with the output from the encryption output, I get "TypeError: Can't convert 'int' object to str implicitly."
As you can see, I've added some redundancies to help try to fix things but nothing's working. I ran it with different code (can't remember what), but all that one kept outputting was something like "generatorobject at ."
I'm really lost and I could use some pointers guys, please and thank you.
EDIT: The problem arises on line 27.
EDIT 2: Replaced "character = int((character+96))" with "character = int(character)+96", now the problem is that it only prints (and as I can only assume) only appends the last letter of the decrypted message.
EDIT 2 SOLVED: output = [] was in the for loop, thus resetting it every time. Problem solved, thank you everyone!
Full traceback would help, but it looks like character = int(character)+96 is what you want on line 27.

How to convert str into an int?

I'm trying to make this code turn the prodname variable into an int value:
def prod_check(dirname):
prodname_to_prodnum = {}
fid2 = open('sample.txt','r')
line = fid2.readline()
line = line.strip()
pline = line.split(',')
prodname = (pline[0])[1:-1]
prodnum = prodname
prodname_to_prodnum[prodname] = prodnum
line = fid2.readline()
fid2.close()
but when I used "int(prodname)" I get an error
Try this instead of prodnum = prodname:
try:
prodnum = int(prodname)
except ValueError:
prodnum = None
print('prodname = ',prodname)
Lists in Python are 0-based, not 1-based. You've already broken the line into fields with split, so you should use prodnum = int(pline[0]) to get the first field.
Edit: I wish people would use copy/paste to put their code into the question, typos make all the difference.
I don't know why you're removing the first and last character from the number field, perhaps because you need to strip blanks from it? If so, try using prodnum = int(pline[0].strip()).

Categories