how to fix 'pylint too many statements'? - pylint

Is there a way to condense the following code to remove the pylint too many statements error. All this code is contained within a single function: -
selection = input("Enter 1, 2, 3, 4 or 5 to start: \n")
if selection == "1":
print("\nYou have selected "+"'"+question_data[0][0]+"', let's begin!")
for key in science:
print("--------------------------------------------------------\n")
print(key)
for i in science_choices[num_question-1]:
print("")
print(i)
choice = input("Enter you answer (A, B or C): \n").upper()
answers.append(choice)
correct_answers += check_correct_answer(science.get(key), choice)
num_question += 1
player_score(correct_answers, answers)
elif selection == "2":
...................................................
elif selection == "3":
...................................................
elif selection == "4":
...................................................
elif selection == "5":
...................................................
else:
print("\nYou entered an incorrect value.Please try again.\n")
start_new_quiz()
the program works as is but it's for a college assignment and I would prefer not to submit with pylint errors.

One obvious way is to create a function for each selection:
selection = input("Enter 1, 2, 3, 4 or 5 to start: \n")
if selection == "1":
treat_one()
elif selection == "2":
...................................................
elif selection == "3":
...................................................
elif selection == "4":
...................................................
elif selection == "5":
...................................................
else:
print("\nYou entered an incorrect value.Please try again.\n")
start_new_quiz()
def treat_one():
print("\nYou have selected "+"'"+question_data[0][0]+"', let's begin!")
for key in science:
print("--------------------------------------------------------\n")
print(key)
for i in science_choices[num_question-1]:
print("")
print(i)
choice = input("Enter you answer (A, B or C): \n").upper()
answers.append(choice)
correct_answers += check_correct_answer(science.get(key), choice)
num_question += 1
player_score(correct_answers, answers)
You could also create a dictionary:
functions_to_use = {
"1": treat_one,
...
}
function = functions_to_use.get(selection)
if function is None:
print("\nYou entered an incorrect value.Please try again.\n")
else:
function()
Of if you want to over-engineer it, use getattr:
function = getattr("treat_{selection}", error)
function()
def error():
print("\nYou entered an incorrect value.Please try again.\n")

Related

How do I make this flow from def get_burger_choice to def get_burger_price

So I am trying to make this continue from get_burger_choice to get_burger price to where it would flow and finish the program. I am trying to write this program to where I could get the type of burger then the price from get_burger_price. Heres the problem, I do not know how to intergrate it towards doing that. I am completely stuck after the part where it says "no" at the end part of get_burger_choice to where I can transition to get_burger_price
Here is the code that I used : the part highlighted is where Im having trouble transitioning:I would like it to where if the user says no, it would ask if they would like to see the price, and it would transition towards get_burger_price
def get_burger_choice():
SIZE = 3
burgers = ["Cheesy", "Regular", "Veggie" ]
search = True
while search == True:
index = 0
found = False
print("What type of burger would you like?")
searchValue = input()
while found == False and index <= SIZE - 1:
if burgers[index].lower()==searchValue.lower():
found = True
else:
index = index + 1
if found:
print("That is on our menu")
else:
print("That is not in our menu")
print("Do you want see another burger? yes/no: ")
tryagain = input()
if tryagain.lower() =='no':
print("Would you like to see the price? yes or no: ")
if
def price_burger(burger_choice, burger_price):
if burger_price == 'cheesy':
burger_price = 3.00
elif burger_choice == 'regular':
burger_price = 2.00
elif burger_choice == 'veggie':
burger_price = 2.00
else:
print("we do not have that, sorry")
return burger_price
def total_price(burger_price, burger_choice=None):
print("The burger cost $", burger_price)
def closing(burger_choice):
if burger_choice == 'cheesy':
print("Nice selection, This is our best!")
else:
print("enjoy!")
def main(burger_price = 0):
choice = "yes"
while choice != "no":
burger_choice = get_burger_choice()
burger_price = price_burger(burger_choice,burger_price)
total_price(burger_price)
closing(burger_choice)
choice = input("\nWould you like to try again? yes or no: ")
main()

Rosalind Translating RNA into Protein problem

Hello i tried doing this problem from ROSALIND but when i put the example rna sequence (AUGGCCAUGGCGCCCAGAACUGAGAUCAAUAGUACCCGUAUUAACGGGUGA) it produced me the wrong output "['M', 'M', 'N', 'I']" instead of the suggested "MAMAPRTEINSTRING".I tried to modify the code but still not it did not give me the desired output.I would like some help if someone can.
Here is my code:
**dna_seq = input("PLace your RNA sequence here(it must not exceed 1kb):")
list = []
for x in range (0,len(dna_seq),3):
if dna_seq[x:x+3] == "AUG":
list.append("M")
elif dna_seq[x:x+3] == ("UUU" or "UUC"):
list.append("F")
elif dna_seq[x:x+3] == ("UUA" or "UUG" or "CUU" or "CUC" or "CUA" or "CUG"):
list.append("L")
elif dna_seq[x:x+3] == ("AUU" or "AUC" or "AUA"):
list.append("I")
elif dna_seq[x:x+3] == ("GUA" or "GUG" or "GUC" or "GUU"):
list.append("V")
elif dna_seq[x:x+3] == ("UCA" or "UCU" or "UCG" or "UCC"):
list.append("S")
elif dna_seq[x:x+3] == ("CCU" or "CCA" or "CCC" or "CCG" or "AGU" or "AGC"):
list.append("P")
elif dna_seq[x:x+3] == ("ACA" or "ACU" or "ACG" or "ACC"):
list.append("T")
elif dna_seq[x:x+3] == ("GCU" or "GCA" or "GCG" or "GCC"):
list.append("A")
elif dna_seq[x:x+3] == ("UAU" or "UAC"):
list.append("Y")
elif dna_seq[x:x+3] == ("UAA" or "UAG" or "UGA"):
list.append("STOP")
elif dna_seq[x:x+3] == ("CAU" or "CAC"):
list.append("H")
elif dna_seq[x:x+3] == ("CAA" or "CAG"):
list.append("Q")
elif dna_seq[x:x+3] == ("AAU" or"AAC"):
list.append("N")
elif dna_seq[x:x+3] == ("AAA" or "AAG"):
list.append("K")
elif dna_seq[x:x+3] == ("GAU" or "GAC"):
list.append("D")
elif dna_seq[x:x+3] == ("GAA" or "GAG"):
list.append("E")
elif dna_seq[x:x+3] == ("UGU" or "UGC"):
list.append("C")
elif dna_seq[x:x+3] == ("UGG"):
list.append("W")
elif dna_seq[x:x+3] == ("CGA" or "CGG" or "CGC" or "CGU" or "AGA" or "AGG"):
list.append("R")
elif dna_seq[x:x+3] == ("GGU" or "GGC" or "GGA" or "GGG"):
list.append("G")
print(list)**
Thanks for your time!
The statement ("CAU" or "CAC") evaluates to "CAU".:
>>> ("CAU" or "CAC")
'CAU'
Thus your elif statements will only ever check the first codon in the list. You can fix this by rewriting your statements to this format:
elif dna_seq[x:x+3] == "CAU" or dna_seq[x:x+3] "CAC":
But much better would be to make a dictionary where your codons are the keys and the values are the amino acids corresponding to that codon. Then build your protein sequence by getting the value of a codon from the dictionary and add it your list.
Finally, don't name a variable in python list. It overwrites the built in function list().

discord.py rewrite | Problem with getting author message

I've been making a number game command in my server, and someone recommended I add difficulties. So, I have 3 difficulties for the user to chose from.
I have already got a bit of code which got the author's response and worked, so I re-used it in my code, and now I am stumped. It may be glaringly obvious, but I cannot find it:
#client.command(name='numgame',
brief='Guess a number between 1 and 100',
pass_ctx=True)
async def numgame(ctx):
if ctx.author.id != 368442355382222849:
await ctx.send('Command currently disabled')
return
await ctx.send('Difficulties: a] 1-10 b] 1-50 c] 1-100')
msg = await client.wait_for('message', check=check(ctx.author), timeout=30)
diff = str(msg.content)
if diff == 'a':
max = 10
number = random.randint(1,10)
await ctx.send('You have 5 guesses')
await ctx.send('Pick a number between 1 and 10')
elif diff == 'b':
max = 50
number = random.randint(1,50)
await ctx.send('You have 5 guesses')
await ctx.send('Pick a number between 1 and 50')
elif diff == 'c':
max = 100
number = random.randint(1,100)
await ctx.send('You have 5 guesses')
await ctx.send('Pick a number between 1 and 100')
else:
ctx.send('Please try the command again...')
return
msg = None
This is the check I am using:
def check(author):
def inner_check(message):
# author check
if message.author != author:
return False
# inner check
try:
int(message.content)
return True
except ValueError:
return False
When I respond to the bot in-chat with "a", "b" or "c", I get no response.
I disabled the command for everyone but me whilst I tried to fix it, but I have no idea how to start.
I would appreciate an answer, as I don't see the solution myself, thanks!
[I didn't show the actual number game, because it is irrelevant and long]
Just create a new check function that does what you want.
def abc_check(author):
def inner_check(message):
return author == message.author and message.content in ('a', 'b', 'c')
return inner_check

Balance variable keeps resetting after each loop

I was wondering how I'm supposed to get my "balance" variable to change depending on the value added or subtracted to it each time, without resetting for the next loop.
At the moment it will add or subtract a given value and return the correct number but on the next loop it will use the original base value instead of using the new value from the previous loop.
import time
print ("Welcome to balance tracker!")
sBal=float(input ("Starting balance: "))
float(sBal)
transactionAmounts = []
transactionTypes = []
print ("Your current balance is", '$',sBal)
while True:
input("Press enter to continue")
print ("""
------------
[A]ddition
[S]ubtraction
[H]istory
[I]nformation
[Q]uit
------------
""")
choice=input("What would you like to do? ")
choice = choice.upper()
if choice == "A":
aval=float(input ("Enter amount you would like to add here: "))
nBal=(sBal)+(aval)
transactionTypes.append('Addition')
transactionAmounts.append(float(aval))
balance = float(sBal) + aval
print ("Your current balance is $",balance)
elif choice == "S":
aval=input("Enter amount you would like to subtract here: ")
nBal=float(sBal)-float(aval)
transactionTypes.append('Subtraction')
transactionAmounts.append (float(aval))
balance = float(sBal) - aval
print ("Your current balance is $",balance)
elif choice == "H":
aCount = 1
tCount = 0
for i in transactionAmounts:
print ('Transaction',aCount,':',transactionTypes[tCount],i)
aCount = aCount + 1
tCount = tCount + 1
elif choice == "Q":
break
else:
print ("invalid choice")
The solution to your problem is that when your assigning your balance variable, your adding sBal(starting balance) every time to the amount they would like to add... This is causing the balance to always be set back to the starting balance plus or minus the amount added. Try defining sBal as balance also like so...
balance = float(input("Starting balance: ")) #line 5
float(sBal) #<<<can be deleted #line 6
Also don't forget to alter anywhere in the code that calls sBal to call balance.
print("Your current balance is ", "$", difference) #line 9
balance = float(balance) (+ or -) aval #lines 30 and 37
Also you can delete your nBal(new balance) as it is never called.

elasticsearch: using wildcards for integer values

I would like to find all objects which have a year value which starts with 20... so I would like to search for 20*, where * is a wild card.
I tries something like
'match_phrase_prefix': { 'year': { 'query': '20*', 'max_expansions': 50}}
but I guess this only works for strings. How would I do this for integers?
EDIT: I found a solution... its not pretty but it works
year_query = '20'
if len(str(year_query)) < 4:
try:
low_year, high_year = extend_year(int(year_query))
filter_list.append({"range": {"year": {"gte": low_year, "lte": high_year}}})
except ValueError:
print "Not a valid input for year"
pass
else:
for year in year_query.split(','):
if '-' in year:
year_range = year.split('-')
high_year = year_range[1].strip()
if len(high_year) < 4:
low_year, high_year = extend_year(high_year)
try:
filter_list.append({"range" : {"year" : {"gte" : int(year_range[0].strip()),"lte" : int(high_year),"format": "yyyy"}}})
except ValueError:
print "Not a valid input for year"
pass
else:
try:
filter_list.append({ "match": {"year": int(year.strip()) }})
except ValueError:
print "Not a valid input for year"
pass
with the function
def extend_year(input_year):
length = len(str(input_year))
if length == 4:
return input_year, 0
elif length == 3:
return input_year*10, int(str(input_year) + '9')
elif length == 2:
return input_year*100, int(str(input_year) + '99')
elif length == 1:
return input_year*1000, int(str(input_year) + '999')
elif length == 0:
return 0, 9999
else:
return input_year, 0
if anybody can come up with a better solution please let me know
This should work
'range': { 'year': { 'gte': 2000, 'max_expansions': 50}}

Resources