I believe I have something incorrect with my function but I still pretty new to python and functions in general and I am missing what my issue is. In the code below I am sending no values into the function, but once the function reads the database I want it to pull the values from the database back into the main program. I placed a print statement inside of the function to make sure its pulling the values from the database and everything works properly. I copy and pasted that same print line right after the function call in the main area but I am getting a NameError: 'wins' is not defined. This leads me to believe I am not returning the values correctly?
#Python3
import pymysql
def read_db():
db = pymysql.connect(host='**********',user='**********',password='**********',db='**********')
cursor = db.cursor()
sql = "SELECT * FROM loot WHERE id = 1"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
wins = row[2]
skips = row[3]
lumber1 = row[4]
ore1 = row[5]
mercury1 = row[6]
db.commit()
db.close()
print ("Wins = ",wins," Skips = ",skips," Lumber = ",lumber1," Ore = ",ore1," Mercury = ",mercury1)
return (wins, skips, lumber1, ore1, mercury1)
read_db()
print ("Wins = ",wins," Skips = ",skips," Lumber = ",lumber1," Ore = ",ore1," Mercury = ",mercury1)
Doing just read_db() causes the return values to be thrown out. You need to assign the return values to variables:
wins, skips, lumber, ore = read_db()
The fact that you're returning a variable called wins does not mean a wins variable will become available in the scope you call read_db() from. You need to assign return values explicitly.
Related
So, I am new at DataBases and I have a question. I first made a re-search in the internet but could not find anything or actually I could not understand correctly what they were explaining. Before starting with my question I want to say that I am currently working in a Discord Bot in Python as Main Language and I am trying to create a per-server-prefix system. I have already made it once but in .JSON format. Then I heard that using .JSON to save this kind of Data is not actually good so I moved to DataBases. Now, my question is:
I have stored the guild_id and prefix in my DB, how could I use that for a per-server-prefix system? I have not tried anything yet except writing the Code to store both Texts. I would really love if anyone could explain to me not just tell me the Code! Any answer will be appreciated <3.
Main.py:
def get_prefix(client, message):
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT prefix FROM prefixes WHERE guild_id = {message.guild.id}")
result = cursor.fetchone()
if result is None:
return "/"
else:
client = commands.Bot(command_prefix = get_prefix)
Prefixes.py (COGS):
#commands.command()
#commands.has_permissions(administrator=True)
async def prefix(self, ctx, prefix=None):
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT prefix FROM prefixes WHERE guild_id = ?", ctx.guild.id)
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO prefixes(guild_id, prefix) VALUES(?,?)")
val = (ctx.guild.id, prefix)
await ctx.channel.send(f"{prefix}")
elif result is not None:
sql = ("UPDATE prefixes SET prefix = ? WHERE guild_id = ?")
val = (prefix, ctx.guild.id)
await ctx.channel.send(f"update `{prefix}`")
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()
That is pretty much the whole code. If you think anything should be changed or have any suggestions, answer in the comments!
All you need to do is, after the else, put return result. For example:
result = cursor.fetchone()
if result is None:
return "/"
else:
return result
cursor.fetchone() returns a tuple with each element requested in the row, as you only requested the prefix, it will contain just that (e.g: ("!",)) which is permitted as your command_prefix callable can return a string or tuple of strings.
Warning:
You may want to add a check to ensure that someone doesn't specify an empty string (A zero length string with nothing in it) as their prefix, otherwise your bot will attempt to run every message it sees as a command
References: discord.ext.commands.Bot.command_prefix
I've been searching for my problem here, but i can't find the exact answer to my problem.
I call a sympy function ( solve() ). This function can return a full list or an empty list.
I call this piece of code inside a while:
try:
sol = solve([eq1,eq2],[r,s])
rB = bin(abs(sol[0][0]))
sB = bin(abs(sol[0][1]))
stop = True
r = rB[2:len(rB)]
s = sB[2:len(sB)]
P = int("0b"+r+s,2)
Q = int("0b"+s+r,2)
print(P*Q == pubKey.n)
print("P = {}".format(P))
print("Q = {}".format(Q))
break
except ValueError:
pass
What i want is:
if the solve() returns an empty list, just pass. And if the solve() returns a full list, keep with the execution. The solve will be returning empty list until i find the right value.
This can be reached by checking sol[0][0], if there's a non-empty list this will work, but if the list is empty, this will throw an error (null pointer) i want try to flag it and pass.
What i'm having now is that when sol is empty, it tries to get sol[0][0], and ofc this throws an error that's not being catched by the try, and the whole code stops.
Anyone knows a solution for that? I'm not using try correctly?
Set sol in the beginning of each loop to some value and check it in the except clause
about else
try/except has an else which will be run the try block did not raise an Exception
and for has an else clause for when it was not broken out of!
for foo in iterable:
# set value so the name will be available
# can be set prior to the loop, but this clears it on each iteration
# which seems more desirable for your case
sol = None
try:
"logic here"
except Exception:
if isinstance(sol, list):
"case where sol is a list and not None"
# pass is implied
else: # did not raise an Exception
break
else: # did not break out of for loop
raise Exception("for loop was not broken out of!")
New to python and OOP. Hopefully I'm using the correct terms. I'm using a list to hold all of my objects. I want to reference this list to get the name of the object that I would like to get a property value for. I then want to pass this name to a function to get one or more properties. But I'm getting a string error (because the list is returning a string of the object name and not the actual object).
Here is the code:
class creature():
def __init__(self, name, legs):
self.name = name
self.legs = legs
rat = creature("rat",4)
mouse = creature("mouse",4)
beaver = creature("beaver",4)
squirrel = creature("squirrel",4)
chimpanzee = creature("chimpanzee",2)
gorilla = creature("gorilla",2)
orangutan = creature("orangutan",2)
spider_monkey = creature("spider_monkey",2)
black_widow = creature("black_widow",8)
recluse = creature("recluse",8)
wolf_spider = creature("wolf_spider",8)
daddy_long_leg = creature("daddy_long_leg",8)
def checkLegs(critter):
nbrLegs = critter.legs
return success
animals = [
['rat', 'mouse', 'beaver', 'squirrel'],
['chimpanzee','gorilla','orangutan','spider_monkey'],
['black_widow','recluse','wolf_spider','daddy_long_leg']
]
numberOfLegs = checkLegs(recluse)
print("The Recluse has: ")
print(numberOfLegs)
print(" legs")
Here is the response:
The test animal is: orangutan
Traceback (most recent call last):
File "/Python37/help.py", line 32, in <module>
numberOfLegs = checkLegs(testAnimal)
File "Python37/help.py", line 20, in checkLegs
nbrLegs = critter.legs
AttributeError: 'str' object has no attribute 'legs'
There's a couple things here that are preventing this from working. Look at your checkLegs function. It is returning something called success...however, that's not being used anywhere, and since you haven't wrapped it in ""s (I assume you were trying to return the word success to check if the function works) it is trying to return it as a variable, but of course it's undefined. You want the function to return the result of the code you use the function to execute. In this case you want to return nbrLegs. You also need to check the indentation of your constructor. You also don't need the array of animals since you're already defining them in your class. Other than that you were pretty close. Here's your code, with the fixes implemented:
class creature():
def __init__(self, name, legs):
self.name = name
self.legs = legs
rat = creature("rat",4)
mouse = creature("mouse",4)
beaver = creature("beaver",4)
squirrel = creature("squirrel",4)
chimpanzee = creature("chimpanzee",2)
gorilla = creature("gorilla",2)
orangutan = creature("orangutan",2)
spider_monkey = creature("spider_monkey",2)
black_widow = creature("black_widow",8)
recluse = creature("recluse",8)
wolf_spider = creature("wolf_spider",8)
daddy_long_leg = creature("daddy_long_leg",8)
def checkLegs(critter):
nbrLegs = critter.legs
return nbrLegs
numberOfLegs = checkLegs(recluse)
print("The Recluse has: " + str(numberOfLegs) + " legs")
I'm rewriting an old keyword-scanner from Python2 to Python3 and have problems to handle more than one return parameter in my final main()-function.
def scanner_pref():
dork = input('Dork: ')
number = input('Number of sites: ')
return dork, number
So, I need to return dork and number to the next function
def scanner(dork, number):
url = "http://www.google.de/search"
payload = {'q': dork, 'start':'0', 'num': int(number) *10}
[..]
so the scanner can proceed with the given parameters of payload.
But when I try to write the main()-function, it can't handle the scanner-function, because it suddendly requires the numbers parameter. see below
def main():
pref = scanner_pref()
scan = scanner(pref) <--
parser(h3tag=scan)
I don't really understand why scan = scanner(pref, ?) requires the number parameter when it receives the information from the scanner(pref) above and doesn't really care about the dork-parameter.
If I remove "number" from scanner_pref(), move it back to scanner(..) it works fine and no error or warning message appears.
def scanner_pref():
dork = input('Dork: ')
return dork
#
def scanner(dork, number):
url = "http://www.google.de/search"
number = ("Number of sites: ")
payload = {'q': dork, 'start':'0', 'num': int(number) *10}
#
def main():
pref = scanner_pref()
scan = scanner(pref)
parser(h3tag=scan)
works fine and without problems
scanner(dork, number) takes two arguments.
When you call pref = scanner_pref() the values dork and number are stored in perf as a tuple. When you pass pref to scanner you are still only passing one argument, a tuple with two values.
you have two easy options
pref_dork, pref_number = scanner_pref()
scan = scanner(pref_dork, pref_number)
or
pref = scanner_pref()
scan = scanner(pref[0],perf[1])
Howdo people,
I'm to put together a limited Q&A program that will allow the user to query Wikidata using SPARQL with very specific/limited query structures.
I've got the program going, but I'm running into issues when entering queries that are formulated differently.
def sparql_query(line):
m = re.search('What is the (.*) of (.*)?', line)
relation = m.group(1)
entity = m.group(2)
wdparams['search'] = entity
json = requests.get(wdapi, wdparams).json()
for result in json['search']:
entity_id = result['id']
wdparams['search'] = relation
wdparams['type'] = 'property'
json = requests.get(wdapi, wdparams).json()
for result in json['search']:
relation_id = result['id']
fire_sparql(entity_id, relation_id)
return fire_sparql
As you can see, this only works with queries following that specific structure, for example "What is the color of night?" Queries along the lines of 'What are the ingredients of pizza?' simply would cause the program to crash because it doesn't follow the 'correct' structure as set in the code. As such, I would like it to be able to differentiate between different types of query structures ("What is.." and "What are.." for example) and still collect the needed information (relation/property and entity).
This setup is required, insofar as I can determine, seeing as the property and entity need to be extracted from the query in order to get the proper results from Wikidata. This is unfortunately also what I'm running into problems with; I can't seem to use 'if' or 'while-or' statements without the code returning all sorts of issues.
So the question being: How can I make the code accept differently formulated queries whilst still retrieving the needed information from them?
Many thanks in advance.
The entirety of the code in case required:
#!/usr/bin/python3
import sys
import requests
import re
def main():
example_queries()
for line in sys.stdin:
line = line.rstrip()
answer = sparql_query(line)
print(answer)
def example_queries():
print("Example query?\n\n Ask your question.\n")
wdapi = 'https://www.wikidata.org/w/api.php'
wdparams = {'action': 'wbsearchentities', 'language': 'en', 'format': 'json'}
def sparql_query(line):
m = re.search('What is the (.*) of (.*)', line)
relation = m.group(1)
entity = m.group(2)
wdparams['search'] = entity
json = requests.get(wdapi, wdparams).json()
for result in json['search']:
entity_id = result['id']
wdparams['search'] = relation
wdparams['type'] = 'property'
json = requests.get(wdapi, wdparams).json()
for result in json['search']:
relation_id = result['id']
fire_sparql(entity_id, relation_id)
return fire_sparql
url = 'https://query.wikidata.org/sparql'
def fire_sparql(ent, rel):
query = 'SELECT * WHERE { wd:' + ent + ' wdt:' + rel + ' ?answer.}'
print(query)
data = requests.get(url, params={'query': query, 'format': 'json'}).json()
for item in data['results']['bindings']:
for key in item:
if item[key]['type'] == 'literal':
print('{} {}'.format(key, item[key]['value']))
else:
print('{} {}'.format(key, item[key]))
if __name__ == "__main__":
main()