How to use sys.exit() if input is equal to specific number - python

I am looking to correct this code so that when the user inputs 99999 then the code stops running, im also looking to make it so that if the user input is 999 it sets the total to 0
import sys
def money_earned():
total = int()
try: # try open the file
file = open("total.txt", "r")
data = file.readline()
total = int(data)
except: # if file does not exist
file = open("total.txt", "w+") # create file
total = 0
file.close() # close file for now
while True:
try:
pay_this_week = int(input("How much money did you earn this week? "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
pay_this_week_message = "You've earned £{0} this week!".format(pay_this_week)
total = pay_this_week + total
total_message = "You have earned £{0} in total!".format(total)
print(pay_this_week_message)
print(total_message)
if pay_this_week == "99999":
sys.exit()
file = open("total.txt", "w") # wipe the file and let us write to it
file.write(str(total)) # write the data
file.close() # close the file
money_earned()

So you're taking the input as a string and immediately converting it to an int, but you could actually convert it to an int later and check for some words in your input first.
Right now you have
pay_this_week = int(input("..."))
but if you change this to
input_from_user = input("...")
pay_this_week = int(input_from_user)
then we can add some more code inbetween
input_from_user = input("...")
if input_from_user == "done":
return # this will exit the function and so end execution
elif input_from_user == "reset":
total = 0 # reset the total
else:
pay_this_week = int(input_from_user)
this should have the desired effect

Related

Storing Python game results in .txt file till next program run? (Python 3.8)

First of all, let me apologize for the title because I was not sure how to properly ask/state what I am trying to do. So let me get straight to explaining.
I am writing a Python dice program, where the user makes a bet (starting bet is $500) and chooses a number between 2 and 12. The user gets three rolls of the dice to match their number in which depending on the roll count, they add to their wage, win their wage, or subtract from their wage (bank amount). This continues till
they exceed the bet limit, 500.
Enter a 0 (zero) as the bet amount, in which 0 (zero) terminates the program.
The user has lost all their money, thus the bank amount reaches 0 (zero).
This all works exactly as I need it to. However, I want to store the value of the bank amount to a .txt file so that, for example, if I quit the game with a total of $300, then next time I open and run the program I will start with $300 instead of the default $500. So I need to create this file and figure out how/where to incorporate it into my written program.
This is my code for the program so far:
import random
def rollDice(rcnt):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
x = int(die1 + die2)
print('Roll #', rcnt, 'was', x)
return x
def prog_info():
print("You have three rolls of the dice to match a number you select.")
print("Good Luck!!")
print("---------------------------------------------------------------")
print(f'You will win 2 times your wager if you guess on the 1st roll.')
print(f'You will win 1 1/2 times your wager if you guess on the 2nd roll.')
print(f'You can win your wager if you guess on the 3rd roll.')
print("---------------------------------------------------------------")
def total_bank(bank):
bet = 0
while bet <= 0 or bet > min([500,bank]):
print(f'You have ${bank} in your bank.')
get_bet = input('Enter your bet (or 0 to quit): ')
bet = int(get_bet)
if get_bet == '0':
print('Thanks for playing!')
return bank, bet
return bank, bet
def get_guess():
guess = 0
while (guess < 2 or guess > 12):
try:
guess = int(input('Choose a number between 2 and 12: '))
except ValueError:
guess = 0
return guess
prog_info()
bank = 500
guess = get_guess
rcnt = 1
bet = 1
while rcnt < 4 and bet:
rcnt = 0
bank,bet = total_bank(bank)
if not bet: continue
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * 1.5
elif guess == rollDice(rcnt+3):
bank = bank
else:
if bet:
bank = bank - bet
if bank == 0:
print(f'You have ${bank} saved in your bank.')
print('Thanks for playing!')
There's a built-in python function called open(): https://www.w3schools.com/python/python_file_write.asp
At the start of your program, you should have your program check for any saved progress by finding the file. If there is no file, your program should make one when one wants to stop playing.
A way of doing this can be:
try:
f=open("winnings.txt","r") # reads the file for any saved progress, if it exists
bank = int(f.readline())
f.close() # closes the connection. important, as the file might be lost if you don't close it after using it
except IOError: # if the file doesn't exist
bank = 500
...your code here...
f=open("winnings.txt","w") # overwrites the previous save
f.write(str(bank))
f.close()
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
https://www.w3schools.com/python/python_json.asp
This will write to (and overwrite) a file:
import json
saveData = {
"var 1": 1234,
"foo": "hello world",
10: "in the morning"
}
# Saving
with open("save.txt", "w") as f: # Write
# Remove the indent if you want it all on one line
print(json.dumps(saveData, indent=4), file=f)
del saveData
# Loading
with open("save.txt", "r") as f: # Read
saveData = json.loads(f.read())
print(saveData)
# Or, print with JSON to make it look good
print(json.dumps(saveData, indent=4))
WARNING: This only works with default Python objects. You will need to convert (serialize) any custom objects before dumping them to a file. Here is an example of serializing your objects:
class myClass:
def __init__(self, x, y):
self.x = x
self.y = y
def save(self):
return {
"x": self.x,
"y": self.y
}
def load(self, data):
self.x = data["x"]
self.y = data["y"]
obj = myClass(1234, 5678)
objData = obj.save()
print(objData)
del obj
obj = myClass(None, None)
obj.load(objData)

How can i remove " " and . from a data in a list

So i have this college python project that asks me to make a program to manage an inventory, my question basically is that whenever I try to convert the price and the quantity again to floats this exception rase, so how can I convert them so I can make further process on them?
note that I tried to use .strip but it didn't work
this is the error:
float_price = float(i)
ValueError: could not convert string to float: '.'
this is the code that I have issues with:
from tabulate import tabulate
def read_data():
file = open("inventory.txt", "r")
list_of_lists = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
updated_list = list_of_lists[1:]
file.close()
return updated_list
def list_data():
updated_list = read_data()
index = 0
price = 0
quantity = 0
j = 0
while j < len(updated_list):
for i in updated_list[1][4]:
float_price = float(i)
price += float_price
print(price)
header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
print(tabulate(updated_list, headers=header))
list_data()
this is the code to add data to the file:
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n' + make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to import the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+ '\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
as error message indicates '.' is string and it cannot be converted to float so raises error.. it depends what you want to do with such situation you can use try except as.
from tabulate import tabulate
def read_data():
file = open("inventory.txt", "r")
list_of_lists = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
updated_list = list_of_lists[1:]
file.close()
return updated_list
def list_data():
updated_list = read_data()
index = 0
price = 0
quantity = 0
j = 0
while j < len(updated_list):
for i in updated_list[1][4]:
try:
float_price = float(i)
price += float_price
except ValueError as e:
print('Value Error')
print(price)
header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
print(tabulate(updated_list, headers=header))
list_data()

Python Debugging, Program will not display text lines outside user input of 1

The basics of the program are to ask the user for a .txt file and count how many lines in the file. Then the program displays the number of lines in the file and the user will input a number to display a certain line in the file. If the user hits 0 the program will end.
The program runs fine until I enter a number besides 1 or the last line number in the .txt file. The program proceeds to display the "Enter a line number, want to quit? Hit 0" Over and over.
inName = input("Enter the a valid file name: ")
inputFile = open(inName, "r")
count = 0
for line in inputFile:
count = count + 1
print("The file has " + str(count) + " lines.")
inputFile.close()
while True:
try:
n = int(input("Enter a line number, want to quit? Hit 0: "))
lineno = 0
break
except ValueError:
print("Try again. Line number must be between 1 and " + str(count))
while n != 0:
if n >= 0 and n <= count:
inputFile = open(inName, "r")
for line in inputFile:
lineno = lineno + 1
if lineno == n:
print(line)
inputFile.close()
else:
print("Try again. Line number must be between 1 and " + str(count))
while True:
try:
n = int(input("Enter a line number, hit 0 to quit: "))
lineno = 0
break
except ValueError:
print("Try again. Line number must be between 1 and " + str(count))
I will not address the multitude of issues with your code, since the comments and answer have done a pretty thorough job there already. Instead, I'd like to discuss the I/O problem you are creating by opening and closing the file over and over. It's expensive to do that. For a program that spends virtually all its time waiting for user input, is probably won't be noticeable, but opening and closing files without need is a bad habit.
I would suggest one of two solutions to get around this. If you are dealing with small text files, just load the whole thing into memory, e.g. with file.readlines():
inName = input("Enter the a valid file name: ")
with open(inName, "r") as file:
data = file.readlines()
count = len(data)
print(f"The file has {count} lines.")
while True:
try:
n = int(input("Enter a line number, want to quit? Hit 0: "))
except ValueError:
print(f"Try again. Line number must be between 1 and {count}")
else:
if n == 0:
break
print(data[n - 1])
For large files, I would agree with your technique of loading only one line at a time, but you have to be smart about it. I would open the file once, create a table of offsets to the line starts, and move around the file using that table:
inName = input("Enter the a valid file name: ")
with open(inName, "r") as file:
table = [0]
table.extend(file.tell() for _ in file)
count = len(table) - 1 # last entry is size of file
print(f"The file has {count} lines.")
while True:
try:
n = int(input("Enter a line number, want to quit? Hit 0: "))
except ValueError:
print(f"Try again. Line number must be between 1 and {count}")
else:
if n == 0:
break
file.seek(table[n - 1])
print(file.readline()
Refactored your code and made some changes in the loops, removed the part where you were closing the file mid-loop and replaced it with break.
Try this if it works :
inName = input("Enter the a valid file name: ")
inputFile = open(inName,"r")
count = 0
for line in inputFile:
count = count + 1
print("The file has "+str(count)+" lines.");
inputFile.close()
while True:
try:
n = int(input("Enter a line number, want to quit? Hit 0: "))
lineno = 0
except ValueError:
print("Try again. Line number must be between 1 and "+str(count))
if n != 0:
if n >= 0 and n <= count:
inputFile = open(inName, "r")
for line in inputFile:
if lineno == n:
print(line)
#inputFile.close()
break
else:
lineno = lineno + 1
else:
print("Try again. Line number must be between 1 and "+str(count))
else:
break

Python password system with lock after certain number of attempts

So I am trying to create a password system in Python, whereby after a certain number of incorrect attempts, the user will be blocked from accessing it for, say, 5 minutes. I am currently unsure how the values of the variables can be kept after rerunning the same file and then used in this manner. Could someone help me with this, as I am currently still new to Python?
Update:
After experimenting for a while with the code Jonas Wolff provided me I finalised my code to the following:
def password():
count = 0
currentTime = float(time.time())
passwordList = ["something", "password", "qwerty", "m42?Cd", "no"]
passwordNum = random.randint(0, 4)
password = passwordList[passwordNum]
with open("password.txt", "r") as file:
check = file.readline()
initialTime = file.readline()
if initialTime=="":
initialTime==0
if int(check)==1 and (currentTime-float(initialTime))<300:
print("You are still locked")
print("Please try again in", int(300-(currentTime-float(initialTime))), "seconds.")
quit()
print("The randomised password is No.", passwordNum+1) #Prints a string to let the user know which password was randomly selected
while count<5:
inp = input("Enter the Password: ")
if inp==password:
print("Access Granted")
print()
f = open("password.txt", "w")
f.write("0\n0")
f.close()
select()
elif (count+1)==5:
print("You have been locked")
print("Please try again in 5 minutes")
f = open("password.txt", "w")
f.write("1\n")
f.write(str(currentTime))
f.close()
quit()
else:
count+=1
print("Incorrect Password")
print("You have", 5-count, "tries left.")
continue
Thanks a lot for the help you have provided and the patience with which you answered my questions.
import YourProgram # this is the program you want to run, if the program runs automaticly when opened then move the import to the part where i wrote YourProgram() and delete the YourPregram() line
import time
pswd = "something"
count = 0
with open("PhysxInit.txt","r") as file:
file_info = file.readline()
numa = file_info.count("1")
count = numa
while True:
with open("PhysxInit.txt","r") as file:
file_info = file.readline()
tima = file.readline()
inp = input("What is the password:")
if inp == pswd:
if tima == "":
tima = "0" # this should solve yoúr problem with float convertion however it doesn't make sence that this step should be needed
if str(file_info[:5]) != "11111" or time.time() > float(tima):
YourProgram() # this is just meant as the thing you want to do when when granted acces i magined you where blocking acces to a program.
f = open("PhysxInit.txt", "w")
f.write("\n")
f.close()
break
else:
count += 1
f = open("PhysxInit.txt", "w")
f.write(("1"*count)+"\n"+str(tima))
if count == 5:
f.write(str(time.time()+60*5))
f.close()
#f = open("PhysxInit.txt", "w")
#f.write("\n")
#f.close()
does this work?
just make sure you have a text file called PhysxInit.txt
after running the program, and having guessed wrong a few times my txt file look like this.
11111
1536328469.9134998
it should look something like mine though the numbers may be diffrent.
To read a specific line as you requested you need to do:
with open("PhysxInit.txt", "r") as f:
for w,i in enumerate(f):
if w == #the number line you want:
# i is now the the line you want, this saves memory space if you open a big file

Use values saved to a file in order to compute mean/median/mode/etc

I have a program that saves a file that you can write values to. What I am trying to do is use the saved files to calculate my mean/median/mode and to be able to delete values. functions. I am able to add values to the file through the open("filename","a")...but how do I make it so that I am able to import the file values to calculate my other functions?
Sorry its so long, but if anyone can help I would really appreciate it, I am new to figuring out File IO a stuff.
filename = input("What do you want to name your file? Be sure to include .txt after the filename!:")
def main(filename):
print("Now what would you like to do?")
print("--------------------------------------------------------------------------------")
print("Press 1 if you would like to ADD a Value to your list")
print("Press 2 if you would like to DELETE a Value from your list according to its value")
print("Press 3 if you would like to DELETE a Value from your list according to its location")
print("Press 4 if you would like to DISPLAY your List")
print("Press 5 if you would like to COMPUTE MEAN for your list")
print("Press 6 if you would like to COMPUTE MEDIAN for you list")
print("Press 7 if you would like to COMPUTE MIDPOINT for you list")
print("Press 8 if you would like to COMPUTE MODE(S) for your list")
print("Press 9 if you would like to COMPUTE STANDARD DEVIATION for your list")
print("Press 10 if you would like to READ values from a FILE you have made")
print("Press 0 if you would like to EXIT")
print()
execute = int(input("which action would you like to do next?"))
if execute == 1:
add_Values(filename)
if execute == 2:
remove_Value_List(filename)
if execute == 3:
del_Value_Location(filename)
if execute == 4:
read_file(filename)
if execute == 5:
computing_Mean(filename)
if execute == 6:
computing_Median(filename)
if execute == 7:
computing_Midpoint(filename)
if execute == 8:
computing_Modes(filename)
if execute == 9:
computing_Standard_Dev(filename)
if execute == 10:
read_file(filename)
if execute == 0:
print()
print("That's too bad I was having so much fun...but okay...bye!")
if execute >= 12:
print("Sorry but that is not one of the options")
if execute <= -1:
print("Sorry but that is not one of the options")
def add_Values(filename):
fout = open(filename,"a")
again = 'y'
while again == 'y':
fout.write(input("Enter a number you want to write to the file:")+"\n")
print("Do you want to add another number?")
again = input("y = yes, anything else = no:")
fout.close()
print("The numbers have been saved to the file")
main(filename)
def remove_Value_List(filename):
fout = open(filename, "r")
fout.readlines()
remove = "y"
while remove == "y":
print()
print("Here is your list:")
add_Values(filename)
number_list = float(input("Which value should I remove?"))
try:
values.remove(number_list)
print("Here is the revised list:")
print()
print()
except ValueError:
print("That item is not found in the list.")
number_list = float(input("which value should I remove?"))
remove = input("Would you like to remove a value? y = yes, amything else = no:")
fout.close()
print()
main(filename)
def del_Value_Location(filename):
remove = "y"
fout = open(filename,"r")
fout.readlines()
while remove == "y":
print()
print("Here is your list:")
add_Values(filename)
number_list = int(input("Which position should I remove?"))
try:
del values[number_list]
print("Here is the revised list:")
read_file_one(filename)
print()
except ValueError:
print("That item is not found in the list.")
number_list = float(input("which value should I remove?"))
remove = input("Would you like to remove a value? y = yes, amything else = no:")
fout.close()
print()
main(filename)
def computing_Mean(filename):
with open(filename,"r") as fout:
summ = 0
cnt = 0
for line in fout.readlines():
cnt += 1
summ += float(line.strip())
print ("Mean value is:" (summ/cnt))
def computing_Median(filename):
fin = open(filename,"r")
fin.readlines()
ordered = sorted(filename)
length = len(filename)
print("The median of this list is:")
print(float((ordered[length//2] + ordered[-(length+1)//2]))/2)
main(filename)
def computing_Midpoint(filename):
with open(filename,"r") as fout:
filename.sort(key=int)
minNum = min(float(filename))
maxNum = max(float(filename))
print("The midpoint of this list is:")
print((minNum + maxNum) / 2)
main(filename)
def computing_Modes(filename):
from collections import Counter
data = Counter(filename)
print("The Mode(s) of this list is/are:")
print(data.most_common(1))
main(filename)
def computing_Standard_Dev(filename):
mean = sum(filename)/len(filename)
for i in values:
total = 0
newDev = i - mean
squared = newDev**2
total = (total + squared)
divider = (total/(len(values)-1))
standardDev = divider**.5
print("The standard deviation is:")
print(standardDev)
main(filename)
def read_file(filename):
fin = open(filename, 'r')
L = fin.readlines()
for ix in range(len(L)):
L[ix]=L[ix].strip()
while "" in L:
L.remove("")
for ix in range(len(L)):
L[ix]=float(L[ix])
fin.close()
print(L)
main(filename)
main(filename)
There are lots of errors in your code which are very similar to each other so I will explain only one of those similar ones and you should fix others by examining fixed one.
For startes you are opening a file named filename. Using quotes around it makes it a string. You should use it like this:
def add_Values(filename):
fout = open(filename,"w")
But using with statement to open files is much more better because file is closed automatically even if exception is raised.
def add_Values(filename):
with open(filename) as fout:
#do smth
There is no file to work with in def del_Value_Location(filename): and some others. You should open your file in those as well.
To make calculations you need read your data from your file. Which can be achieved by using file.readlines()
def computing_Mean(filename):
with open(filename,"r") as fout:
summ = 0
cnt = 0
for line in fout.readlines():
cnt += 1
summ += int(line.strip())
print ("Mean value is: %.1f" % (summ/cnt))
If you want to change how many digits you want to see, you should change %.1f part.
With this you should fix your other computations by yourself.
About menu, you can do something like this to make it appear again without using a second function.
filename = input("What do you want to name your file? Be sure to include .txt after the filename!:")
#exclude this filename in main and use it as `main`s argument.
def main(filename):
print("Now what would you like to do?")
Ofcoure after this, you should change all main_two()s to main(filename).

Categories

Resources