I have a text file that has results listed like this:
Welcome to your results
The result of 50+25=75
The result of 60+25=85
The result of 70+25=95
The result of 80+25=105
I need python to read the file and pull out the numbers to the left of the "=" and add them up. I have no idea how to get this to work.
# take input from the user
print("Select operation.")
print("1.Display The Content of the result file")
print("2.Add two numbers")
print("3.Subtract two numbers")
print("4.Multiply two numbers")
print("5.Divide two numbers")
print("6.Append results to file")
print("7.Display Total of inputs")
print("8.Display Average of inputs")
print("9.Exit")
choice = input("Select an option(1-9):")
if choice == 1:
file = open('results.txt', 'r')
print file.read()
elif choice >= 2 and choice <= 5:
l_range = int(input("Enter your Lower range: "))
h_range = int(input("Enter your Higher range: "))
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 < l_range:
print "The input values are out side the input ranges \n Please check the numbers and try again"
elif num2 > h_range:
print "The input values are out side the input ranges \n Please check the numbers and try again"
else:
if choice == 2:
print "The result of", num1,"+", num2,"=", add(num1,num2)
resultstr = "The result of " + str(num1) + "+" + str(num2) + "=" + str(add(num1,num2))
elif choice == 3:
print "The result of", num1,"-",num2,"=", subtract(num1,num2)
resultstr = "The result of " + str(num1) + "-" + str(num2) + "=" + str(subtract(num1,num2))
elif choice == 4:
print "The result of", num1,"*", num2,"=", multiply(num1,num2)
resultstr = "The result of " + str(num1) + "*" + str(num2) + "=" + str(multiply(num1,num2))
elif choice == 5:
print "The result of", num1,"/", num2, "=", divide(num1,num2)
resultstr = "The result of " + str(num1) + "/" + str(num2) + "=" + str(divide(num1,num2))
if num2 == 0:
print "The result of", num1,"/", num2, "=", "You can't divide by zero!"
elif choice == 6:
print("The results have been appended to the file")
file = open('results.txt', 'a')
file.write(resultstr + "\n")
file.close()
elif choice == 7:
print ("Display total inputs")
elif choice == 8:
print ("Display average of total inputs")
elif choice == 9:
print ("Goodbye!")
else:
print("Invalid input")
lp_input = raw_input("Do you want to perform another action? Y/N:")
if lp_input == 'n':
print("Goodbye!")
From what I understand from the question, a simple regex match would solve the problem. You may do it like so:
Read the file line by line.
Make a regex pattern like so, to get the data from the string:
>>> pattern = "The result of (\d+?)[+-/*](\d+?)=(\d+).*"
Say if a line from the file is stored in the variable result:
>>> result = "The result of 25+50=75"
import the re library and use the match function like so which gives you the data from the string:
>>> s = re.match(pattern, result)
>>> print s.groups()
('25', '50', '75')
You can then get the numbers from this tuple and do any operation with it. Change the regex to suit your needs, but given the contents of the file at the start, this should be fine.
Related
Doing my homework rn and a bit stuck, why does the code execute "else" even thought the "if" has been satisfied? Ignore the sloppy code, I'm very new :/
order1 = input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ")
while order == True:
if order1 == 1:
print("You have selected to order 1: " + orderBurger)
elif order1 == 2:
print("You have selected to order 1: " + orderFries)
elif order1 == 3:
print("You have selected to order 1: " + orderDrink)
else:
print("Invalid Input")
check = input("Is this your final item?:" + "1: " + q1 + "2: " + q2 + "Answer = ")
if check == 1:
print("Your items have been added to the basket")
break
elif check == 2:
check
elif check == 3:
check
else:
print("Invalid input")
This is the output
If you use type(order1), you'll see if your answer is a string or an int. If it's a string (and I think it is), you can convert it into int using int(order1), or replace your code by if order1 == '1'
Indentation is very important in Python. Based on how the indentations are implemented, the code blocks for conditions get executed.
A misplaced indent can lead to unexpected execution of a code block.
Here is a working demo of the ordering program
# File name: order-demo.py
moreItems = True
while (moreItems == True):
order = input("\n What would you like to order?\n"
+ " 1: Burger\n 2: Fries\n 3: Drink\n Answer = ")
if ((order == "1") or (order == "2") or (order == "3")):
print("You have selected to order " + order)
print("Your item has been added to the basket.\n")
else:
print("Invalid Input")
check = input("Is this your final item?: \n 1: Yes \n 2: No \n Answer = ")
if check == "1":
print("\n Thank you. Please proceed to checkout.")
moreItems = False
elif check == "2":
print("Please continue your shopping")
else:
print("Invalid input")
Output
$ python3 order-demo.py
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 1
You have selected to order 1
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 2
Please continue your shopping
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 2
You have selected to order 2
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 1
Thank you. Please proceed to checkout.
$
replace first line with this :
order1 = int( input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ") )
num1 = random.randint(1,20)
num2 = random.randint(1,20)
question = ["Bigger" , "Smaller"]
questiondecide = random.choice(question))
if questiondecide == "Higher":
userAnswer=input("Please find the Higher value between" + num1 "and" +
num2)
elif questiondecide == "Lower":
userAnswer=input("Please find the Lower value between" + num1 "and" +
num2)
I'm stuck on this point, I'm trying to figure out a way that if the code chooses Bigger/smaller
, the code will identify the bigger/smaller number generated and thus require the user to input the answer based on the question, but how do I identify if num1 or num2 is bigger or smaller and thus write a condition to award the user a point for answering correctly?
Basically want this: (Possible algorithm)
if set of numbers generated is higher
require user to input bigger number
userMarks = userMarks + 1
and so on if smaller number is asked, how do I write this down in Python?
import random
from random import randint
num1 = random.randint(1,20)
num2 = random.randint(1,20)
question = ["Bigger" , "Smaller"]
questiondecide = random.choice(question)
biggest = max(num1, num2)
smallest = min(num1, num2)
if questiondecide == "Bigger":
userAnswer = input("Please find the Higher value between " + str(num1) + " and " + str(num2) + ":" + "\n")
print(biggest)
if userAnswer == biggest:
print("This is the biggest number")
print("and you have chosen the bigger number!")
elif userAnswer == smallest:
print("This is the smallest number")
print("but you have not chosen the bigger number!")
elif questiondecide == "Smaller":
userAnswer = input("Please find the Lower value between " + str(num1) + " and " + str(num2) + ":" + "\n")
if userAnswer == biggest:
print("This is the biggest number")
print("but you have not chosen the smaller number!")
elif userAnswer == smallest:
print("This is the smallest number")
print("and you have chosen the smaller number!")
Hope this helps! Have any questions ask away!
I did a calculator code which works perfectly fine, but I need to append the results on a text file and/or read from the text file. I've done most of it but I'm having some errors which I need help with
-When I append the result, it just prints "5.098.042.0..." and it is supposed to be printing like this
"5 + 3 = 8
7 * 3 =43..."
It does show it in the code, but for some reason it just prints the result in the text
Please help, any suggestions to save work in the future or anything will be appreciated, thanks!
def menu():
print("\t1. Addition")
print("\t2. Substraction")
print("\t3. Multiplication")
print("\t4. Division")
print("\t5. Show")
print("\t6. Quit")
def option(min, max, exi):
option= -1
menu()
option= int(input("\n\t-> What would you like to calculate?: "))
while (option < min) or (option > max):
print("\n\t>>> Error. Invalid option.")
menu()
option= int(input("\n\t-> What would you like to calculate?: "))
return option
def add():
num1 = float(input("\tEnter a number: "))
num2 = float(input("\tEnter a number: "))
answer = num1 + num2
print("\n\t-> The result of " + str(num1) + " + " + str(num2) + "= ", answer)
return answer
def subs():
num1 = float(input("\tEnter a number: "))
num2 = float(input("\tEnter a number: "))
answer = num1 - num2
print("\n\t-> The result of " + str(num1) + " - " + str(num2) + "= ", answer)
return answer
def mult():
num1 = float(input("\tFirst number: "))
num2 = float(input("\tSecond number: "))
answer = num1 * num2
print("\n\t-> The result of " + str(num1) + " * " + str(num2) + "= ", answer)
return answer
def div():
num1 = float(input("\tFirst number: "))
num2 = float(input("\tSecond number: "))
if num2 != 0:
answer = num1 / num2
print("\n\t-> The result of " + str(num1) + " / " + str(num2) + "= ", answer)
else:
print("\n\t>>> Error. Division by zero.")
answer= "Error. Division by zero."
return answer
def result(r):
print("\n\t The last result was" , r)
def ex():
print("Goodbye")
def main():
solution = 0
op= -1
while op != 6:
op = option(0, 6, 0)
if op == 1:
solution = str(add())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 2:
solution = str(subs())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 3:
solution = str(mult())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 4:
solution = str(div())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 5:
with open ("myResultt.txt","r") as f:
for line in f:
print(line)
else:
solution = ex()
with open ("myResultt.txt","r") as f:
f.close()
main()
You prompt for the operands in the sum and etc... functions. If you want those operands to appear in the result file, you either have to return them along with the answer, or do the write in the function itself. For example,
def add():
num1 = float(input("\tEnter a number: "))
num2 = float(input("\tEnter a number: "))
answer = num1 + num2
result = "{} + {} = {}".format(num1, num2, answer)
print("\n\t-> The result of " + result)
with open ("myResultt.txt","a") as f:
f.write(result + "\n")
return answer
I need to have the output look like this: "The sum of (num1) and (num2) is (num3) and (num1)>(num2)." or visa versa with which number is bigger. I cannot figure out how to append or join these strings together without getting error codes. The + and \ are not working to join them and I even tried to make another string with a new name for it and join them all together.
CODE:
num1 = int(input("Enter number 1:"))
num2 = int(input("Enter number 2:"))
num3 = num1 + num2
print (" The sum of", (num1))
print ("and", (num2))
print ("is:", (num3))
the_text = "".join([ "The sum of", (num1), "and", (num2), "=" (num3)])
if num1 > num2:
print ("The number", (num1))
print (">")
print (num2)
elif num2 > num1:
print ("The numer", (num2))
print (">")
print (num1)
else:
print (num1)
print ("=")
print (num2)
input ("Press enter to close.")
Assuming the language required is Python,
comparison_result = ""
if num1 > num2:
comparison_result = ">"
elif num1 < num2:
comparison_result = "<"
else:
comparison_result = "="
the_text = "The sum of " + str(num1) + " and " + str(num2) + " is " + str(num1 + num2) + " and " + str(num1) + comparison_result + str(num2)
You just need to typecast the int as str.
You can use formatting:
cmp_char = ""
if a > b:
cmp_char = ">"
elif a < b:
cmp_char = "<"
else:
cmp_char = "="
print "The sum of {} and {} is {} and {} {} {}".format(num1, num2, num3, num1, cmp_char, num2)
I have been doing a school project recently which which is about a school maths quiz. I successfully done two of the three tasks of my project. However the third task is seeming quite difficult.
I'm currently trying to store the last three scores of that student. However I can't quite get it to work. I did have a look at this thread: Displaying only the highest of a person's 3 most recent scores, saved in a .txt file. However I am having an error in my code for the for:
scores = file.readlines()
Which gives me an error saying that it's not readable. So unfortunately I couldn't get that code to work.
So what I'm trying to do is score the last three scores of the student. Then if there is more then 3, then I want to delete the least recent score.
This is my code:
import random
import csv
import operator
import os.path
import sys
user_scores = {}
validclass = "No"
classfile = "Class"
studentteacher = "None"
while studentteacher == "None":
studentteacherinput = input("Are you a Teacher or a Student?")
if studentteacherinput == "Teacher":
studentteacher = "Teacher"
print(studentteacher)
elif studentteacherinput == "Student":
studentteacher = "Student"
print(studentteacher)
else:
print("Please enter the one applicable ' Student ' or ' Teacher '.")
while validclass == "No":
pupilclass = input("What class are you in or what class would you like to see??")
print(pupilclass)
if pupilclass == "1":
if os.path.exists("class1scores.txt") and studentteacher == "Teacher":
file = open("class1scores.txt", "r")
validclass = "Yes"
elif os.path.exists("class1scores.txt") and studentteacher == "Student":
file = open("class1scores.txt", "a")
classfile = "class1scores.txt"
validclass = "Yes"
else:
file = open("class1scores.txt", "w")
validclass = "Yes"
elif pupilclass == "2":
if os.path.exists("class2scores.txt") and studentteacher == "Teacher":
file = open("class2scores.txt", "r")
validclass = "Yes"
elif os.path.exists("class2scores.txt") and studentteacher == "Student":
file = open("class2scores.txt", "a")
classfile = "class2scores.txt"
validclass = "Yes"
else:
file = open("class1scores.txt", "w")
validclass = "Yes"
elif pupilclass == "3":
if os.path.exists("class3scores.txt") and studentteacher == "Teacher":
file = open("class3scores.txt", "r")
validclass = "Yes"
elif os.path.exists("class3scores.txt") and studentteacher == "Student":
file = open("class3scores.txt", "a")
classfile = "class3scores.txt"
validclass = "Yes"
else:
file = open("class1scores.txt", "w")
validclass = "Yes"
file.seek(0)
scores = file.readline()
if studentteacher == "Teacher":
teacherinput = input("How would you like to sort the list? ' Alphabetically ' to sort it alphabetically with the students highest score, ' Highest ' for the highest scores with highest to lowest or ' Average ' for average scores with highest to lowest")
if teacherinput == "Alphabetically":
print("alphabetically")
csv1 = csv.reader(file, delimiter = ",")
sort = sorted(csv1, key = operator.itemgetter(0))
for eachline in sort:
print(eachline)
sys.exit()
if teacherinput == "Highest":
print("Highest")
if teacherinput == "Average":
print("Average")
namecheck = "invalid"
while namecheck == "invalid":
name = input("Please enter your name?")
if name.isalpha():
print("Your name is valid.")
namecheck = "valid"
#file.write(name + ",")
else:
print("Please enter a valid name, only containing letters.")
operation = input("Hello %s! Would you like to do Addition, Subtraction or Multiplication" % (name))
score = 0
if operation == "Addition":
for i in range(0, 10):
number1 = random.randint(1, 20)
number2 = random.randint(1, 20)
answer = number1 + number2
question = input("What is " + str(number1) + " + " + str(number2))
if question.isdigit() == True:
int(question)
else:
question = input("Please enter a answer with digits only. What is " + str(number1) + " + " + str(number2))
if int(question) == answer:
score += 1
print("Correct!")
else:
print("Wrong!")
elif operation == "Subtraction":
for i in range(0, 10):
number1 = random.randint(1, 20)
number2 = random.randint(1, 20)
answer = number1 - number2
if number2 >= number1:
answer = number2 - number1
question = input("What is " + str(number2) + " - " + str(number1))
else:
question = input("What is " + str(number1) + " - " + str(number2))
if question.isdigit() == True:
int(question)
else:
if number2 >= number1:
answer = number2 - number1
question = input("Please enter a positive answer with digits only. What is " + str(number2) + " - " + str(number1))
else:
question = input("Please enter a positive answer with digits only. What is " + str(number1) + " - " + str(number2))
if int(question) == answer:
score += 1
print("Correct!")
else:
print("Wrong!")
elif operation == "Multiplication":
for i in range(0, 10):
number1 = random.randint(1, 20)
number2 = random.randint(1, 20)
answer = number1 * number2
question = input("What is " + str(number1) + " x " + str(number2))
if question.isdigit() == True:
int(question)
else:
question = input("Please enter a answer with digits only. What is " + str(number1) + " + " + str(number2))
if int(question) == answer:
score += 1
print("Correct!")
else:
print("Wrong!")
print("Your final score is %s/10, Well Done!" % (score))
#file.write(str(score) + "\n")
#This is the code which I was trying to use to get the last 3 scores.
user_scores = {}
for line in scores:
name, score = line.rstrip('\n').split(',')
score = int(score)
if name not in user_scores:
user_scores[name] = [] # Initialize score list
user_scores[name].append(score) # Add the most recent score
if len(user_scores[name]) > 3:
user_scores[name].pop(0) # If we've stored more than 3, get rid of the oldest
file.close()
Sorry for the inefficient method, but it's just the way I like to think. And thanks for your time.
#This is the code which I was trying to use to get the last 3 scores.
user_scores = {}
for line in scores:
name, score = line.rstrip('\n').split(',')
score = int(score)
if name not in user_scores:
user_scores[name] = [] # Initialize score list
user_scores[name].append(score) # Add the most recent score
if len(user_scores[name]) > 3:
user_scores[name].pop(0) # If we've stored more than 3, get rid of the oldest
So I took that from the link mentioned above. My aim is to try and only get three scores, and not above 3.
As you seem to know, there are different modes you can open()(2/3) a file in. If you use "a" or "w", you can't read from the file. You can add a "+", to allow reading, too, though:
open("file.txt","a+")
Also, I'm not sure what version of Python you're using, but file() is a built-in type and function in Python 2, so you shouldn't use it as a variable name if that's the version you're using.
Implement a queue - https://docs.python.org/2/library/collections.html#collections.deque
from collections import deque
for line in scores:
name, score = line.rstrip('\n').split(',')
score = int(score)
if name not in user_scores:
user_scores[name] = deque(maxlen=3)
temp_q = user_scores[name]
temp_q.append(str(score))
user_scores[name] = temp_q
Now user scores is a dict with key as name, and values as a deque object with just 3 scores. You need to iterate through them, cast the queue to list and join the elements to write them to file.
filehandle = open('outputfile.csv' ,'w')
for key, values in user_scores.iteritems():
filehandle.write(name + ',')
filehandle.write(','.join(list(values)) + '\n')
filehandle.close()