I'm brand new to both Python and StackOverflow, and I have a problem that has been stumping me for the past couple of hours.
I am making a peer-evaluation script for my high-school class. When you run the script, you input your classmate's name, then you rate them 1-10 on effort, accountability, and participation. These 3 values are then averaged. This average is assigned to the variable "grade". Since each classmate is going to get multiple grades, I need to have the "grade" variable export to another Python document where I can average every grade for each respective classmate.
So far, I have the script create a .txt file with the same name as the evaluated classmate, and the grade integer is stored there. Does anyone know of a way that I can export that integer to a Python file where I can append each successive grade so they can then be averaged?
Thanks
Python peer evaluation script
def script():
classmate = input('Please enter your classmate\'s name: ')
classmateString = str(classmate)
effortString = input('Please enter an integer from 1-10 signifying your classmate\'s overall effort during LLS: ')
effort = int(effortString)
accountabilityString = input('Please enter an integer from 1-10 signifying how accountable your classmate was during LLS: ')
accountability = int(accountabilityString)
participationString = input('Please enter an integer from 1-10 signifying your classmate\'s overall participation: ')
participation = int(participationString)
add = effort + accountability + participation
grade = add / 3
gradeString = str(grade)
print ('Your grade for ', classmate, 'is: ', grade)
print ('Thank you for your participation. Your input will help represent your classmate\'s grade for the LLS event.')
filename = (classmateString)+'.txt'
file = open(filename, 'a+')
file.write(gradeString)
file.close()
print ('Move on to next classmate?')
yes = set(['yes','y','Yes','Y'])
no = set(['no','n','No','n'])
choice = input().lower()
if choice in yes:
script()
elif choice in no:
sys.exit(0)
else:
sys.stdout.write("Please respond with 'yes' or 'no'")
script()
script()
put
import name_of_script_file
at the top of your Python file, assuming they are in the same folder.
Then you can access the variable like:
name_of_script_file.variable_name
Related
I am writing a code that basically asks for user input of an 8 digit number, that is then read from a text file to see if it is valid and then asks the user for quantity. It works fine up until it needs to calculate the total of the product (multiplied by quantity entered)? It produces this error:
Traceback (most recent call last):
File "C:\Users\User\Desktop\A453 Task 2.py", line 25, in <module>
price=float(itemsplit[2]) #price is
ValueError: could not convert string to float: 'magent,'
Here is my actual code:
loop=1
while loop==1:
print ("The Hardware Store")
print ("a - Place an order by barcode")
print ("x - Exit")
task=input("Please make your selection")
if task.lower()=="a":
print("The Hardware Store")
myfile=open("hardware_store.txt", "r") #this opens the text file
product_information=myfile.readlines() #reads the file and stores it
as a variable named variable 'details'
myfile.close() #closes the file
while True:
digits=input("Please enter your GTIN-8 code\n")
if len(digits) !=8: #if the digits aren't equal to 8 digits, the
input not accepted
print("Please enter a valid GTIN-8 code\n")
else:
break #if the code is the correct length, the loop ends
for line in product_information:
if digits in line:
productline=line
myfile=open("receipt.txt", "w") #opens receipt file
myfile.writelines("\n" + "+")
quantity=input("How much of the product do you wish to purchase?\n")
itemsplit=line.split(' ') #seperates into different words
price=float(itemsplit[2]) #price is
total=(price)*(quantity) #this works out the price
myfile.writelines("Your total spent on this product is: " +str("£:,.2f)".format(total)+"\n"))
if task.lower()=="x":
print("Thank you for visiting the hardware store, come again!")
break
else:
print("Sorry, please enter a valid input")
And here is the text file (named "hardware_store.txt")
16923577,Hammer,3.00,
78451698,32 lrg nails,2,
17825269,32 med nails,2.00,
58246375,32 sml nails,2.00,
21963780,Drill Bits set,7.00,
75124816,Lrg Brush,2.00,
78469518,Sml Brush,1.00,
58423790,Dust Pan,1.00,
88562247,32 lrg screws,2.00,
98557639,32 med screws,2.00,
37592271,32 sml screws,2.00,
50966394,screwdriver set,7.00,
75533458,wall bracket,0.70,
12345678, neodymium magent, 9.99
10101010, screws 12x50mm Pack 50, 2.79
I don't understand what is happening, it works up until you enter the desired quantity. Thanks in advance
You file hardware_store.txt has values separated on each lines by comma, not whitespace. You should split the line by ',', not by ' '.
You could also look at the CSV module in python to read your file.
In itemsplit list you have:
itemsplit[0] = "12345678,"
itemsplit[1] = "neodymium"
itemsplit[2] = "magent,"
itemsplit[3] = "9.99"
itemsplit[2] hasn't got any number to cast float.
You must use try ... except ... to catch the exception when no number is in your list item.
I've corrected your code:
so say we have a hardware_store.txtfile that contains:
12345678 5
task = ""
while task.lower() != "x":
print ("The Hardware Store")
print ("a - Place an order by barcode")
print ("x - Exit")
task=input("Please make your selection ")
if task.lower()=="a":
print("The Hardware Store")
myfile=open("hardware_store.txt", "r") #this opens the text file
product_information=myfile.readlines() #reads the file and stores it as a variable named variable 'details'
myfile.close() #closes the file
while True:
digits=input("Please enter your GTIN-8 code\n")
if not len(digits) == 8: #if the digits aren't equal to 8 digits, the input not accepted
print("Please enter a valid GTIN-8 code\n")
else:
break #if the code is the correct length, the loop ends
for line in product_information:
if digits in line:
#productline=line
myfile=open("receipt.txt", "w") #opens receipt file
myfile.write("\n" + "+")
quantity=input("How much of the product do you wish to purchase?\n")
quantity = int(quantity)
price = line.split(" ")[1]
price=float(price) #price is
total=(price)*(quantity) #this works out the price
myfile.write("Your total spent on this product is: £:({:.2f}){}".format(total, '\n'))
myfile.close()
else:
print("Sorry, please enter a valid input")
else:
print("Thank you for visiting the hardware store, come again!")
Running the code:
The Hardware Store
a - Place an order by barcode
x - Exit
Please make your selection a
The Hardware Store
Please enter your GTIN-8 code
12345678
How much of the product do you wish to purchase?
5
The Hardware Store
a - Place an order by barcode
x - Exit
Please make your selection x
Thank you for visiting the hardware store, come again!
receipt.txt:
\n
+Your total spent on this product is: £:(25.00)
You won't see \n in your text editor if you open receipt.txt, I've included the '\n' just to make it clear that there's a new line at the beginning, you'll just see an empty space in your editor followed by +Your reset of the text...
So, I have my code which is for a user wanting to loan books from a library or somewhere. They input the code for the book that they'd like to loan, I have the code with the assigned name, price etc in a text file. They input the quantity of the book that they'd like to loan then a price is calculated. If they want to loan more books, the code loops back and they can repeat the process. I want to make a separate receipt file, which stores everything that the user enters within the loop in this receipt file, and then adds everything together. I read some stuff and tried this, but there is an error and I don't know what I did wrong. Here is my code:
task=input("Enter 'b' to borrow a book, press 'x' to exit. \n")
if task.lower()== "b":
myfile=open("books.txt", "r+")
details=myfile.readlines()
while True:
book=input("Enter the 8 digit book code. \n")
while len(book) !=8
print("Your code is not 8 digits long, please try again.\n")
f = open("books.txt", "r+")
for line in f.readlines():
quantity=input("How many copies of the book do you wish to purchase?\n")
t = line.split(" ")
price = float(t[3])
code = t[1]
NameOfBook = t[2]
total=(price)* int(quantity)
with open("receipt.txt", "w") as receiptFile:
receiptFile.write(str(code))
receiptFile.write(float(NameOfItem))
receiptFile.write(int(quantity))
receiptFile.write(str(price))
receiptFile.write(str(total))
break
answer = input("Do you want to loan another book? Enter 'yes' if you would like to. ")
if answer == "yes":
continue
else:
break
What I tried to enter is this:
with open("receipt.txt", "w") as receiptFile:
receiptFile.write(str(code))
receiptFile.write(float(NameOfBook))
receiptFile.write(int(quantity))
receiptFile.write(str(price))
receiptFile.write(str(total))
I assumed that it would open the file that I made named receipt.txt and then write in each thing the user inputs, however I ended with no success. This came up instead:
Traceback (most recent call last):
File "F:\PYTHOn\New python edited for loop.py", line 19, in <module>
receiptFile.write(float(NameOfBook))
ValueError: could not convert string to float: 'Narnia,'
Please help if possible. thanks :)
I want to prompt the user to input specific data from a text file(keys) so my dictionary can give the value for each of them.
It works like this:
fin=open('\\python34\\lib\\toys.txt')
toys = {}
for word in fin:
x=fin.readline()
x = word.replace("\n",",").split(",")
a = x[0]
b=x[1]
toys[a]=str(b)
i = input("Please enter the code:")
if i in toys:
print(i," is the code for a= ", toys[i],)
else:
print('Try again')
if i == 'quit':
break
but it prints 'try again' if I input a random key from my list. (which is the following:
D1,Tyrannasaurous
D2,Apatasauros
D3,Velociraptor
D4,Tricerotops
D5,Pterodactyl
T1,Diesel-Electric
T2,Steam Engine
T3,Box Car
T4,Tanker Car
T5,Caboose
B1,Baseball
B2,Basketball
B3,Football
B4,Softball
B5,Tennis Ball
B6,Vollyeball
B7,Rugby Ball
B8,Cricket Ball
B9,Medicine Ball
but if I do it in order it works. How can I fix this program so I can input any key at any time and it will still print its corresponding value?
You need to read in the whole file before prompting for your search term. So you'll need two loops -- one to get the whole data in, and a second loop to search through he data.
Here's what your updated code will look like. I replaced the file input with an array so that I could run it using a web tool:
fin=['D1,Tyrannasaurous','D2,Apatasauros','D3,Velociraptor' ]
toys = {}
for word in fin:
x = word.replace("\n",",").split(",")
a = x[0]
b=x[1]
toys[a]=str(b)
while 1:
i = input("\nPlease enter the code:")
if i in toys:
print(i," is the code for a= ", toys[i],)
else:
print('\nTry again')
if i == 'quit':
break
Output here: https://repl.it/BVxh
To read the file into dictionary:
with open('toys.txt') as file:
toys = dict(line.strip().split(',') for line in file)
To print values corresponding to the input keys provided by a user from a command-line interactively until quit key is received:
for code in iter(lambda: input("Please enter the code:"), 'quit'):
if code in toys:
print(code, "is the code for toy:", toys[code])
else:
print(code, 'is not found. Try again')
It uses two-argument iter(func, sentinel).
I'm in a beginning programming class and our program is to create a program to gather information on four different zip codes and five different types of coffee drinks to see if our friend should open up a coffee shop in that area.
My program will not accept my variables
My other problem with my program is it won't loop back around to get more input. I tried to reset the user answer to allow it to go back to the beginning but it doesn't read it.
I set up an accumulater for my if statement
Example
while UserAnswer == "yes":
ZipCode = input("Enter Zip Code: ")
print("Here are your menu choices: \n m = Cafe Mocha\n l = Cafe Latte ")
print(" r = Cafe Regular \n d = Cafe Regular Decafe \n c = Cafe Carmel")
CoffeeType = input("Enter your order: ")
Quantity = input("Enter quantity: ")
#Start inner loop with if statements to determine the quantity of the coffee
while UserAnswer == "no"
if ZipCode == 48026:
if CoffeeType == "m":
CM48026 = Quanity + CM48026'
My accumulater CM48026 doesn't save and at the end it prints out 0.
You need to provide an initial value for the accumulator. And that should be done outside the inner loop. Because you are using the same variable in the expression which provides the value for the accumulator.
So, doing a = b + a will not really work, as the value of a at the right is not really defined.
Moreover, there's a typo for the variable quantity, and that might actually be the reason why your code is not working!
I am very new to Python programming (15 minutes) I wanted to make a simple program that would take an input and then print it back out. This is how my code looks.
Number = raw_input("Enter a number")
print Number
How can I make it so a new line follows. I read about using \n but when I tried:
Number = raw_input("Enter a number")\n
print Number
It didn't work.
Put it inside of the quotes:
Number = raw_input("Enter a number\n")
\n is a control character, sort of like a key on the keyboard that you cannot press.
You could also use triple quotes and make a multi-line string:
Number = raw_input("""Enter a number
""")
If you want the input to be on its own line then you could also just
print "Enter a number"
Number = raw_input()
I do this:
print("What is your name?")
name = input("")
print("Hello" , name + "!")
So when I run it and type Bob the whole thing would look like:
What is your name?
Bob
Hello Bob!
# use the print function to ask the question:
print("What is your name?")
# assign the variable name to the input function. It will show in a new line.
your_name = input("")
# repeat for any other variables as needed
It will also work with: your_name = input("What is your name?\n")
in python 3:
#!/usr/bin/python3.7
'''
Read list of numbers and print it
'''
def enter_num():
i = input("Enter the numbers \n")
for a in range(len(i)):
print i[a]
if __name__ == "__main__":
enter_num()
In the python3 this is the following way to take input from user:
For the string:
s=input()
For the integer:
x=int(input())
Taking more than one integer value in the same line (like array):
a=list(map(int,input().split()))