Basically I'm using Python to pull information off a google spreadsheet.
enter image description here
I have no problem pulling the information I need but when I start to break it down into specific catergories like "goals scored" i get the information but can print it to the terminal with the column headings. Example below:
enter image description here
So basically I want to bring down the above information but also with the column headings:
'player, position, appearances..... etc'
This is what my code looks like to get the information posted above:
data = {
"man united": SHEET.worksheet("man_utd").get_all_values(),
"man city": SHEET.worksheet("man_city").get_all_values(),
"chelsea": SHEET.worksheet('chelsea').get_all_values(),
"liverpool": SHEET.worksheet('liverpool').get_all_values()
}
team_name = ""
position = ""
top_stats = ""
def user_commands():
"""
gives commands the user is able to input to receive different data sets
"""
options = 'Man United, Man City, Liverpool, Chelsea'
print(f"1: {options}")
team_name = input("Please Enter A Team Name:\n").casefold()
print(f"You Have Entered {team_name}\n")
while team_name not in data:
print("You Entered a Wrong Option, Please Enter A Correct Option")
print(f"1: {options}")
team_name = input()
print(tabulate(data[team_name]))
return team_name
def user_commands_2(team_name):
"""
function to see players of a set position
from data received from first input.
Players can be goalkeepers, defenders, midfielders or forwards
"""
options_1 = 'goalkeeper, defender, midfielder,\nforward, home'
print(f"1: {options_1}")
position = input("\nPlease Enter a Position:\n").casefold()
print(f"You Have Entered {position}\n")
while position.casefold() not in (options_1):
print("\nYou Entered a Wrong Option, Please Enter a Correct Option")
print(f"1: {options_1}")
position = input()
if position.casefold() == 'home':
print("Hi! Welcome to a Football Stats Generator")
print("The Available Options Are As Follows:")
main()
res = [i for i in data[team_name] if position.capitalize() in i]
print(tabulate(res))
print("Hi! Welcome To a Football Stats Generator\n")
print("The Available Options Are As Follows:\n")
Any help would be greatly appreciated.
Thanks
Use "get_all_records()" instead of "get_all_values()".
Related
in case it isn't already obvious im new to python so if the answers could explain like im 5 years old that would be hugely appreirecated.
I'm basically trying to prove to myself that I can apply some of the basic that I have learnt into making a mini-contact book app. I don't want the data to save after the application has closed or anything like that. Just input your name, phone number and the city you live in. Once multiple names are inputted you can input a specific name to have their information printed back to you.
This is what I have so far:
Name = input("enter name here: ")
Number = input("enter phone number here: ")
City = input("enter city here: ")
User = list((Name, Number, City))
This, worked fine for the job of giving python the data. I made another input that made python print the information back to me just to make sure python was doing what I wanted it to:
print("Thank you! \nWould you like me to read your details back to you?")
bck = input("Y / N")
if bck == "Y":
print(User)
print("Thank you! Goodbye")
else:
print("Goodbye!")
The output of this, is the list that the user creates through the three inputs. Which is great! I'm happy that I have managed to make it function so far;
But I want the 'Name' input to be what names the 'User' list. This way, if I ask the user to input a name, that name will be used to find the list and print it.
How do I assign the input from Name to ALSO be what the currently named "User" list
You will need to create a variable which can store multiple contacts inside of it. Each contact will be a list (or a tuple. Here I have used a tuple, but it doesn't matter much either way).
For this you could use a list of lists, but a dictionary will be more suitable in this case.
What is a dictionary?
A dictionary is just like a list, except that you can give each of the elements a name. This name is called a "key", and it will most commonly be a string. This is perfect for this use case, as we want to be able to store the name of each contact.
Each value within the dictionary can be whatever you want - in this case, it will be storing a list/tuple containing information about a user.
To create a dictionary, you use curly brackets:
empty_dictionary = {}
dictionary_with_stuff_in_it = {
"key1": "value1",
"key2": "value2"
}
To get an item from a dictionary, you index it with square brackets, putting a key inside the square brackets:
print(dictionary_with_stuff_in_it["key1"]) # Prints "value1"
You can also set an item / add a new item to a dictionary like so:
empty_dictionary["a"] = 1
print(empty_dictionary["a"]) # Prints 1
How to use a dictionary here
At the start of the code, you should create an empty dictionary, then as input is received, you should add to the dictionary.
Here is the code I made, in which I have used a while loop to continue receiving input until the user wants to exit:
contacts = {}
msg = "Would you like to: \n - n: Enter a new contact \n - g: Get details for an existing contact \n - e: Exit \nPlease type n, g, or e: \n"
action = input(msg)
while action != "e":
if action == "n": # Enter a new contact
name = input("Enter name here: ")
number = input("Enter phone number here: ")
city = input("Enter city here: ")
contacts[name] = (number, city)
print("Contact saved! \n")
action = input(msg)
elif action == "g": # Get details for an existing contact
name = input("Enter name here: ")
try:
number, city = contacts[name] # Get that contact's information from the dictionary, and store it into the number and city variables
print("Number:", number)
print("City:", city)
print()
except KeyError: # If the contact does not exist, a KeyError will be raised
print("Could not find a contact with that name. \n")
action = input(msg)
else:
action = input("Oops, you did not enter a valid action. Please type n, g, or e: ")
#can be easier to use with a dictionary
#but its just basic
#main list storing all the contacts
Contact=[]
#takes length of contact list,'int' just change input from string to integer
contact_lenght=int(input('enter lenght for contact'))
print("enter contacts:-")
#using for loop to add contacts
for i in range(0,len(contact_lenght)):
#contact no.
print("contact",i+1)
Name=input('enter name:')
Number=input('enter number:')
City=input("enter city:")
#adding contact to contact list using .append(obj)
Contact.append((Name,Number,City))
#we can directly take input from user using input()
bck=input("Thank you! \nWould you like me to read your details back to you?[y/n]:")
#checking if user wants to read back
if bck=='y':
u=input("enter your name:")
#using for loop to read contacts
for i in range(0,len(Contact)):
#if user name is same as contact name then print contact details
if u==Contact[i][0]:
print("your number is",Contact[i][1])
print("your city is",Contact[i][2])
else:
#if user doesnt want to read back then print thank you
print("Good bye")
For this purpose you should use a dictionary.
The key of every entry should be the string 'User[0]' that corresponds to the person's name.
The contents of every entry should be the list with the information of that user.
I'll give you an example:
# first we need to create an empty dictionary
data = {}
# in your code when you want to store information into
# the dictionary you should do like this
user_name = User[0] # this is a string
data[user_name] = User # the list with the information
If you want to access the information of one person you should do like this:
# user_you_want string with user name you want the information
data[user_you_want]
Also you can remove information with this command:
del data[user_you_want_to_delete]
You can get more information on dictionaries here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
You should start by defining a class to support name, phone and city. Once you've done that, everything else is easy.
class Data:
def __init__(self, name, city, phone):
self.name = name
self.city = city
self.phone = phone
def __eq__(self, other):
if isinstance(other, str):
return self.name == other
if isinstance(name, type(self)):
return self.name == other.name and self.city == other.city and self.phone == other.phone
return False
def __str__(self):
return f'Name={self.name}, City={self.city}, Phone={self.phone}'
DataList = []
while (name := input('Name (return to finish): ')):
city = input('City: ')
phone = input('Phone: ')
DataList.append(Data(name, city, phone))
while (name := input('Enter name to search (return to finish): ')):
try:
print(DataList[DataList.index(name)])
except ValueError:
print('Not found')
i have a program that asks users which department they want to choose from, i made the question into a while loop that would keep asking the same question until they put a valid response in. and whenever they wanted to break the loop they would type the word "exit". once they type in a valid response it would add ask another question in another function that would ask for the class your want info on based on the department you're in, it would then lead it to a website where i can get the information i need. the issue im facing is that it doesn't take the valid response that was typed in, it would instead implement the word "exit" which was used to break out of the loop as it was the last input. i want it to take the input before that and not "EXIT"
here is the code
def get_departments():
umd_departments = requests.get("https://api.umd.io/v0/courses/departments")
umd_departments_list = umd_departments.json()
umd_departments_list2 = json.dumps(umd_departments_list, indent=1)
department_storage = [department['dept_id'] for department in umd_departments_list]#comprehensive for loop to put the department ID into a list
print(department_storage)
while True:
dept = input('what department are you in right now: ')
dept = dept.upper()
if dept == 'EXIT':
break
if dept not in department_storage:
print("not approriate response")
else:
try:
department_url = requests.get(f"https://api.umd.io/v0/courses?dept_id={dept}")
specific_major =department_url.json()
keep_keys = ["course_id"]
courses = [{k: json_dict[k] for k in keep_keys}
for json_dict in specific_major]
print(courses)
except Exception as e:
print(e)
return courses,dept
def get_classes(courses):
classes = [course['course_id'] for course in courses]
print(classes)
course_select = input('what class would you like to select').upper()
if course_select not in classes:
raise ValueError(" class does not exist")
else:
driver = webdriver.Chrome(ChromeDriverManager().install())
url = f"https://app.testudo.umd.edu/soc/202008/{dept}"
driver.get(url)
section_container = driver.find_element_by_id(f"{course_select}")
section_container.find_element_by_xpath(".//a[#class='toggle-sections-link']").click()# it would click on the show section button on the site that would reveal the sections
sleep(1)
section_info = section_container.find_element_by_xpath(".//div[#class='sections sixteen colgrid']").text
return section_info
let's say for example in the get departments function i type in INST and its considered a valid response, it would then ask for which class i want to choose from that department. it would then create a url that would get me the info i need like this:
https://app.testudo.umd.edu/soc/202008/INST
however i get this:
https://app.testudo.umd.edu/soc/202008/EXIT
the latter doesn't produce anything as it doesn't exist and it causes errors. is there a way to make it so that it doesn't make the "EXIT" input stored into a valuable and instead takes the valid response before it? greatly appreciated if anyone could help.
Looks like you just need another variable
userInput = input('what department are you in right now: ')
userInput = userInput.upper()
if userInput == 'EXIT':
break
else:
dept = userInput
so I am using Spyder IDE for python. it stopped executing my codes, I have tried to run only a few lines and all together but still no response.
Anyone familiar with these sort of issues?
#Assinging Variables
ProductName = "iPhone"
ProductPrice = 450
Tax = 0.5 #Tax is a constant that cannot be changed
print(ProductTax)
#Dealing with Inputs
name = input("Your Name")
print(name)
print("Hello", name)
city = input("Where do you live?")
print(name, "lives in", city)
#CASTING - converting one data type to another as examples below.
##Note that all the answers required below will be in form of strings
ProductName = input("what is the product Name?")
ProductPrice = float(input("how much is it cost?")) #the string is converted to float
ProductQuantity = int(input("How many?")) #the string is converted to an integer
TotalPrice = ProductQuantity*ProductPrice
print("Total Price: ", TotalPrice)
##SELECTION
## selection is used to choose between 2 or more otions in programming
## if statements is a type of 'selection'
#weather = input("is it raining")
#if weather == "raining":
#print ("Grab an Umbrella")
#else:print("Wear a coat")
it works for me when create a new Console. Hope that works for you.
enter image description here
I am doing the following dictionary:
import random
from tkinter.messagebox import YES
name = input("Hello, what is your name? ")
print("nice to meet you {}!".format(name))
instruments = (["Bass","Guitar","Piano"])
instruments1 = ({"Name":"Bass","Price":"US$ 900,00"},
{"Name":"Piano","Price":"US$ 1000,00"},
{"Name":"Guitar","Price":"US$ 900,00"})
print("{} we have these instruments for you to buy:".format(name),", ".join(instruments))
#the line above give m all items without the brackets
answer = input("You're going to take some of them? Yes or no.")#waiting the user input
if answer == YES:#boolean command for confirming the yes/no answer.
print("{} which one will be?".format(name))
pos_awnser = input()
print(pos_awnser,"It's a very good choice.")
elif awnser != YES:
print("Sorry, we don't have what you need.")
print(pos_awnser,"costs",)
and I want to display the type of instrument that was chosen previously and display the name and price at the console
Instead of doing it like that, create a single dictionary instead, like this
instruments = ({"Bass":'US$ 900,00',"Guitar":"US$ 1000,00","Piano":"US$ 900,00" })
You can then print the instruments using,
print("{} we have these instruments for you to buy:".format(name),", ".join(instruments.keys())
and display the type of instrument through
print(pos_awnser, instruments[pos_answer], " is a very good choice.")
I want to make this program that acts as a bank, how do I make sure the correct ID number must be entered with the correct pin and have it depending on the id you entered print hello then their name and prompt how much money they have in the bank.
attempts = 0
store_id = [1057, 2736, 4659, 5691, 1234, 4321]
store_name = ["Jeremy Clarkson", "Suzanne Perry", "Vicki Butler-Henderson", "Jason Plato"]
store_balance = [172.16, 15.62, 23.91, 62.17, 131.90, 231.58]
store_pin = [1057, 2736, 4659, 5691]
start = int(input("Are you a member of the Northern Frock Bank?\n1. Yes\n2. No\n"))
if start == 1:
idguess = ""
pinguess = ""
while (idguess not in store_id) or (pinguess not in store_pin):
idguess = int(input("ID Number: "))
pinguess = int(input("PIN Number: "))
if (idguess not in store_id) or (pinguess not in store_pin):
print("Invalid Login")
attempts = attempts + 1
if attempts == 3:
print("This ATM has been blocked for too many failed attempts.")
break
elif start == 2:
name = str(input("What is your full name?: "))
pin = str(input("Please choose a 4 digit pin number for your bank account: "))
digits = len(pin)
balance = 100
while digits != 4:
print("That Pin is Invalid")
pin = str(input("Please choose a 4 digit pin number for your bank account: "))
digits = len(pin)
store_name.append(name)
store_pin.append(pin)
I'm very impressed by how much you've elaborated on your program. Here's how I would view your solution.
So to create a login simulation, I would instead use a dictionary. That way you can assign an ID to a PIN. For example:
credentials = {
"403703": "121",
"3900": "333",
"39022": "900"
}
Where your ID is on the left side of the colon and the PIN is on the right. You would also have to assign the ID to a name that belongs to that ID using, you guessed it, a dictionary!
bankIDs = {
"403703": "Anna",
"3900": "Jacob",
"39022": "Kendrick"
}
Now that you've done that, you can create your virtual login system using if/else control flow. I've made my code like this:
attempts = 0
try:
while attempts < 3:
id_num = raw_input("Enter your ID: ")
PIN = raw_input("Password: ")
if (id_num in credentials) and (PIN == credentials[id_num]):
print "login success."
login(id_num)
else:
print "Login fail. try again."
attempts += 1
if attempts == 3:
print "You have reached the maximum amount of tries."
except KeyboardInterrupt:
print "Now closing. Goodbye!"
Note the try and except block is really optional. You could use the break operator like you did in your code if you wanted to, instead. I just like to put a little customization in there (Remember to break out of your program is CTRL-C).
Finally, Python has a way of making life easier for people by using functions. Notice I used one where I put login(id_num). Above this while loop you'll want to define your login so that you can display a greeting message for that particular person. Here's what I did:
def login(loginid):
print "Hello, %s!" % bankIDs[loginid]
Simple use of string formatting. And there you have it. The same can be done with displaying that person's balance. Just make the dictionary for it, then print the code in your login definition.
The rest of the code is good as it is. Just make sure you've indented properly your while-loop inside the elif on the bottom of your code, and your last 2 lines as well.
Hope I helped. Cheers!