Python comparison of previous data - python

I have a program that asks the user for raw input and then displays it. What I want to do is this:
If the user enters data that was different from the previous data entered, then update the data, else do nothing.
So all I'm doing is checking whether the data the user enters is the same as the one they entered before but I would like to know how I go about doing this in Python.

The natural way to do this is with a data structure that guarantees that its elements are unique. For instance, try defining a set and adding any new user input to it. If you try to add a string that's already in the set, it will do nothing.
record = set()
while True: # just an example; you'll need to end the loop somehow
message = raw_input('give me data! ')
record.add(message)
print record

Here is a simple way to do it:
user_input = raw_input('enter an input\n')
user_input2 = raw_input('confirm your input\n')
if user_input != user_input2:
print 'updating...'
user_input = user_input2
print 'Input is: {}'.format(user_input)
If you need to split up a string of input, see the documentation for str.split and other handy built in functions:
https://docs.python.org/2/library/stdtypes.html#str.split

Related

Need multiple inputs saved to another single input, all information given by user

Building a webscraper for a game I love and right now came into a little issue with python, what I want to do could best be show as:
userdata = { ' ', [ ]}
I'm new to writing python so my question is would this work given the following scenario:
User's account name (which players in the game use to message each other) wants to attach multiple character names to that single account name so other players know that all these characters belong to that one account.
The end result should be something like this:
"Please enter your account name followed by which characters you wish associated with this account:"
user input: Leafzer Leaf1 Leaf2 Leaf3
current limitations in the game work to python's advantage as account and character names can not have any white space. I was considering using split such as:
x = [str(x) for x in input("Enter user data: ").split()]
but as it stands neither of these seem to work quite right.
To reiterate and maybe clear some of the confusion: Writing a website scraper that allows players in the game to enter their account name and a list of mules (characters in the game that just hold items). The list of mules and the account name must be separate as my scraper uses the list of mules to go to a certain website using that mule name and downloads the data into a searchable csv file. If another player searches for an item that is within that csv file, it brings up the account name associated with the mule rather than the mule name and displays the account name to player searching for the item.
I'm stuck trying to figure out how to obtain the user data in this manner. Any help would be appreciated.
Are you after something like this:
users = {}
user, *chars = input("Please input your name and characters: ").split(" ")
users[user] = chars
?
Or slightly less confusingly (but not nearly as neatly):
users = {}
words = input("Please input your name and characters: ").split(" ")
user = words[0]
chars = words[1:]
users[user] = chars
But * unpacking is great, and everyone should use it!
P.S. for your second use case, just call input() twice!:
username = input("Please input your name: ")
chars = input("Please input your characters: ").split(" ")

how to make a program ignore everything but the key word in users input?

datadict = {}#open the file
with open('phoneproblemquery.txt') as file:
for line in file:
problem, answer = line.split('-')
problems = problem.strip().split(' ')
for item in problems:
datadict[item] = answer
user_problem = input('What is the problem?:')
print(datadict[user_problem])
The text-file contains something like this:
screen - replace screen.
if I were to run this program and enter in 'screen' the program will respond 'replace screen'. but, if I were to enter something like 'the screen'(not just 'screen' alone) the program will give a 'keyError' and won't work.
what would I need to do to if the user enters 'the screen' (instead of just 'screen') for the program to provide an output 'replace screen'. would I need to put the users answer into arrays? if so how?
Thanks!
update: 'the screen' was just an example. The user can enter in any
form of way i.e 'screen is...' the keyword is screen. I would want
the program to identify the key word from the users input and get
the response 'replace screen'. ... ;( desperate for an answer...
You want the program to pick keywords out of the user input and look for them in datadict. The difficulty with that is picking out keywords. A simple approach is to have regular expressions rather than simple keywords as the keys of your lookup dictionary. You will of course have to do the matching yourself: the dictionary lookup process won't do it for you.
import re
datadict = {}
#open the file
with open(r'phoneproblemquery.txt') as file:
for line in file:
problem, answer = line.split('-')
problems = problem.strip().split(' ')
for item in problems:
datadict[re.compile(fr'{item}', re.IGNORECASE)] = answer
user_problem = input('What is the problem?:')
for regex, diagnosis in datadict.items():
if regex.search(user_problem):
print (diagnosis)
This will work, but in a more sophisticated implementation it might be better to put the regular expressions in the input data, rather than constructing them at runtime like I have done here. You are already allowing for something of the sort by having a space-delimited list if keywords in your input data. If you had regular expressions in the input instead, the same would apply, only instead of, say
keyboard kybd - replace keyboard
you would have
keyboard|kybd - replace keyboard
and in that event maybe a hyphen would not be the best delimiter. A carriage return might be better, since that can never appear in the input.

How would I save the data to a .csv file

I have made a program based on a maths quiz and have saved the data of the files to a .txt file. If I wanted to save the files in a .csv file would i just chnage .txt to .csv? Here is my code :
import time
import math
import random#I am using this to allow me to randomly pick the symbol operation and to randomly generate numbers
print("Title:Arithmetic Quiz")#Tells the user what the program is.
print("*************************************************************")#This is a line to make the presentation clearer to the user.
#The code below shows the user an introduction of what the program is about.
print("This program will ask you to complete the arithmetic quiz.")
print("The program has 10 questions. You will recieve feedback after.")
print("____________________________________________________________")
#The line above prints a line across the page.
while True:#This creates an infinity loop
UserName = input("What is your name?:")#Ask the user for there name.
if not UserName.isalpha():#This is used to check if the user name is anything else apart from alphabetical letters.
print("Error!Please enter your name using letters. ") #warning if wrong if wrong input given
continue#Continues with the code when correct input given.
else:#It breaks out of the while loop and proceeds with the quiz
break
ClassSelection= input("Please enter what Class you are in?:1, 2 or 3")
ClassChosen=0
while ClassChosen==0:
if ClassSelection=="1":
ClassChosen=1
elif ClassSelection=="2":
ClassChosen=1
elif ClassSelection=="3":
ClassChosen=1
else:
print("You must write 1, 2, or 3.")
ClassSelection=input("Enter the class you are in")
print(UserName," welcome to the Arithmetic Quiz.")#Welcomes the user to the quiz.
print("____________________________________________")
print("The quiz will begin in 3 seconds")
time.sleep(2)
for i in range(0,3):# range between
print (3 - i)#counts down by one
time.sleep(1)#Delays for 1 second
print("Begin!")
print("*****************************************")
RecentStudent= [0,0,0]#This is a list with dummy values. The use of this is to save the last three score of the user.
def MathsQuiz():#I have used a function to make my code more efficient.
score=0#No questions have been answered correctly yet so score is set to zero
for questionNum in range(10):#I have used this to allow me to set my Parameters.
Num1= random.randint (1, 10)#Generates a random number between 1 and 10 for Num1.
Num2= random.randint (1, 10)#Generates a random number between 1 and 10 for Num2
Symbol = ["+","-","*"]#These are my operators used for the arithmetic of Num1 and Num2.
Operation = random.choice(Symbol)#This will randomly choose a operating symbol for a question
RealAnswer= int(eval(str(Num1)+Operation+str(Num2)))#This is used to work out the answer for the question.The evaluate is used to interpret the code as a str and calculate an answer.
#It will store the value of the Answer and call it when it is needed.
print("Please give an answer for:", Num1, Operation, Num2)#This is what makes the question and outputs it to the user by using the random functions.
UserAnswer = int(input("Enter your answer here:"))#This asks the user to enter their anser to the question.
if UserAnswer == RealAnswer:#This checks if the answer from the user is the same as the real answer.
score = score + 1#If the user gets the question right 1 should be added to the score.
print("You are correct! :D")#The program will congratulate the user.
print("_______________________________________________")
else:#If the users answer is not the same as the real answer then it will print a wrong message.
print("You are incorrect! :( ")#This tells the user that they got the question incorrect and tells the user the real answer.
print("The answer was", RealAnswer)
print("________________________________________________")#This will be used to split the quiz.
print()#This is used to format the quiz.
print("__________________________________________________")
print("Thank you for completing the quiz!")
print("Your Score is loading")
import time
time.sleep(2)
print(UserName,"In this test you achieved",score,"/10")#This tells the user the score they achieved in the maths test.
print()#This is used to format the code
del RecentStudent[0]
RecentStudent.append(score)
print("Your three most recent scores are:",RecentStudent)
print("********************************************************")
def Resit1():#This function is used to easily call place of the program such as in this case when resitting.
Resit1=input("Do you want to resit the test? Yes or No?:")#Asks the user if they would like to resit
#The variable will let user input whether they want to do the quiz again.
if Resit1== "Yes" or Resit1=="yes":# Checks the input of the user to the resit question
MathsQuiz()#This is used to call the quiz which will restart the quiz and allow them to retake the quiz.
#It tells the user that they are finished
def Resit2():#This function is used to easily call place of the program such as in this case when resitting.
Resit2=input("Do you want to resit the test? Yes or No?:")#Asks the user if they would like to resit
#The variable will let user input whether they want to do the quiz again.
if Resit2== "Yes" or Resit2=="yes":# Checks the input of the user to the resit question
MathsQuiz()#This is used to call the quiz which will restart the quiz and allow them to retake the quiz.
print("Quiz Finished")#It tells the user that they are finished
MathsQuiz()#This will call the first function that has been set in the program.
Resit1()#This will call the Resit1 function when it is needed by the program.
Resit2()#This will call the Resit2 function when it is needed by the program.
if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
Class1 = []#class1 list is created and is empty.
Class1.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class1.append(UserName)#The name variable is appended as the second item.
Class1.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class1.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class1Scores.txt", 'a')#File opened called classAScores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class1))#Allows me to write the classA list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.
elif ClassSelection=="2":#used to identify whether the ClassSelection is equal to 1.
Class2=[]#classA list is created and is empty.
Class2.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class2.append(UserName)#The name variable is appended as the second item.
Class2.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class2.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class2Scores.txt", 'a')#File opened called classAScores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class2))#Allows me to write the classA list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
elif ClassSelection==3:
Class3 = []#classA list is created and is empty.
Class3.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class3.append(UserName)#The name variable is appended as the second item.
Class3.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class3.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class3Scores.txt", 'a')#File opened called class3Scores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class3))#Allows me to write the class3 list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.
This is my code would I need to change the bottom of the code to save the files in a .csv file. I tried doing a different method, but never got anywhere .
I suggest using the csv module. I've adapted your code to use it (there are a lot of ways you could make your life easier with your code, but let's focus on one issue at a time):
import csv
if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
Class1 = []#class1 list is created and is empty.
Class1.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class1.append(UserName)#The name variable is appended as the second item.
Class1.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class1.append(RecentStudent)#The score variable is appended as the last item.
with open('Class1Scores.csv', 'wb') as file:
writer = csv.writer(file)
writer.writerow(str(Class1))
writer.writerow("\n")
Gentle into to the csv module
Because we're using the with keyword, there is no need to call file.close()
For a more advanced way of doing this, you could use pandas to_csv
Looks like your Class1 is simply a list. Then you can say file.write(",".join(Class1)). But a more robust method is to use the csv module - https://docs.python.org/2/library/csv.html

Python: How to store a REQUEST for input in a variable?

I'm building a text game and need to store 2 things in a single variable: a string, and a request for input. Note that I don't mean to store the output of the request - I mean that if the variable is called, both the string and the request itself are printed, after which the user answers the request.
raw_input("Do you do X or Y?") therefore doesn't work for me, because I need to store the request before I deploy it.
Some background about my approach:
Everything's stored in a dictionary, where the keys are the user's current location and the values are possible choices:
dict = {location1: (location2, location3), location2: (location1, location4)...}
So, I'll print location1, which will simultaneously print the string that describes that location, and make a request for input. The input triggers the program to print the next appropriate location, and the program keeps on going.
I'm trying to work out a recursive function that does this.
For each location, the request for input is worded differently, which is why I don't just build the request into my recursive function.
Sidenote: if anyone has any other suggestions/different approaches I should use instead, please share those too!
For each location, the request for input is worded differently,
Simply create another dictionary for input request corresponding to each location. For ex:
requests_dict = {
'location1': 'Please enter xxx: ',
'location2': 'Do you do X or Y: ', # and so on
}
Then use that dict to print the request.
user_input = raw_input(requests_dict['location2'])
Of course, you would like to make the last code based on some logic so that which one of that dicts is called, but I think you get the idea.
Update:
responses_dict = {}
user_input = raw_input(requests_dict['location2'])
responses_dict[user_input] = 'You are in %s' % user_input

How To Save The Replace - Python

This is what I am using. It runs everytime the user enters something, and it will replace part of the string, but on the second repeat it goes back to how it was eg
first run of it:
t3st
second run:
te5t
I want both of them to stay so after it would be t35t
if ((letterPair) in (allPairs)):
print ("Correct")
iReplace = open("textfile.txt")
iReplace = iReplace.read()
iReplace = iReplace.replace((letterPair[1]),(letterPair[0]))
print (iReplace)
options()
else:
print ("Incorrect letter pairing")
options()
These two lines need to be moved outside of whatever loop you're using to process input:
iReplace = open("textfile.txt")
iReplace = iReplace.read()
As your code stands now, you are re-reading the original string from textfile.txt every time the user presses a key, and then assigning it to iReplace.
You haven't pasted enough code in to be sure, but I assume there is some sort of loop around the code you posted. Put those lines outside of that.

Categories