I can't make multiple statement to check two statement - python-3.x

I am making a code in python to make password and save in the text file, if the user enters the same password in the file, the error code will appear. The problem is that although I made a two statement to check the password is valid and there is no same password in the text file, the statement of the one that will check text file to find same file. Can you tell me where I get mistake?
def InputString():
String = str(input("Enter your password. :"))
return String
def CheckPassword(Password):
##I declared "Index","Upper","Lower","Digit" and "Other" as Integer.
##In python, there is no data type for
##"char", so We use string instead.
##I use "variable" as boolean for checking password.
Upper = 0
Lower = 0
Digit = 0
Other = 0
variable = False
for index in range(len(Password)):
NextChar = (Password[index:index+1])
if NextChar >= "A" and NextChar <= "Z":
Upper = Upper + 1
elif NextChar >= "a" and NextChar <= "z":
Lower = Lower + 1
elif NextChar >= "0" and NextChar <= "9":
Digit = Digit + 1
else :
Other = Other + 1
if Upper > 1 and Lower >= 5 and (Digit - Other) > 0:
variable = True
else :
variable = False
return variable
def CheckThrough (Password):
FileP = open("Password.txt","r")
if FileP.mode == 'r':
contents = FileP.read()
if contents == Password:
usable = False
else :
usable = True
FileP.close()
return usable
###The main programs starts here###
print("Enter the password.")
print("You must add at least 1 upper character.")
print("5 lower character")
print("and the difference between numeric character and symbols must be more than 1.")
variable = False
usable = False
while variable == False and usable == False:
Password = InputString()
variable = CheckPassword(Password)
if variable == True:
usable = CheckThrough(Password)
if usable == True:
print("You can use the password.")
elif usable ==False :
print("The password you entered is already used.")
else :
print("The error is ocuured.")
else :
print("You can't use this password, try again.")
print("Your password is",Password)
FileP = open("Password.txt","a+")
FileP.write(Password)
FileP.write("\n")
FileP.close()

you need to add .strip() so it has no spaces e.g String = str(input("Enter your password. :").strip()). When you enter in the password there's a space but that doesn't get saved to the file thus it always reads it as a new password.
my input = Enter your password. :Kingdom1hearTs
The input into the program = " Kingdom1hearTs"
(used print to see what was being entered into the system)
and the if contents == Password: needs to be if Password in contents:otherwise your seeing if Password is the same as the whole txt file.
NextChar = (Password[index:index+1])
if NextChar >= "A" and NextChar <= "Z":
Upper = Upper + 1
elif NextChar >= "a" and NextChar <= "z": #had the wrong indentation
Lower = Lower + 1
elif NextChar >= "0" and NextChar <= "9":
Digit = Digit + 1
else :
Other = Other + 1

Related

python salted hashes producing unexpected results using sha1 and md5

I am trying to write a simple python script to hash a list of passwords and compare the resulting hashes against a list. I know that these 4 hashes match 4 of the listed passwords hashed with sha1 and salted with either md5(1), md5(2), md5(3), md5(4) or md5(5). My code prints 50 unique hashes however none of them match and I can't figure out why. Any help is appreciated.
import hashlib
possibleHashes = ["9537935389a343a4fbd831b621b00661b91a5172", "576b1b134cb89b0f8a6c4dd1698479a1151b0e63", "5d7196b530fdd24b8faaaecbaa6b08a29daa1304", "d6acda01abcfe8afd510b96c1d0a1645ea4c40b8"]
possiblePasswords = ["123456", "123456789", "qwerty", "password", "12345", "qwerty123", "1q2w3e", "12345678", "111111", "1234567890"]
hashesFound = 0
def hashPassword(saltNum, password):
password = password.encode('utf-8')
encryptedPassword = hashlib.sha1(hashlib.md5(int.to_bytes(saltNum)).digest() + password).hexdigest()
return encryptedPassword
i = 0
while (i < len(possiblePasswords)):
j = 0
print("I: ", i)
while (j < 5):
j += 1
print("J: ", j, " " + hashPassword(j, possiblePasswords[i]))
if (hashPassword(j, possiblePasswords[i]) in possibleHashes):
print(possiblePasswords[i], "\n" + hashPassword(j, possiblePasswords[i]))
i += 1
if i == 10:
print("\nHash Matches Found: ", hashesFound, "\n")
quit()
Edit:
I have tried making saltNum a string and encoding it before it's used in the md5 call however it has made no difference.

I want to be able to restart my program after a user input error

I am making a program using the python module pypokedex, to make a program that will ask for a pokemon's name, and the generation, and pull up a https://www.serebii.net/ page about it. But, if the user spells a pokemon incorrectly, it just errors and shuts down the program. I want it to restart the program.
I also have it so that if the code succeeded, it will still loop, the problem is when it fails, (again, this is only a problem if the user spells a name wrong)
the reason this:Asking the user for input until they give a valid response doesn't work is because I need to have it be certain words, not a range of numbers.
import pypokedex
import webbrowser
while 1==1:
name = input("What pokemon are you searching for? ")
p = pypokedex.get(name = name)
zero = 3-len(str(p.dex))
if(zero == 2):
num = "00" + str(p.dex)
if(zero == 1):
num = "0" +str(p.dex)
if(zero == 0):
num = str(p.dex)
ngen = input("What generation number are you looking for? ")
if(ngen == str(1)):
gen = "pokedex"
if(ngen == str(2)):
gen ="pokedex-gs"
if(ngen == str(3)):
gen = "pokedex-rs"
if(ngen == str(4)):
gen = "pokedex-dp"
if(ngen == str(5)):
gen = "pokedex-bw"
if(ngen == str(6)):
gen = "pokedex-xy"
if(ngen == str(7)):
gen = "pokedex-sm"
url = "https://www.serebii.net/" + str(gen) + "/" + str(num) + ".shtml"\
webbrowser.open(url , 2)

Python 3: How to exit loop without stopping function

I am a complete newbie and have tried solving this problem (with my own head and with online research) for the last 5 hours.
Below is a snippet of a function we have written to simulate a game. We want to offer the ooportunity to start a new round - meaning if a player hits "b", the game should start again at the beginning of the range (0, players). But right now it just goes onto the next player in the range (if player 1 enters "b", the program calls player 2)
players = input(4)
if players in range(3, 9):
for player in range(0, players):
sum_points = 0
throw_per_player_counter = 0
print("\nIt is player no.", player+1, "'s turn!\n")
print("\nPress 'return' to roll the dice.\n"
"To start a new round press 'b'.\n"
"Player", player+1)
roll_dice = input(">>> ")
if roll_dice == "b":
player = 0
throw_per_player_counter = 0
sum_points = 0
print("\n * A new round was started. * \n")
I have tried return and break, also tried to put it all in another while-loop... failed. Break and return just ended the function.
Any hints highly appreciated!
you could change the for loop to a while loop. instead of using a range, make player a counter
players = 4
if 3 <= players < 9:
player = 0 # here's where you make your counter
while player < players:
sum_points = 0
throw_per_player_counter = 0
print("\nIt is player no.", player+1, "'s turn!\n")
print("\nPress 'return' to roll the dice.\n"
"To start a new round press 'b'.\n"
"Player", player+1)
roll_dice = input(">>> ")
player += 1 # increment it
if roll_dice == "b":
player = 0 # now your reset should work
throw_per_player_counter = 0
sum_points = 0
print("\n * A new round was started. * \n")

Counting substring that begin with character 'A' and ends with character 'X'

PYTHON QN:
Using just one loop, how do I devise an algorithm that counts the number of substrings that begin with character A and ends with character X? For example, given the input string CAXAAYXZA there are four substrings that begin with A and ends with X, namely: AX, AXAAYX, AAYX, and AYX.
For example:
>>>count_substring('CAXAAYXZA')
4
Since you didn't specify a language, im doing c++ish
int count_substring(string s)
{
int inc = 0;
int substring_count = 0;
for(int i = 0;i < s.length();i++)
{
if(s[i] == 'A') inc++;
if(s[i] == 'X') substring_count += inc;
}
return substring_count;
}
and in Python
def count_substring(s):
inc = 0
substring_count = 0
for c in s:
if(c == 'A'): inc = inc + 1
if(c == 'X'): substring_count = substring_count + inc
return substring_count
First count number of "A" in the string
Then count "X" in the string
using
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Dim cnt As Integer = 0
For Each c As Char In value
If c = ch Then cnt += 1
Next
Return cnt
End Function
then take each "A" as a start position and "X" as an end position and get the substring. Do this for each "X" and then start with second "A" and run that for "X" count times. Repeat this and you will get all the substrings starting with "A" and ending with "X".
Just another solution In python:
def count_substring(str):
length = len(str) + 1
found = []
for i in xrange(0, length):
for j in xrange(i+1, length):
if str[i] == 'A' and str[j-1] == 'X':
found.append(str[i:j])
return found
string = 'CAXAAYXZA'
print count_substring(string)
Output:
['AX', 'AXAAYX', 'AAYX', 'AYX']

Python while/if statements not working

I am currently learning Python and I am trying to get this game to work. Basically I assigned a word to be guessed and then sliced the word and assigned it to several other variables. Basically, each variable assigned as "letterx" is a letter which makes up part of the string variable word. The problem is getting the while statement with nested if statements to work. For some reason I can't get the guess input to equal letterx. All I get when I run the code is "No." and then the amount of turns left. However, I can't get the elif statement to work. Pretty much everything else works. I'm used to programming in Java and I am fairly new to Python so any tips or help would be greatly appreciated. Thank you for your time and help! Here's the code:
#Guess The Word
word = "action"
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""
position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5
letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]
print("Welcome to Guess the Word!\n")
count = 6
while(count != 0):
guess = input("Take a guess: \n")
if(guess != letter1 or guess != letter2 or guess != letter3 or guess !=
letter4 or guess != letter5 or guess != letter6):
count -= 1
print("No.\n")
print("Turns left: \n", count)
elif(guess == letter1 or guess == letter2 or guess == letter3
or guess == letter4 or guess == letter5 or guess == letter6):
count -= 1
print("Yes.\n")
if(count == 0):
print("Your turns are up, what do you think the word is?")
guess = input("The word is...: \n")
if(guess == word):
print("You win! That's the word")
elif(guess != word):
print("Sorry, you lose.")
Here's the program running in the Python shell:
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Welcome to Guess the Word!
Take a guess:
a
No.
Turns left:
5
Take a guess:
c
No.
Turns left:
4
Take a guess:
t
No.
Turns left:
3
Take a guess:
i
No.
Turns left:
2
Take a guess:
o
No.
Turns left:
1
Take a guess:
n
No.
Turns left:
0
Your turns are up, what do you think the word is?
The word is...:
action
You win! That's the word
Let's say guess equals letter1. Then even though
guess == letter1, the first condition is still True since guess != letter2. And similarly, no matter what guess is, there is some letter (amongst letter1, letter2, etc.) which it is not equal.
So the first if condition is always True.
Instead, you could use
while(count != 0):
guess = input("Take a guess: \n")
if not guess in word:
count -= 1
print("No.\nTurns left: \n", count)
else:
count -= 1
print("Yes.\n")
By the way, it should be entirely possible to code the game without defining letter1, letter2, etc. All this code should be deleted:
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""
position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5
letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]
Just use word[0] in place of letter1, and word[1] in place of letter2, etc.
And note you may not even need word[0], word[1]. For example,
with Python you can use
guess in word
instead of
guess in (word[0], word[1], word[2], word[3], word[4], word[5])
It's not only a lot less typing, it is more general, since guess in word does the right thing with words of any length.

Resources