Storing incorrect passwords on .txt file - Python 2.7 - python-2.7

I am creating a python program which stores it in a list, then records in a text file called wrongpasswords.txt.
The program should ask the user for input by saying 'Please enter your password: '. The correct password will always be 'rusty' but the user can of course enter any String. And also, how do I add to my program that the number of characters the user inputs wrong is also stored for each incorrect password?
Please do mind me as I am a beginner in programming and python.
Please see my code below:
enteredPass = raw_input("Enter your password: ")
incorrectPass= file("wrongpasswords.txt","w")
counter = 0
for i in range(0, counter+1):
if enteredPass != "rusty":
counter = counter +1
incorrectPassO = open("wrongpasswords.txt","w")
incorrectPassO.write("Incorrect password" +str(counter)+": " + enteredPass + "\n")
incorrectPassO.close()
enteredPass = raw_input("Enter your password: ")
else:
incorrectPassO = open("wrongpasswords.txt","w")
incorrectPassO.write("Correct password entered on the " + str(counter)+"th entry")
incorrectPassO.close()

If I understood correctly you're trying to create a simple login program that counts the wrong login attempts? This should work:
counter = 0
correct_answer_entered = False
while not correct_answer_entered:
enteredPass = raw_input("Enter your password: ")
counter = counter + 1
if enteredPass != "rusty":
incorrectPassO = open("wrongpasswords.txt","a")
incorrectPassO.write("Incorrect password" +str(counter)+": " + enteredPass + "\n")
incorrectPassO.close()
else:
incorrectPassO = open("wrongpasswords.txt","a")
incorrectPassO.write("Correct password entered on the " + str(counter)+"th entry")
incorrectPassO.close()
correct_answer_entered = True
The points I fixed in your code that you should notice:
I replaced the "w" with an "a" where you open the file, since "w" makes it write over what's already wroten in the file, while "a" appends after what's there.
I replaced the for loop with a while, what you did was a range from 0 to 1, so the loop would exit after the first round, I added a boolean value (correct_answer_entered), to indicate if the correct password was entered, and keeps going if it wasn't.
I moved the "counter = counter + 1" outside of the if statement, since the number of attempts is not related to wither the password is correct or not, the way you did it if the password was correct at the first attempt it'd say 0th attempt instead of 1th.
overrall your code is pretty nice and it's good to see new people getting into programming ^.^

Related

why does the while loop not work?

I'm creating a program that takes in the users grade(A-F), health(0-100) and economic output(0-100). I need a while loop for when the user inputs a value wrong e.g A for health. why does the loop keep repeating? how do I do this for the grade as well?
name = raw_input(' Enter your name: ')
grade = raw_input(' Enter your grade: ')
string_two = raw_input(' Enter your economic out put: ')
while string_two not in range (0,100):
print 'please enter a value between 0 and 100.'
string_two = raw_input(' Enter your economic out put: ')
string_one = raw_input(' Enter your health: ')
while string_one not in range (0,100):
print 'please enter a value between 0 and 100.'
string_one = raw_input(' Enter your health: ')
health == int(string_one)
economic_output == int(string_two)
if economic_output > 85:
print name + ' you are exceptional! Welcome aboard!'
elif grade == 'A':
print name + ' you are exceptional! Welcome aboard!'
elif economic_output > 60:
if health > 60:
if grade == 'B' or 'C':
print 'Congatulations ' + name +'!' + ' Come aboard!'
else:
print 'Sorry, ' + name + ' but you dont meet the criteria and cammot be permitted to board. '
The while loop keeps repeating because raw_input always returns a string object, regardless if you typed digits only or something else. string_two not in range (0,100) is always true because a string cannot be in any range of ints.
So what you can do. If I were you, I would define a function which would ask the user to enter something in a while loop until his input satisfies some pattern (just as you are trying to do in your code) and convert it to a specific type if necessary. There is a very useful tool to check a string for matching some pattern, it is called regular expressions (RE).
import re
def inputAndValidate(prompt, pattern, convertFunc=str):
result = raw_input(prompt)
while re.match(pattern, result) is None:
print 'Input pattern is "' + pattern + '". Please enter a string matching to it.'
result = raw_input(prompt)
return convertFunc(result)
Putting a piece of code being used several times to a function is a good practice. So here I defined a function called inputAndValidate with 2 mandatory parameters - a prompt to be displayed for user to let him understand what do you want from him, and the pattern to check his input. The third parameter is optional - it's a function which will be applied to the user input. By default, it's str, a function converting something to a string. User input is already a string, so this function will do nothing, but if we need an int, we'll pass int as the third parameter and get an int from the inputAndValidate function, and so on.
re.match(pattern, string) returns a match object if the string did match the pattern, and None if it didn't. See official re documentation for more information.
Usage of the function
name = inputAndValidate('Enter your name: ', r'.+')
# This pattern means any string except empty one. Thus we ensure user will not enter an empty name.
grade = inputAndValidate('Enter your grade (A-F): ', r'[A-F]')
# This pattern means a string containing only one symbol in the A-F range (in the ASCII table).
economic_output = inputAndValidate('Enter your economic output (0-100): ', r'\d{1,3}', int)
# This pattern means a string containing from one to three digits. `int` passed to the third parameter means the result will be an int.
health = inputAndValidate('Enter your health (0-100): ', r'\d{1,3}', int)
# Same as the previous one.
re module documentation also contains information about the regular expressions language, it can help you understand the patterns I used.

Input validation python 2.7.13

I am trying to validate input that is going into a list. The input needs to be an integer. How I have it works if I input an integer or a single letter. but if I enter something like 'qw' the program crashes. What can I do to better validate the input? Here is my code:
def getPints(pints):
counter = 0
while counter < 7:
pints[counter] = raw_input("Enter the number of pints donated: ")
check = isinstance(pints[counter], int)
while check == False:
print "Please enter an integer!"
pints[counter] = input("Enter the number of pints donated: ")
counter = counter + 1
As written, check will always evaluate to False, because raw_input() only returns a string, never an integer. Then you'll get stuck in an infinite while loop, because you don't update check in it.
Instead of isinstance, use the string isdigit() method.
check = pints[counter].isdigit()
You'll also need to re-evaluate check inside the loop. But really, you don't need check at all.
pints[counter] = raw_input("Enter the number of pints donated: ")
while not pints[counter].isdigit():
print "Please enter an integer!"
pints[counter] = raw_input("Enter the number of pints donated: ")
I suspect you also want to convert pints[counter] to an int once you have a suitable input.
You're using the LBYL method (Look Before You Leap). You can also use the EAFP (Easier to Ask Forgiveness than Permission) method by just trying to convert the input to an int and catching the exception if the input is bad:
while True:
try:
pints[counter] = int(raw_input("Enter the number of pints donated: "))
break
except ValueError:
print "Please enter an integer!"

Python: Trying to loop through a string to find matching characters

I am trying to create a simple "guess the word" game in Python. My output is something like:
String: _____ _____
Guess a word: 'e'
String:_e__o __e_e
Guess a word: 'h'
(and so on)
String: hello there
I have a function to do this, and within this function I have this code:
def guessing(word):
count = 0
blanks = "_" * len(word)
letters_used = "" #empty string
while count<len(word):
guess = raw_input("Guess a letter:")
blanks = list(blanks)
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz "):
print "Please only guess letters!"
#Checks if guess is found in word
if guess in word and guess not in letters_used:
x = word.index(guess)
for x in blanks:
blanks[x] = guess
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-counter
print "There are", str(word.count(guess)) + str(guess)
guess is the raw input I get from the user for a guess, and letters_used is just a collection of guesses that the user has already input. What I'm trying to do is loop through blanks based on the word.index(guess). Unfortunately, this returns:
Guess a letter: e
e___
Yes, there are 1e
Help would be much appreciated!
Your code was almost correct. There were few mistakes which I have corrected:
def find_all(needle, haystack):
"""
Finds all occurances of the string `needle` in the string `haystack`
To be invoked like this - `list(find_all('l', 'hello'))` => #[2, 3]
"""
start = 0
while True:
start = haystack.find(needle, start)
if start == -1: return
yield start
start += 1
def guessing(word):
letters_uncovered_count = 0
blanks = "_" * len(word)
blanks = list(blanks)
letters_used = ""
while letters_uncovered_count < len(word):
guess = raw_input("Guess a letter:")
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz"):
print "Please only guess letters!"
if guess in letters_used:
print("This character has already been guessed correctly before!")
continue
#Checks if guess is found in word
if guess in word:
guess_positions = list(find_all(guess, word))
for guess_position in guess_positions:
blanks[x] = guess
letters_uncovered_count += 1
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-letters_uncovered_count
print "There are", str(word.count(guess)) + str(guess)
else:
print("Wrong guess! Try again!")

Getting error "NameError: name 'letter' is not defined"

I'm fairly new to python and don't know much but i tried to make a program that sees how fast it can guess a string in this case a password. I tried to create an individual variable for each letter by making a loop that sets the variable. (I added the print letter1... at the end so i can see if it works).Then when i went to test it i got this error.
letter[x] = password[x - 1:-(len(password)-1)]
NameError: name 'letter' is not defined
print "Password guesser"
password = raw_input('Enter Password (1-30 carechters only): ')
passwordLength= len(password)
for x in range(0,passwordLength):
letter[x] = password[x - 1:-(len(password)-1)]
print letter1
print letter2
print letter3
Since you're assigning letters with dictionary syntax, you may want to declare the letter variable as a dictionary: letter = {}, then output it as a dictionary. This may get you in the direction you want to go:
letter = {}
for x in range(passwordLength):
letter[x] = password[x - 1:-(passwordLength-1)]
print letter[0]
print letter[1]
print letter[2]

Converting integers for loop in Python - Loop ignores function value?

I'm working on a number guessing game and can't seem to get my loop to work while utilizing a function. I was manually typing out conversion under each if/elif in the block, but that was tedious and only checking for integers - string inputs couldn't read and broke the system.
I tried creating a conversion function to check the values and determine if it was an integer or string and change the variable type accordingly. However this results in an infinite loop fo line 18.
Can someone point out what I'm doing wrong here?
Heads up, I do have the random.py script from Python.org and am importing it so the game plays differently each time.
from random import randint
print 'Hello, my name is Skynet. What\'s yours?'
myName = raw_input()
print 'Good to meet you, ' + myName + '! Let\'s play a game.'
print 'I\'m thinking of a number between between 1 and 20, can you guess it?'
pcNum = randint(1,20)
myNum = raw_input()
def checkNum(myNum):
try:
int(myNum)
except ValueError:
returnVAL = 'That\'s not a number I know, try again.'
else:
returnVAL = int(myNum)
return returnVAL
while myNum != pcNum:
if myNum > pcNum:
print 'That\'s too high! Try again.'
myNum = raw_input()
checkNum(myNum)
else:
print 'That\'s too low! Try again.'
myNum = raw_input()
checkNum(myNum)
if myNum == pcNum:
print 'Good job, my number was ' + str(pcNum) + ' too! Good job, ' + myName
Any input is appreciated. I did some browsing here and got some a better idea of how to pull this off, or so I thought, and now here I am asking. First post!
print "I'm thinking of a number between between 1 and 20, can you guess it?"
while True:
guess = raw_input("What's your guess? ")
try:
guess = int(guess, 10)
except ValueError:
print "That's not a number I know, try again."
continue
if guess == pcNum:
...
break
elif guess > pcNum:
...
else:
...
Don't mix responsibilities. It is wrong to have myNum be both a number and an error message.
Also, think what you want to do when a user enters a non-number. In your case, the user's guess is "That's not a number I know, try again.", and it's being compared to pcNum; this makes no sense. If it was me, I would want the user to enter the number again. So rather than checkNum, I want input_valid_integer:
def input_valid_integer():
result = None
while result is None:
text = raw_input()
try:
result = int(text)
except ValueError:
print 'That\'s not a number I know, try again.'
return result