Can I pass sqlite3 table column name as search parameter? - python

My first help request on Stack Overflow. Python version 3.6.4
I have an issue with my code. It is meant to to return a price quote based on parameters entered - such as country, shipment weight and in what zone is the city in given country.
The table looks like something this(excel picture).
Screenshot Image
Is it possible to narrow down which column to use. Such as if search parameters are estonia and 3 kgs it nicely returns all three columns of zone1, zone2 and zone3:
What country? :estonia
weight?: 70
('estonia', '75', '10,83', '12,25', '14,43')
But can I pass in an argument based on user input to narrow down which zone column to use to get the value?
For example if a city is in zone1, take only values from column zone1 based on other search parameters
My robust code is as follows:
import sqlite3
import pandas as pd
conn = sqlite3.connect("transportHinnakiri.db")
c = conn.cursor()
df = pd.read_csv("baltikum.csv")
df.to_sql("baltikum", conn, if_exists="append", index=False)
input_country = input("What country? :").lower()
input_weight = int(input("Weight?: "))
def weight_category(input_weight):
if input_weight < 1:
return 1
elif 1 < input_weight <= 3:
return 3
elif 3 < input_weight <= 10:
return 10
elif 10 < input_weight <= 20:
return 20
elif 20 < input_weight <= 31.5:
return 31.5
elif 31.5 < input_weight <= 50:
return 50
elif 50 < input_weight <= 75:
return 75
elif 75 < input_weight <= 100:
return 100
result = weight_category(input_weight)
def get_post():
c.execute("SELECT * FROM baltikum WHERE country=? AND weight=?",(input_country, result))
row = c.fetchone()
return row
result_final = get_post()
print(result_final)`

I'm not sure if this is what you are looking for but here is how I would do it. First get the city from the user:
city = input("input City: ").lower()
Then I would create some data structure, say dictionary, that holds all the zones and their cities:
zones = {'zone1': ['boston', 'new york'], 'zone2': ['san fransisco', 'los
angeles']}
Then you can have a function that takes in a city and returns a zone
def get_zone(city):
for zone in zones.keys():
if city in zones[zone]:
return zone
return "Error city not found"
Of course you would have to do something to normalize user input. Then you could create a command string and execute the command
def execute_command(zone, weight, country):
cmd = "SELECT {zone} FROM baltikum WHERE country={country} AND weight={weight}".format(zone = zone, country = country, weight = weight)
data = c.execute(cmd)
return data
Then you only get data from selected zone. Hope this helps!

Related

how to execute a class with some condition statements in python?

#Making a program "(subscribing for an entertainment)like Netflix" that would ask for users name then age.before they enter they should be on a legal age then if not print ("sorry you are not allowed to have a subscription").
If not. The code will continue then will ask for the users for their amount of money that they will pay and the higher the money the higher the discount price. Then will also asked how many months they will subscribe for the entertainment restricted (1,3,6,12 only) else the program will stop.
class Entertainment:
def __init__(self, subscription, price, term):
self.subscription = subscription
self.price = price
self.term = term
nameUser = input("Your name is,")
ageUser = int(input("Age:"))
if ageUser < 13:
return total_amount
subscription = float(input("Money Available: "))
if subscription <= 100:
price = subscription - 0.5
elif subscription in range(101 - 200):
price = subscription - 0.10
elif subscription in range(201 - 300):
price = subscription - 0.15
elif subscription >= 400:
price = subscription - 0.20
def MonthlySubs():
# Making this strictly 1,3,6,12 only and other numbers will not be accepted
use_months = float(input("(1,3,6,12) Only "))
if use_months == 1:
return price / 1
elif use_months == 3:
return price / 3
elif use_months == 6:
return price / 6
elif use_months == 12:
return price / 12
else:
print("Invalid Months of subscription")
break
#MAKING SOMETHING LIKE HOW PEOPLE SUBSCRIBE FOR PREMIUM BENEFITS
#problem is I don't understand how I will make these conditions connect to become a whole program
# Help me how I will have an output like this using classes:
>#Name: Mitchel
> #Age: 21
> #Money: 200
> #subscription months = 3
> #your payment amount is 209.5

Get sum of goals scored by each team

I am analyzing a football games dataset and I want to answer a question - how many goals each team has scored and lost.
My dataset:
date home_team away_team home_score away_score
1873-03-08 England Scotland 0 1
1873-03-09 Scotland England 1 0
... ... ... ... ...
The function takes in 2 parameters - start year and end year
I've tried to have an empty list at a start, while iterating through the whole set add the name of the country and append the goals they've scored but since there are many different teams my list is not correct.
def total_goals(start, end):
x = 0
goals_scored = 0
goals_scored_list = []
goals_lost = 0
goals_lost_list = []
complete_list = []
for item in range(len(data['home_team'])):
date = int(data['date'][x][:4])
if date >= start:
if date <= end:
if int(data['home_score'][x]) > int(data['away_score'][x]):
goals_scored_list.append(data['home_team'])
goals_scored_list.append(data['home_score'])
x += 1
else:
x += 1
return goals_scored_list
My desired output would be a list which would contain a list for each unique team, that list would have country name, goals scored and goals lost:
[['England',1,1],['Scotland',0,2],[...]]
I assume I would need to create a list for each unique country, maybe using something like
if country not in data['home_team']:
goals_scored_list.append(data['home_team'][x]
But I believe there is a more sophisticated way to achieve my goal.
I believe this should work:
class Team:
def __init__(self,name):
self.name = name
self.wins = 0
self.losses = 0
def addEl(self,pos,score):
try:
score = int(score)
except Exception as e:
print e
if pos:
self.wins += score
else:
self.loss += score
def total_goals(start,end):
d = {}
for i in range(len(data)):
date = int(data['date'][i])
if date >= start and date <= end: #make sure it's in the params
pos = int(data['home_score'][i]) > int(data['away_score'][i]) #true if home wins, false otherwise
if data['home_team'][i] in d: #check if home_team already exists
d[data['home_team']].addEl(pos,data['home_score'][i]) #add score to wins/losses
else:
d[data['home_team'][i]] = Team(data['home_score'][i])
d[data['home_team'][i]].addEl(pos,data['home_score'][i])
if data['away_team'][i] in d:
d[data['away_team']].addEl(not(pos),data['away_score'][i])
else:
d[data['away_team'][i]] = Team(data['away_score'][i])
d[data['away_team'][i]].addEl(not(pos),data['away_score'][i])
return d
Using a custom class has the advantage of letting you add more characteristics like how many games were won/lost, additional statistics etc.etc.

Input When Converted To An Integer Is Out Of Range

say I have this following code:
command = input("prompt :> ").strip().lower()
try:
command = command.split()
# My input will be something like AB 1 2
x = int(command[1])-1
y = int(command[2])-1
if command[0] == "ab":
A_to_B(heights[x],distances[y])
Where heights is a list of lists and so is distance:
heights = [['1','2'],['3','4'],['5','6']]
distances = [['a','b'],['c','d'],['e','f']]
So I input AC 1 2
x = 0
y = 1
Then I'll pluck the list at the 0 index from heights, and the list at the 1 index from distances. However I keep running into a IndexError:list out of range. How can I fix this? Thank you in advance!
For simplicity's sake I changed quite a bit of the names in the code above.
Here's what my actual A_to_B function looks like
def tableau_to_foundation(tab, fnd):
'''Determines if movements from the tableaus to the foundations are valid.'''
if len(tab) == 0:
raise RuntimeError("Your tableau is empty.")
src_card = tab[-1]
dest_card = None
valid_fnd_move(src_card, dest_card)
fnd.append(tab.pop())
And here's valid_fnd_move(src_card, dest_card)
def valid_fnd_move(src_card, dest_card):
'''Determines if the initial moves done to the foundation are valid. '''
#First Check for when foundation is empty
if dest_card == None and src_card.rank() == 1:
return
#Second Check for when foundation is empty
if dest_card == None and src_card.rank() != 1:
raise RuntimeError("You need to place an ace into the foundation first.")
#Checks if foundation is not empty
if not dest_card.suit() == src_card.suit() and \
src_card.rank == dest_card.rank() + 1:
raise RuntimeError("You can only place cards of the same suit together in a particular foundation")

Printing wrong if statement

I have this data in a CSV
34512340,0
12395675,2
56756777,1
My code below is checking what the stock level of each product is. The product is the eight digit number in the csv, and the number after the comma is the amount of available stock.
If the stock level is above 0, all works fine.
However, when the stock level gets to 0, instead out printing the out of stock message, the program prints the new order message. Can anybody work out why this is happening?
def checkstocklevel(code):
with open('stockcontrol.csv',newline='') as f:
for line in f:
if code in line:
data = line.split(",")
stocklevel = int(data[1])
if stocklevel <= 5:
print("New Order Required - Remaining Stock:",data[1],)
elif stocklevel <= 10:
print("Low Stock - Remaining Stock:",data[1],)
elif stocklevel < 1:
print("Sorry, this product is out of stock")
f = open("receipts","a")
f.write(code)
f.write(" Product Out Of Stock\n")
f.close()
else:
print("Normal Stock -",data[1],)
return stocklevel
Thanks
A value of 0 already matches your first condition stocklevel <= 5 so your later condition < 1 is never reached.
Reorder your conditions. Start with the most strict condition, then relax them.
if stocklevel < 1:
print("Sorry, this product is out of stock")
f = open("receipts","a")
f.write(code)
f.write(" Product Out Of Stock\n")
f.close()
elif stocklevel <= 5:
print("New Order Required - Remaining Stock:",data[1],)
elif stocklevel <= 10:
print("Low Stock - Remaining Stock:",data[1],)
else:
print("Normal Stock -",data[1],)

repetition of the compounds in the loop python

Good day friends!
Tell me please, I have the following code:
all_users = UserProfile.objects.all()
for s,usera in enumerate(all_users):
name = usera.nickname
name_id = usera.id
print(s)
if int(s) <= 50:
print('1_iterator')
r = api.request(example)
elif int(s) <= 100:
r = api2.request(example)
elif #a total of seven compounds, api3,api4,api5,api6,api7
try:
for item in r.get_iterator():
#then loop adds data to the database
how do I get a cycle every 50 iterations connect to the new api, and if he reaches seven then again from the beginning, and so has not yet come to an end user in the database?
Advance thanks!
You could set up an itertools.cycle.
apis = itertools.cycle([api1, api2, api3, api4, api5, api6, api7])
for s,usera in enumerate(all_users):
if (s % 50) == 0:
current_api = apis.next()
name = usera.nickname
name_id = usera.id
print(s)
current_api.request(example)
...

Categories

Resources