I am writing a program for my business that will require some division. For one of the user inputs, it is possible that 0 is a variable but it will then be required to be divided. If opps == 0 then sales and addon are irrelevant, but total might still have a variable assigned to it by the user. Line 9 contains my solution, but it requires the entering of false information. Is there any better way to handle this?
ans = 'y'
opps = []
sales = []
addon = []
total = []
while ans in ['y', 'Y', 'yes', 'Yes', 'YES']:
opps.append(int(input("Number of opportunities: ")))
while opps[-1] == 0:
opps.append(int(input("Number of opportunities can not equal 0, input at least 1: ")))
sales.append(int(input("Quantity of of sales: ")))
addon.append(float(input("Addon $ amount: ")))
total.append(float(input("Sales dollar amount: ")))
cra = (sales[-1] / opps[-1]) * 100
addonp = (addon[-1] / total[-1]) * 100
print("\nResults: " + "\nAddon %: " + "%.2f" % addonp + "%\n" "CRA %: " + "%.2f" % cra + "%\n")
ans = str(input("Continue? (Y/N)"))
if ans not in ['y', 'Y', 'yes', 'Yes', 'YES']:
oppst = sum(opps)
salest = sum(sales)
addont = sum(addon)
cratp = (salest / oppst) * 100
tsales = sum(total)
addontp = (addont / tsales) * 100
print("\nYour totals are: \n" +
"\n" +
"Opportunities: " + str(int(oppst)) + "\n" +
"\n" +
"# of Sales: " + str(int(salest)) + "\n" +
"\n" +
"Addon $ amount: " + "$" + "%.2f" % addont + "\n" +
"\n" +
"Addon %: " + "%.2f" % addontp + "%\n" +
"\n" +
"CRA %: " + "%.2f" % cratp + "%\n" +
"\n" +
"Total Sales: " + "$" + "%.2f" % tsales
)
input("\nPress any key to close...")
Related
I am executing PostgreSQL13 queries coding them in python 3.9 using the psycopg2 library. I also am working with PostGIS extension over PostgreSQL.
Kindly look for the comment which points out the line which causes the syntax error. I am having trouble both understanding what is the syntax error and how to debug it since I need to execute PostgreSQL queries using python so any tips will be greatly appreciated.
def corefunc(rf, openConnection):
pcur = openConnection.cursor(name="pcur" + rf)
rcur = openConnection.cursor(name="rcur" + rf)
acur = openConnection.cursor()
rcur.execute("SELECT geom FROM " + rf)
for number in range (1, 5):
acur.execute("DROP TABLE IF EXISTS " + "pf"+ rf)
acur.execute("CREATE TABLE " + "pf" + rf + " (index integer, sums integer)")
pcur.execute("SELECT geom FROM " + "pf" + str(number))
row = 1
for each in rcur.fetchall():
if number == 1: acur.execute("INSERT INTO " + "pf" + rf + " (index, sums) VALUES (" + str(row) + ",0)")
for eachone in pcur.fetchall():
#-------------------------------------------- the statement below gives the syntax error
acur.execute("UPDATE TABLE " + "pf" + rf + " SET sums = sums + "\
+"ST_Contains(" + " ' " + each[0] + " ' " + ", " + " ' " + eachone[0] + " ' " + ")::int WHERE index = " + str(row))
row = row + 1
def parallelJoin (pointsTable, rectsTable, outputTable, outputPath, openConnection):
#Implement ParallelJoin Here.
cursor = openConnection.cursor()
cursor.execute("SELECT COUNT(*) FROM " + pointsTable)
size_data = (cursor.fetchall())[0][0]
for number in range(1, 5):
cursor.execute("DROP TABLE IF EXISTS pf" + str(number))
cursor.execute("CREATE TABLE pf" + str(number) + " AS SELECT * FROM "
+ pointsTable + " LIMIT " + str(size_data/4)
+ " OFFSET " + str(((number-1)*size_data)/4))
cursor.execute("SELECT COUNT(*) FROM " + rectsTable)
size_rects = (cursor.fetchall())[0][0]
for number in range(1, 5):
cursor.execute("DROP TABLE IF EXISTS rf" + str(number))
cursor.execute("CREATE TABLE rf" + str(number) + " AS SELECT * FROM "
+ pointsTable + " LIMIT " + str(size_rects/4)
+ " OFFSET " + str(((number - 1) * size_rects)/4))
threads = dict()
for number in range(0, 4):
threads[number] = threading.Thread(target=corefunc, args=("rf" + str(number + 1), openConnection))
threads[number].start()
break
while threads[0].is_alive() or threads[1].is_alive()\
or threads[2].is_alive() or threads[3].is_alive(): pass
# more shit to do
Nevermind, I just thought checking out the syntax from somewhere and I found the problem. To update table, the query begins with "UPDATE...." not "UPDATE TABLE.....".
name = input("Въведете име: ")
Town = input("град: ")
school = input("Училище: ")
age= input("години: ")
hoby = input("Хоби: ")
sport = input("спорт: ")
print ("")
print ("Здравейте, казвам се" + name + " ,аз съм на " + age + "години.")
print ("")
print ("Аз живея в/във" + Town + ". " + "Уча в" + school + ".")
print ("Моето хоби е " + hoby + " ,и спортувам " + sport + ".")
print ("")
print ("Въведете 3 числа за триъгълника")
a = input("Страна А ")
b = input("Страна Б ")
c = input("Страна С ")
hc = int(input("Височината на триъгълника е "))
p = int(a) + int(b) + int(c)
S = int((c * hc) / 2)
print ("Периметъра на триъгълника е: " + int(p) + " ,a лицето е: " + int(S))
this is the code.
Error:
Traceback (most recent call last):
File "C:\Users\B21pa\Desktop\Python\Homework\Homework-3\homework-3.py", line 20, in <module>
S = int((c * hc) / 2)
TypeError: unsupported operand type(s) for /: 'str' and 'int'
You will need to cast the inputs to int() where you explicitly expect them to be integers. All input captured from the terminal comes across as string. Attempting to add strings just concatenates them. Division is not supported on strings hence this error that / is an invalid operand for type str.
Your code fixed should be:
name = input("Въведете име: ")
Town = input("град: ")
school = input("Училище: ")
age= input("години: ")
hoby = input("Хоби: ")
sport = input("спорт: ")
print ("")
print ("Здравейте, казвам се" + name + " ,аз съм на " + age + "години.")
print ("")
print ("Аз живея в/във" + Town + ". " + "Уча в" + school + ".")
print ("Моето хоби е " + hoby + " ,и спортувам " + sport + ".")
print ("")
print ("Въведете 3 числа за триъгълника")
a = int(input("Страна А "))
b = int(input("Страна Б "))
c = int(input("Страна С "))
hc = int(input("Височината на триъгълника е "))
p = a+b+c
S = int((c * hc) / 2)
print ("Периметъра на триъгълника е: " + str(p) + " ,a лицето е: " + str(S))
This script was created by an ex-lab member that was quite a bit more adapt at Python scripting than I am.
I am attempting to find Cooccupancy between annotated peaks in "exon" regions of the entire human h19 genome. However, after trying to get this to run for about an hour I am looking for help.
Here is the script:
#!/usr/bin/python
import math
import sys
import re
import csv
import MySQLdb
import itertools
import argparse
# format for execution: ./findCooccupancy.py <loci file> <comma separated list of marks to check> <window size> <outputfile>
# example: ./findCooccupancy.py AllGenes.txt PolII-ChIP,KAP1-ChIP,Hexim 150 output.txt
# format of loci file:
# chr2 12345678 12345900 GENEA 1 +
# chr4 987654321 98765000 GENEB 1 -
# etc...
locifile = sys.argv[1]
marks = sys.argv[2]
window = int(sys.argv[3])
outputfile = sys.argv[4]
loci = list(csv.reader(open(locifile, 'rb'),delimiter='\t'))
#loci = list(itertools.chain.from_iterable(loci))
db = MySQLdb.connect(host="localhost",user="snrnp",passwd="snrnp",db="snrnp")
cur = db.cursor()
cntdict = {}
for mark in marks.split(","):
cntdict[mark] = []
counter = 1
for locus in loci:
print "Working on line# " + str(counter)
counter += 1
if str(locus[5]) == "+":
exon = locus[1]
else:
exon = locus[2]
for mark in marks.split(","):
# this is incredibly dirty. sorry. I don't have time to do this better
if mark == 'PolII-ChIP':
cur.execute("select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and (abs(summit - " + str(exon) + ") < " + str(window) + ")")
#print "select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and (abs(summit - " + str(exon) + ") < " + str(window) + ")"
else:
cur.execute("select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and ((chr_start < " + str(exon) + " and chr_end > " + str(exon) + ") or (abs(chr_start - " + str(exon) + ") < " + str(window) + ") or (abs(chr_end - " + str(exon) + ") < " + str(window) + "))")
#print "select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and ((chr_start < " + str(exon) + " and chr_end > " + str(exon) + ") or (abs(chr_start - " + str(exon) + ") < " + str(window) + ") or (abs(chr_end - " + str(exon) + ") < " + str(window) + "))"
cnt = cur.fetchone()[0]
if cnt > 0:
cntdict[mark].append(",".join(locus))
convertedlist = []
for key in cntdict.keys():
convertedlist.append(cntdict[key])
intersectlist = set(convertedlist[0]).intersection(*convertedlist[1:])
for key in cntdict.keys():
print str(key) + " hits: " + str(len(cntdict[key]))
print "\nTotal Intersection Count: " + str(len(intersectlist))
with open(outputfile, 'w') as outputwriter:
for line in intersectlist:
outputwriter.write(line + "\n")
This is the command line that I have been using:
./findCooccupancy.py ~/code/snRNP/analysis/from\ sequencing/KEC_Project/Pol-IIAnnotatedPeaksGenome.txt PolII-ChIP 150 KECExonOccupancy.txt
This is the latest error message I have received:
Working on line# 1
Traceback (most recent call last):
File "./findCooccupancy.py", line 41, in <module>
cur.execute("select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and (abs(summit - " + str(exon) + ") < " + str(window) + ")")
File "/Library/Python/2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "/Library/Python/2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1054, "Unknown column 'Start' in 'where clause'")
My assignment was to write a program which extracts the first/last names, birth year, and ID from a file, manipulate that information to create a username and formatted ID, prompt the user for 3 test grades, calculate the average, and finally write all the information to a new file. This is the program I wrote, and the error I got is listed below the program.
Define main function
def main():
infile = open("studentinfo.txt", "r")
data = infile.read()
fName, lName, ID, year = data.split(",")
year = int(year)
Prompt the user for three test scores
grades = eval(input("Enter the three test scores separated by a comma: "))
Create a username
uName = (lName[:4] + fName[:2] + str(year)).lower()
converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
grade_1, grade_2, grade_3 = grades
Convert the grades to strings so they can be written to a new file
[grade_1, grade_2, grade_3] = [str(grade_1), str(grade_2), str(grade_3)]
Calculate the average
average =(grade_1 + grade_2+ grade_3)/3
Convert the average to a string
average = str(average)
Write the information the file
outfile = open("studentreport.txt", "w")
outfile.write("*******Student Report*******\nStudent Name:" + fName + " " + lName)
outfile.write("\nStudent ID: " + converted_id + "\n" + "Username: " + uName + "\n\n")
outfile.write("Grade 1: " + grade_1 + "\n" "Grade 2: " + grade_2 + "\n" + "Grade 3: " + grade_3 + "\n" + "Average: " + average)
infile.close()
outfile.close()
main()
Traceback (most recent call last):
File "C:/Users/ovi/Desktop/Python Project 1.py", line 34, in
main()
File "C:/Users/ovi/Desktop/Python Project 1.py", line 22, in main
average =(grade_1 + grade_2+ grade_3)/3
TypeError: unsupported operand type(s) for /: 'str' and 'int'
You need to convert your converted string grades to floats (or int)
average =(float(grade_1) + float(grade_2)+ float(grade_3))/3.0
average = str(average)
You need to convert the variables of type int to strings.
outfile.write("Grade 1: " + str(grade_1) + "\n" "Grade 2: " + str(grade_2) + "\n" + "Grade 3: " + str(grade_3) + "\n" + "Average: " + str(average))
OR
You could simply do like this..
>>> gr1 = 23
>>> gr2 = 45
>>> gr3 = 56
>>> total = gr1+gr2+gr3
>>> avg = total/3
>>> l = [gr1, gr2, gr3, total, avg]
>>> print("GRade 1: {} grade 2: {} grade 3: {} total: {} average : {}".format(*l))
GRade 1: 23 grade 2: 45 grade 3: 56
In my Code below I am having issues with 2 things. For one The math in the function on lines 40 (examPoints) and 47 (hwkPoints) is being passed a range of values in a list on line 94. It should be taking the scores and adding them up but for some reason it isn't adding the last number on each range passed.
ex: for myValues[11:13] it is being passed the numbers 75, 95, and 97 but it only adds the first 2 and not the last.
My code is here:
from time import asctime
from time import localtime
def findGrade(myGrade): #argument number in range of 1 - 100 or float myNum?
if myGrade >= 90:
letterGrade = "A"
if myGrade >= 80:
letterGrade = "B"
if myGrade >= 70:
letterGrade = "C"
if myGrade >= 60:
letterGrade = "D"
if myGrade < 60:
letterGrade = "F"
return letterGrade
def calculatePointsEarned(hwkGrades, examGrades):
hwkTotal = float(hwkPoints(hwkGrades))
#print hwkTotal
examTotal = float(examPoints(examGrades))
#print examTotal
myAverage = (hwkTotal + examTotal) / possiblePoints
myAverage = myAverage * 100.0
#myAverage = int(myAverage)
return myAverage
def totalPoints(hwkGrades, examGrades):
hwkTotal = int(hwkPoints(hwkGrades))
examTotal = int(examPoints(examGrades))
allPoints = str((hwkTotal + examTotal))
return allPoints
#Create newtimeline using day of week, space, month, space, day, space, year, space time from asctime function
def timeMessage():
localtime()
newTimeline = asctime()
return newTimeline
def examPoints(examValues):
myGrades = 0
for grade in examValues:
myGrades = int(grade) + myGrades
#print str(myGrades) + " exam\n"
return myGrades
def hwkPoints(hwkValues):
myGrades = 0
for grade in hwkValues:
myGrades = int(grade) + myGrades
#print str(myGrades) + " hwk"
return myGrades
def requestMessage (myValues, myTime):
nameLine = myValues[1] + ", " + myValues[2] + "\t" + myValues[0] + "\t" + myValues[3]
examScore = "Exam " + "- " + myValues[11] + ", " + myValues[12] + ", " + myValues[13]
hwkScore = "Homework " + "- " + myValues[4] + ", " + myValues[5] + ", " + myValues[6] + ", " + myValues[7] + ", " + myValues[8] + ", " + myValues[9] + ", " + myValues[10]
pointsEarned = "Total points earned " + "- " + totalPoints(myValues[4:10], myValues[11:13])
myGrade = "Grade: " + str(theAverage) + " that is a " + findGrade(theAverage)
message = nameLine + "\n" + examScore + "\n" + hwkScore + "\n" + pointsEarned + "\n" + myGrade + "\n" + myTime
return message
def fileOutput(studentID, lastName, firstName, dateTime):
myLine = studentID + " " + lastName + ", " + firstName + " " + dateTime + "\n"
return myLine
#Create input stream from grades.dat and assign to infile
inFile = open('grades.dat', "r")
#Create output stream to results.dat and assign to outfile
outFile = open('results.dat', 'w+')
myTime = timeMessage()
theAverage = 0
theLettergrade = ""
theMessage = ""
possiblePoints = 550
theRequest = ""
studentID = raw_input("Please input student ID: ")
myLine = "notemptystring"
while myLine != "": #may be wrong Is myline not equal to the empty string?
myLine = inFile.readline() #may be wrong Read line from infile and assign to myline
myLine = myLine.strip('\r\n')
myValues = myLine.split(",") #Separate values in myline and assign to myvalues
if studentID == myValues[0]:
#print myValues
#Call calculatePointsEarned function with a list of homework values and a list of exam values and assign to theaverage
theAverage = calculatePointsEarned(myValues[4:10], myValues[11:13])
#print theAverage
theLettergrade = findGrade(theAverage) #Call findGrade function with theaverage and assign to thelettergrade)
#print theLettergrade
#Call fileOutput function with studentid, lastname, firstname, and datetime to get message for writing to output file, and assign to therequest
theRequest = fileOutput(myValues[0], myValues[1], myValues[2], timeMessage())
#print theRequest
theMessage = requestMessage(myValues, timeMessage()) #Call requestMessage with myline and mytime for message to display, and assign to themessage
#Write theRequest to outfile
outFile.write(theRequest)
print theMessage
else: #is studentid not equal to first element in myValues
"Do Nothing"
#close infile and outfile
inFile.close()
outFile.close()
Edit: Sorry for the link I was having problems getting the code to look right on here.
for myValues[11:13] it is being passed the numbers 75, 95, and 97 but it only adds the first 2 and not the last
myValues[11:13] selects two elements, not three. The end index (13) is not included in the range.
Have a read of Explain Python's slice notation