Python List NoneType Error - nonetype

I'm having an issue with an OpenCourseWare project I'm trying to implement. I'm creating a hangman game and everything seems to be okay until I attempt to run the actual function for playing the game.
I'm receiving the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "Game of Hangman/hangman.py", line 118, in play_hangman
print(print_guessed())
File "Game of Hangman/hangman.py", line 92, in print_guessed
if letter in letters_guessed == True:
TypeError: argument of type 'NoneType' is not iterable
I can't seem to understand why the list is evaluating to a NoneType even though it is declared as an empty list. I've used the console to attempt to find the answer and says the type is NoneType. Could someone help me please? I've provided the code as a reference.
# Name:
# Section:
# 6.189 Project 1: Hangman template
# hangman_template.py
# Import statements: DO NOT delete these! DO NOT write code above this!
from random import randrange
from string import *
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
# Import hangman words
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = split(line)
print " ", len(wordlist), "words loaded."
print 'Enter play_hangman() to play a game of hangman!'
return wordlist
# actually load the dictionary of words and point to it with
# the words_dict variable so that it can be accessed from anywhere
# in the program
words_dict = load_words()
# Run get_word() within your program to generate a random secret word
# by using a line like this within your program:
# secret_word = get_word()
def get_word():
"""
Returns a random word from the word list
"""
word=words_dict[randrange(0,len(words_dict))]
return word
# end of helper code
# -----------------------------------
# CONSTANTS
MAX_GUESSES = 6
# GLOBAL VARIABLES
secret_word = get_word()
letters_guessed = []
# From part 3b:
def word_guessed():
'''
Returns True if the player has successfully guessed the word,
and False otherwise.
'''
global secret_word
global letters_guessed
wordGuessed = False
####### YOUR CODE HERE ######
for letter in secret_word:
if letter in letters_guessed:
wordGuessed = True
else:
wordGuessed = False
break
return wordGuessed
def print_guessed():
'''
Prints out the characters you have guessed in the secret word so far
'''
global secret_word
global letters_guessed
printedWord = []
####### YOUR CODE HERE ######
for letter in secret_word:
if letter in letters_guessed:
printedWord.append(letter)
else:
printedWord.append("-")
return printedWord
def play_hangman():
# Actually play the hangman game
global secret_word
global letters_guessed
# Put the mistakes_made variable here, since you'll only use it in this function
mistakes_made = 0
# Update secret_word. Don't uncomment this line until you get to Step 8.
secret_word = get_word()
####### YOUR CODE HERE ######
while mistakes_made < MAX_GUESSES or word_guessed() == False:
print("WORD:")
userGuess = raw_input("What is your guess?\n").lower()
if userGuess in secret_word:
letters_guessed = letters_guessed.append(userGuess)
else:
letters_guessed = letters_guessed.append(userGuess)
mistakes_made += 1
print(print_guessed())
if word_guessed() == False:
print("Sorry but you've run out of guesses...")
else:
print("You've correctly guessed the secret word!")
print("Secret Word: " + secret_word)
Just as a disclaimer, this isn't an assignment in the sense I'm not enrolled in school. I'm just a guy trying to get back in to programming and found some assignments to play with.

Looks like I've found my answer. The problem appeared to be with the assignment I was doing with the letters_guessed variable.
Instead of doing:
letters_guessed = letters_guessed.append(userGuess)
I should have done:
letters_guessed.append(userGuess)

Related

Crack a zip using python 2

I need to crack a zip file and i know the first part of the password but I don't know the last 3 letters. This is what i've written but it doesn't work. I have no idea why. can anyone spot my mistake?
T
import zipfile
import itertools
import time
# Function for extracting zip files to test if the password works!
def extractFile(zip_file, password):
try:
zip_file.extractall(pwd=password)
return True
except KeyboardInterrupt:
exit(0)
except Exception, e:
pass
# Main code starts here...
# The file name of the zip file.
zipfilename = 'data.zip'
# The first part of the password.
first_half_password = 'Cola'
# We don't know what characters they add afterwards...
# This is case sensitive!
alphabet = 'abcdefghijklmnopqrstuvwxyz'
zip_file = zipfile.ZipFile(zipfilename)
# We know they always have 3 characters after the first half of the password
# For every possible combination of 3 letters from alphabet...
for c in itertools.product(alphabet, repeat=3):
# Slowing it down on purpose to improve performance in web terminal.
# Remove this line at your peril
time.sleep(0.001)
# Add the three letters to the first half of the password.
password = first_half_password+''.join(c)
# Try to extract the file.
print "Trying: %s" % password
# If the file was extracted, you found the right password.
if extractFile(zip_file, password):
print '*' * 20
print 'Password found: %s' % password
print 'Files extracted...'
exit(0)
# If no password was found by the end, let us know!
print 'Password not found.'

How to add a string to a file with the execution of a regular expression?

import re
import logging
x = input("enter number of bad car")
if re.match('/^[A-ZА-Я]{1}[0-9]{3}[A-ZА-Я]{2}([0-9]{0,3})?$/', x):
logging.debug("found match" + x)
with open("some.txt" , 'w') as f:
f.write(x + '\n')
else:
logging.debug("does not match")
However, nothing is written in the file some.txt
I got a logging file which wrote away 'does not match' with the following changes:
import re
import logging
logging.basicConfig(filename = ( "loggingfile.log"), level = logging.DEBUG, format = '%(message)s')
x = input("enter number of bad car")
if re.match('/^[A-ZА-Я]{1}[0-9]{3}[A-ZА-Я]{2}([0-9]{0,3})?$/', x):
logging.debug("found match" + x)
with open("some.txt" , 'w') as f:
needed = str(x + '\n')
logging.info(needed)
else:
logging.info("does not match")
So, I added:
logging.basicConfig, which set some basic configuration stuff
for your logging file (name, path, format...)
I created needed up front, which has all the needed data in it, and then wrote it away to the logging file using logging.info()
I think that that is all that I changed, hope I helped out!
I got output like this from 'logging.log' with input (the random number) 56184615:
does not match
Your regex cannot match. `/^' means a slash, followed by the start of the string. Try to remove the two slashes in the regex.

.zip file password not found (present in .txt file)

This code is verbatim from a book titled 'Violent Python'. It is meant to be a simple script that iterates through a .txt file and tries each entry as the password to a locked .zip file.
The script runs and no errors are thrown but no output is given until I
add a count variable that proves each entry is being checked. Although the correct password is in the file the 'if guess:' statement is never run.
Any help will be greatly appreciated!
import zipfile
def extractFile(zfile,password):
try:
zFile.extractall(pwd=password)
return password
except:
return
def main():
count = 0 #added for debugging
zFile = zipfile.ZipFile('secure.zip')
passFile = open('dictionary.txt')
for line in passFile.readlines():
count = count + 1 #added for debugging
password = line.strip('\n')
guess = extractFile(zFile, password)
print count #added for debugging
if guess:
print "[+] Password = " + password + "\n"
exit(0)
if __name__=='__main__':
main()

how to lookup the numbers next to character using python

this is just part of the long python script. there is a file called aqfile and it has many parameters. I would like to extract what is next to "OWNER" and "NS".
Note:
OWNER = text
NS = numbers
i could extract what is next to OWNER, because they were just text and i could extract.
for line in aqfile.readlines():
if string.find(line,"OWNER")>0:
print line
m=re.search('<(.*)>',line)
owner=incorp(m.group(1))
break
but when i try to modify the script to extract the numbers
for line in aqfile.readlines():
if string.find(line,"NS")>0:
print line
m=re.search('<(.*)>',line)
ns=incorp(m.group(1))
break
it doesnt work any more.
Can anyone help me?
this is the whole script
#Make a CSV file of datasetnames. pulseprog and, if avaible, (part of) the title
#Note: the whole file tree is read into memory!!! Do not start too high in the tree!!!
import os
import os.path
import fnmatch
import re
import string
max=20000
outfiledesc=0
def incorp(c):
#Vervang " door """ ,CRLF door blankos
c=c.replace('"','"""')
c=c.replace("\r"," ")
c=c.replace("\n"," ")
return "\"%s\"" % (c)
def process(arg,root,files):
global max
global outfiledesc
#Get name,expno,procno from the root
if "proc" in files:
procno = incorp(os.path.basename(root))
oneup = os.path.dirname(root)
oneup = os.path.dirname(oneup)
aqdir=oneup
expno = incorp(os.path.basename(oneup))
oneup = os.path.dirname(oneup)
dsname = incorp(os.path.basename(oneup))
#Read the titlefile, if any
if (os.path.isfile(root + "/title")):
f=open(root+"/title","r")
title=incorp(f.read(max))
f.close()
else:
title=""
#Grab the pulse program name from the acqus parameter
aqfile=open(aqdir+"/acqus")
for line in aqfile.readlines():
if string.find(line,"PULPROG")>0:
print line
m=re.search('<(.*)>',line)
pulprog=incorp(m.group(1))
break
towrite= "%s;%s;%s;%s;%s\n" % (dsname,expno,procno,pulprog,title)
outfiledesc.write(towrite)
#Main program
dialogline1="Starting point of the search"
dialogline2="Maximum length of the title"
dialogline3="output CSV file"
def1="/opt/topspin3.2/data/nmrafd/nmr"
def2="20000"
def3="/home/nmrafd/filelist.csv"
result = INPUT_DIALOG("CSV file creator","Create a CSV list",[dialogline1,dialogline2,dialogline3],[def1,def2,def3])
start=result[0]
tlength=int(result[1])
outfile=result[2]
#Search for procs files. They should be in any dataset.
outfiledesc = open(outfile,"w")
print start
os.path.walk(start,process,"")
outfiledesc.close()

Writing between between characters in a text file?

I have a module that i want to write into. I'm having several problems. One of which locating a string within the file. Currently I open the file, then use a for line in (filename), then do an if to determine if it finds a string, and all of that works. However before (it is commented out now) i tried to determine what position it was at using tell(). However this gave me an incorrect position, giving me 1118 i believe, instead of 660 something. So i determined the position manually to use seek.
However the second problem was, if i write to this file at the position in the file, it just overwrites all the data from thereon. I would want to insert the data instead of overwriting it.
Unless i insert a string equal in character length where i want the write to happen, it will just override most of the if statements and things like that below.
Is there any way to naively do this?
Here is the file i want to write into
# Filename: neo_usercurves.py
# Created By: Gregory Smith
# Description: A script containing a library of user created curves
# Purpose: A library to store names of all the user curves, and deletes curves
# if specified to do so
import os
import maya.cmds as mc
import module_locator
my_path = module_locator.module_path()
def usercurve_lib(fbxfile=None, remove=None):
"""All control/curve objects created by user
Keyword Arguments:
fbxfile -- (string) name of fbx file to import
remove -- (boolean) will remove an entry from the library and delete the
associated fbx file
"""
curves_dict = {
#crvstart
#crvend
}
if remove is None:
return curves_dict
elif not remove:
try:
name = mc.file(curves_dict[fbxfile], typ='FBX', i=1,
iv=True, pmt=False)
return name[0]
except RuntimeError:
return None
else:
try:
os.remove('%s\%s.fbx' %(my_path, fbxfile))
return '%s.fbx' %(fbxfile)
except OSError:
print 'File %s does not exist.' %(fbxfile)
return None
This is the code below that i'm running in a module called neo_curves.py (this is not the complete code, and 'my_path' is just the path of the current directory neo_curves.py is being run in)
def create_entry(self, crv):
"""Exports user curve to user data directory and adds entry into
neo_usercurves.py
Keyword Arguments:
crv -- (PyNode) the object to export
"""
# set settings
mel.eval('FBXExportFileVersion "FBX201400"')
mel.eval('FBXExportInputConnections -v 0')
select(crv)
mc.file('%s\userdat\%s.fbx' %(my_path, str(crv)), force=True, options='',
typ='FBX export', pr=True, es=True)
with open('%s\userdat\\neo_usercurves.py' %(my_path), 'r+') as usercrvs:
for line in usercrvs:
if line.strip() == '#crvstart':
#linepos = usercrvs.tell()
#linepos = int(linepos)
#usercrvs.seek(linepos, 0)
usercrvs.seek(665, 0)
usercrvs.write("\n "+str(crv)+" : '%s\%s' %(my_path, '"+
str(crv)+".fbx')")
break
This will give me this result below:
# Filename: neo_usercurves.py
# Created By: Gregory Smith
# Description: A script containing a library of user created curves
# Purpose: A library to store names of all the user curves, and deletes curves
# if specified to do so
import os
import maya.cmds as mc
import module_locator
my_path = module_locator.module_path()
def usercurve_lib(fbxfile=None, remove=None):
"""All control/curve objects created by user
Keyword Arguments:
fbxfile -- (string) name of fbx file to import
remove -- (boolean) will remove an entry from the library and delete the
associated fbx file
"""
curves_dict = {
#crvstart
loop_crv : '%s\%s' %(my_path, 'loop_crv.fbx') return curves_dict
elif not remove:
try:
name = mc.file(curves_dict[fbxfile], typ='FBX', i=1,
iv=True, pmt=False)
return name[0]
except RuntimeError:
return None
else:
try:
os.remove('%s\%s.fbx' %(my_path, fbxfile))
return '%s.fbx' %(fbxfile)
except OSError:
print 'File %s does not exist.' %(fbxfile)
return None
In short: on most operating systems you can not insert into files without rewriting if the lengths are not the same.
Have a look at a long discussion here: Why can we not insert into files without the additional writes? (I neither mean append, nor over-write)