This is my entire code block but I am just having trouble making the scores show after the game is played. The score is being added to the file correctly, but when I go to print the scores, the new score is not appearing, even though I have appended it. How can I fix my code to make it show up? I am new to coding so anything helps. I think this is an easily solvable error, but I don't know how to fix it. Thank you!
#STAGE 1: Opening the files and grabbing data
users_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt"
passwords_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt"
scoreslist_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt"
#Define functions for future use
def get_file_contents(file_path):
return [line.strip() for line in open(file_path)]
scoreslist = get_file_contents(scoreslist_path)
def add_file_contents(file_path, contents):
with open(file_path, "a") as file:
file.write(contents)
def login_user(new_account=False):
usernameslist = get_file_contents(users_path)
passwordslist = get_file_contents(passwords_path)
#Determine if user needs to create a new account:
if new_account:
response = 'y'
else:
response = input("-"*50 + "\nWelcome! Do you have an account (y/n)? ")
print("-"*50)
#If user has an account:
if response == "y":
goodlogin = False
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for id in range(len(usernameslist)):
if username == usernameslist[id] and password == passwordslist[id]:
goodlogin = True
if goodlogin:
print(print_in_green + "Access granted!" + print_default)
#Ask if user would like to view leaderboard
leaderboard = input("Would you like to view the leaderboard (y/n)? ")
#If thet want to see leaderboard:
if leaderboard == "y":
print("-"*50 + "\n" + print_in_blue + "Here is the leaderboard!\n" + print_default + "-"*50)
for c in range(0, len(scoreslist)-1):
max = scoreslist[c]
index_of_max = c
for i in range (c+1, len(scoreslist)):
if (scoreslist[i] > max):
max = scoreslist[i]
index_of_max = i
aux = scoreslist[c]
scoreslist[c] = max
scoreslist[index_of_max] = aux
#print(scoreslist)
print(*scoreslist, sep = "\n")
print("-"*50)
#If they don't want to see scores:
else:
print("OK!")
#If they type the wrong username or password:
else:
print(print_in_red + "Incorrect Login credentials, please try again by restarting." + print_default)
#If user does not have account:
else:
goodlogin2 = False
newusername = input("What is your new username? ")
#Check to see if username already exists
if newusername in usernameslist:
print("This username is already taken. Please try another.")
else:
goodlogin2 = True
print(print_in_green + "Ok, please continue!" + print_default)
#Check to see if two passwords match
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again: ")
if newpassword == newpasswordagain:
print("Please follow the instructions to log in with your new credentials.")
add_file_contents(users_path, '\n' + newusername)
add_file_contents(passwords_path, '\n' + newpassword)
login_user(new_account=True)
else:
print(print_in_red + "Your passwords do not match. Please try again." + print_default)
login_user()
#Playing the game (rolling dice):
import random
min = 1
max = 6
sum = 0
#Ask user if they want to play
game_response = input("Would you like to play the game by rolling your dice (y/n)? ")
if game_response == "y":
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dices...")
print("The values are:")
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(print_in_pink)
print(int(dice1))
print(int(dice2))
print(print_default)
score = (int(dice1) + int(dice2))
sum = sum + score
roll_again = input("Your score for this round is " + str(score) + ". Roll the dices again (y/n)? ")
else:
print("Ok!")
print("Your final score is " + print_in_pink + str(sum) + print_default + "!")
add_file_contents(scoreslist_path, '\n' + str(sum))
scoreslist.append(str(sum))
leaderboard_again = input("Would you like to view the leaderboard again (y/n)? ")
if leaderboard_again == "y":
print("-"*50 + "\n" + print_in_blue + "Here is the leaderboard!\n" + print_default + "-"*50)
for c in range(0, len(scoreslist)-1):
max = scoreslist[c]
index_of_max = c
for i in range (c+1, len(scoreslist)):
if (scoreslist[i] > max):
max = scoreslist[i]
index_of_max = i
aux = scoreslist[c]
scoreslist[c] = max
scoreslist[index_of_max] = aux
#print(scoreslist)
print(*scoreslist, sep = "\n")
print("-"*50)
#If they don't want to see scores:
else:
print("OK. Thanks for logging in!")
You never update scoreslist to have sum in it (either by appending it or by reading scoreslist out of the file again). Add a line that adds sum to scoreslist:
add_file_contents(scoreslist_path, '\n' + str(sum))
scoresline.append(sum)
Related
I need help, I don't know hot wo change the value of a cell and save it to the file. I just want to make it so when the user has verified the o changes to 1 in the verified column. The information looks weird because it is encrypted. All of the code for verification and cell stuff can be found in the Verify() function.
The csv file:
The whole code:
import pandas as pd
import re
import csv
import smtplib
import math
import random
from email.message import EmailMessage
#====================================================================================================#
def Register():
firstname = input("Enter your first name: ").lower()
surname = input("Enter your surname: ").lower()
age = input("Enter your age: ")
if not str.isdecimal(age):
print("Age must be a number. Please try again.")
age = input("Enter your age: ")
email = input("Enter your email: ").lower()
regex = "^[a-z0-9]+[\._]?[a-z0-9]+[#]\w+[.]\w{2,3}$"
if not re.search(regex, email):
print("Invalid email please try again.")
email = input("Enter your email: ").lower()
password = input("Enter a strong password: ")
if len(password) < 6:
print("Password should be between 6 to 18 characters long.")
password = input("Enter a strong password: ")
username = firstname[:1] + surname + age
username.lower()
print("\nYour username is: " + username + "\nYour email is: " + email + "\nYour password is: " + password + "\nYour firstname is: " + firstname + "\nYour surname is: " + surname + "\nYour age is: " + age)
encryptedFirstname = "".join(chr(ord(char)+3) for char in firstname)
encryptedSurname = "".join(chr(ord(char)+3) for char in surname)
encryptedAge = "".join(chr(ord(char)+3) for char in age)
encryptedEmail = "".join(chr(ord(char)+3) for char in email)
encryptedPassword = "".join(chr(ord(char)+3) for char in password)
encryptedUsername = "".join(chr(ord(char)+3) for char in username)
verified = "0"
AccountInfo = [encryptedFirstname, encryptedSurname, encryptedAge, encryptedEmail, encryptedPassword, encryptedUsername, verified]
if not str.isdecimal(age) or len(password) < 6 or not re.search(regex, email):
print("Error occured, please make sure all your details are valid.")
MainMenu()
else:
try:
open("Accounts.csv", "x")
with open("Accounts.csv", "a", newline = "") as file:
writer = csv.writer(file)
writer.writerow(["Firstname", "Surname", "Age", "Email", "Password", "Username, Verified"])
writer.writerow(AccountInfo)
file.close()
print("Account successfully made. Please verify your email now.")
MainMenu()
except:
with open("Accounts.csv", "a", newline = "") as file:
writer = csv.writer(file)
writer.writerow(AccountInfo)
file.close()
print("Account successfully made. Please verify your email now.")
MainMenu()
#====================================================================================================#
def Login():
User0 = input("Username: ").lower()
Pass0 = input("Password: ")
encryptedPassword = "".join(chr(ord(char)+3) for char in Pass0)
encryptedUsername = "".join(chr(ord(char)+3) for char in User0)
try:
file = open("Accounts.csv", "r")
except:
print("Account doesn't exist. Please register an account.")
MainMenu()
detailsList = []
line = 0
for line in file:
detailsList.append(line.rstrip('\n').split(","))
loggedIn = 0
for details in detailsList:
if encryptedUsername == details[5] and encryptedPassword == details[4] and details[6] == "0":
loggedIn = 1
break
if encryptedUsername == details[5] and encryptedPassword == details[4] and details[6] == "1":
loggedIn = 2
break
if loggedIn == 1:
print("You need to verify your account.")
MainMenu()
if loggedIn == 2:
print("Successfully logged in.")
MainMenu()
elif loggedIn == 0:
print("Incorrect details.")
MainMenu()
#====================================================================================================#
def Verify():
User1 = input("Username: ").lower()
Pass1 = input("Password: ")
encryptedUsername1 = "".join(chr(ord(char)+3) for char in User1)
encryptedPassword1 = "".join(chr(ord(char)+3) for char in Pass1)
try:
file = open("Accounts.csv", "r")
except:
print("Account doesn't exist. Please register an account.")
MainMenu()
detailsList = []
line = 0
for line in file:
detailsList.append(line.split(","))
loggedIn = False
for details in detailsList:
if encryptedUsername1 == details[5] and encryptedPassword1 == details[4]:
decryptedEmail = "".join(chr(ord(char)-3) for char in details[3])
loggedIn = True
UserEmail = decryptedEmail
break
LineNumber = 0
with open("Accounts.csv", 'r') as file:
for line in file:
LineNumber += 1
if encryptedUsername1 in line:
break
if loggedIn == True:
print("Verifying Email Address...")
digits = "0123456789"
CODE = ""
msg = EmailMessage()
smtp = smtplib.SMTP("smtp.gmail.com", 587)
for i in range(6):
CODE += digits[math.floor(random.random()*10)]
msg.set_content(f"Your code is: {CODE}\nThis code expires in 5 minutes.")
msg["Subject"] = "PyDatabase: Verification"
msg["From"] = "me#gmail.com"
msg["To"] = UserEmail
smtp.starttls()
smtp.login("me#gmail.com", "password")
smtp.send_message(msg)
smtp.quit()
InputedCode = input("Enter Your Code >>> ")
if InputedCode == CODE:
print("Verified!")
LineNumber = LineNumber - 1
DataFrame = pd.read_csv("Accounts.csv")
Pos = DataFrame.loc[LineNumber, "Verified"]
print(Pos)
else:
print("Wrong code, try again!")
MainMenu()
else:
print("Incorrect password or username. Please try again.")
MainMenu()
#====================================================================================================#
def MainMenu():
print("#------------------#" + "\n| 1 - Register |" + "\n| 2 - Login |" + "\n| 3 - Verify |" + "\n#------------------#")
choice = input(">>> ")
if choice == "1":
Register()
elif choice == "2":
Login()
elif choice == "3":
Verify()
else:
print("Invalid choice.")
#====================================================================================================#
MainMenu()
Use df.loc[desired_row, desired_column] = specified_value to set the value, and use pd.to_excel(desired_file_name) to save the file.
I fix it just had to subtract 2 from the line number to get to the right line in the verify function.
LineNumber -= 2
How would I ask the user if they want to play and then start the simulation? And if they don't the program prints a goodbye message. And print the total number of times the coin was flipped at the end.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
while True:
try:
time_flip= int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
def random_flip():
return random.randint(0, 1)
def count_for_sides():
count_head=0
count_tail=0
times=num_of_input()
while True:
if count_head + count_tail == times:
break
else:
if random_flip()==0:
count_head+=1
else:
count_tail+=1
print()
print(str(count_head) + " came up Heads")
print(str(count_tail) + " came up Tails")
count_for_sides()
You can get input from the user before calling the count_for_sides method and call it if they opt in.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
while True:
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
def random_flip():
return random.randint(0, 1)
def count_for_sides():
count_head=0
count_tail=0
times=num_of_input()
while True:
if count_head + count_tail == times:
break
else:
if random_flip()==0:
count_head+=1
else:
count_tail+=1
print()
print(str(count_head) + " came up Heads")
print(str(count_tail) + " came up Tails")
userWantsToPlay = input("Do you want to play this game? (Y/n): ")
if (userWantsToPlay == 'Y'):
count_for_sides()
print("Welcome to English, please enter your name,age,and password.")
print("If you have previously signed in, enter using the same name,age,and password")
name = input("Please enter your name: ")
age = input("Now please enter you age: ")
username = name[0:3] + age
password = input("Now please create a password: ")
userpass = (username+","+password)
check = open("logins.txt")
string = check.read().strip().split()
if userpass in string:
print("You have logged in as",username,"The questions will now start. \n")
else:
newlog = input("Looks like you dont have an account with those details, Would you like to create a new one? Y/N: ")
if newlog == "Y" or newlog == "y" or newlog == "yes" or newlog == "Yes":
f = open("logins.txt","a+")
chosen = f.write(username+","+password+"\n")
print("The username",username,"and password",password,"have now been saved, the questions will now start \n")
f.close()
else:
print("Please either sign in or log in and try again.")
welcome()
import random
f = open("English.txt","r")
points = 0
for line in f:
currentLine = line.split(",")
q = currentLine[0]
answer = currentLine[1]
questions = currentLine[1:-1]
random.shuffle(questions)
print(q)
for i in range(len(questions)):
print (i+1,":",questions[i])
userAnswer = int(input("Make a selection :"))
if answer == questions[userAnswer-1]:
points = (points+1)
print ("CORRECT, You have",points,"points")
str(points)
else:
print ("INCORRECT")
f.close()
f = open("scores.txt","a+")
score = f.write(username+","+password+","+points+"\n") #It is giving a type error about this line and I cant seem to understand why
f.close()
The error shown is:
line 193, in english
score = (username+","+password+","+points+"\n")
TypeError: must be str, not int
Please let me know if you have a better way of writing the scores into a text file. THank you.
Replace the error line with: score = f.write(username+","+password+","+str(points)+"\n")
Starting at "#If user does not have account:" the code is printing the output multiple times. I just want it to print the output (either the username is taken or they can continue) once. Then, I want the password to be typed twice and compared to make sure that they match. Can you help me fix this issue?
import colorama
colorama.init()
print_in_green = "\x1b[32m"
print_in_red = "\x1b[31m"
print_in_blue = "\x1b[36m"
print_in_pink = "\x1b[35m"
print_default = "\x1b[0m"
#STAGE 1: Opening the files and grabbing data
users_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt"
passwords_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt"
scoreslist_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt"
def get_file_contents(file_path):
return [line.strip() for line in open(file_path)]
scoreslist = get_file_contents(scoreslist_path)
def add_file_contents(file_path, contents):
with open(file_path, "a") as file:
file.write(contents)
def login_user(new_account=False):
usernameslist = get_file_contents(users_path)
passwordslist = get_file_contents(passwords_path)
if new_account:
response = 'y'
else:
response = input("-"*50 + "\nWelcome! Do you have an account (y/n)? ")
print("-"*50)
#If user has an account:
if response == "y":
goodlogin = False
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for id in range(len(usernameslist)):
if username == usernameslist[id] and password == passwordslist[id]:
goodlogin = True
if goodlogin:
print(print_in_green + "Access granted!" + print_default)
#Ask if user would like to view leaderboard
leaderboard = input("Would you like to view the leaderboard (y/n)? ")
#If thet want to see scores:
if leaderboard == "y":
print("-"*50 + "\n" + print_in_blue + "Here is the leaderboard!\n" + print_default + "-"*50)
for c in range(0, len(scoreslist)-1):
max = scoreslist[c]
index_of_max = c
for i in range (c+1, len(scoreslist)):
if (scoreslist[i] > max):
max = scoreslist[i]
index_of_max = i
aux = scoreslist[c]
scoreslist[c] = max
scoreslist[index_of_max] = aux
#print(scoreslist)
print(*scoreslist, sep = "\n")
print("-"*50)
#If they don't want to see scores:
else:
print("OK. Thanks for loging in!")
else:
print(print_in_red + "Incorrect Login credentials, please try again by restarting." + print_default)
#If user does not have account:
else:
goodlogin2 = False
newusername = input("What is your new username? ")
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
print("Ok, please continue!")
else:
print("This username is already taken. Please try another.")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
if newpassword == newpasswordagain:
print("Please follow the instructions to log in with your new credentials.")
add_file_contents(users_path, '\n' + newusername)
add_file_contents(passwords_path, '\n' + newpassword)
login_user(new_account=True)
else:
print("Your passwords do not match. Please try again.")
login_user()
The problem with your code lies in the fact that you are printing the message "Ok, please continue!" within your for loop.
...
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
print("Ok, please continue!")
else:
print("This username is already taken. Please try another.")
...
What happens is that every time your usernameslist[id] is checked against the 'newusername' variable, the print statement 'print("Ok, please continue!")' is run, causing the message to be displayed multiple times.
What you can do to fix this issue is to move the print statement out of the for loop, so that, assuming that a new username does not match any username in the usernameslist, the message "Ok, please continue!" will be displayed once to the user before they are prompted to input their password twice.
Here's what should work for you:
...
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
else:
print("This username is already taken. Please try another.")
if goodlogin2 = True:
print("Ok, please continue!")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
...
It looks like you're iterating over your whole list of usernames and printing out a success or error message with each iteration.
Try this instead:
# If user does not have account:
else:
goodlogin2 = False
newusername = input("What is your new username? ")
if newusername in usernameslist:
print("This username is already taken. Please try another.")
else:
goodlogin2 = True
print("Ok, please continue!")
# for id in range(len(usernameslist)):
# if newusername != usernameslist[id]:
# goodlogin2 = True
# print("Ok, please continue!")
# else:
# print("This username is already taken. Please try another.")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
if newpassword == newpasswordagain:
print("Please follow the instructions to log in with your new credentials.")
add_file_contents(users_path, '\n' + newusername)
add_file_contents(passwords_path, '\n' + newpassword)
login_user(new_account=True)
else:
print("Your passwords do not match. Please try again.")
This produces the following output for a user with no previous account who enters a name which has not been used:
--------------------------------------------------
Welcome! Do you have an account (y/n)? n
--------------------------------------------------
What is your new username? not_taken2
Ok, please continue!
What is your new password? pwd2
Please enter your new password again.pwd2
Please follow the instructions to log in with your new credentials.
Please enter your username:
My question is, how would I compare a username and password two a whole document to find if it is in there. so far I have this:
regorlog = raw_input("press 1 to register, press 2 to log in! \n")
if regorlog == "1":
uname = raw_input("what is your desired username?\n")
pwd = raw_input("what is your desired password?\n")
pwd2 = raw_input("please retype your password\n")
if (pwd == pwd2):
file = open("userlog.txt", "a")
file.write(uname + " || " + pwd + "\n")
file.close()
else:
print 'sorry, those passwords do not match'
elif regorlog == "2":
loguname = raw_input("what is your username? \n")
logpwd = raw_input("what is your password? \n")
file = open("userlog.txt", "r")
#here, I need to read the file userlog.txt, and look and see if the username and password combination exists in the file somewhere.
file.close()
I am having trouble reading the whole file, and looking for the username and password combo. any help would be much appreciated.
I just figured it out. here is what I ended up doing!
regorlog = raw_input("press 1 to register, press 2 to log in! \n")
if regorlog == "1":
uname = raw_input("what is your desired username?\n")
pwd = raw_input("what is your desired password?\n")
pwd2 = raw_input("please retype your password\n")
if (pwd == pwd2):
file = open("userlog.txt", "a")
file.write(uname + " || " + pwd + "\n")
file.close()
else:
print 'sorry, those passwords do not match'
elif regorlog == "2":
loguname = raw_input("what is your username? \n")
logpwd = raw_input("what is your password? \n")
file = open("userlog.txt", "r")
if loguname + " || " + logpwd in open('userlog.txt').read():
print "true"
file.close()
I suggest using a built-in module to do this for you:
import shelve
regorlog = raw_input("press 1 to register, press 2 to log in! \n")
if regorlog == "1":
uname = raw_input("what is your desired username?\n")
pwd = raw_input("what is your desired password?\n")
pwd2 = raw_input("please retype your password\n")
if pwd == pwd2:
shelf = shelve.open("userlog.txt", "c")
shelf[uname] = pwd
shelf.close()
else:
print 'sorry, those passwords do not match'
elif regorlog == "2":
loguname = raw_input("what is your username? \n")
logpwd = raw_input("what is your password? \n")
shelf = shelve.open("userlog.txt", "c")
try:
matched = shelf[loguname] == logpwd
except KeyError:
matched = False
shelf.close()
print 'Matched: ', matched
Edit: fixed. I suggest changing the name of the file, though
change the last part in what you have to:
# ...
elif regorlog == "2":
loguname = raw_input("what is your username? \n")
logpwd = raw_input("what is your password? \n")
login_info = loguname + " || " + logpwd
with open("userlog.txt", "r") as users_file: # closes the file automatically
if any(login_info == line.rstrip() for line in users_file):
# if any line in the file matches
print "true"
But for the love of security please don't store passwords as plaintext
https://crackstation.net/hashing-security.htm