I suppose to create a function that allows user pick a range and it will print out the number within the range. however, I keep getting empty DataFrame with my code. can anyone help me?
` import pandas as pd
if __name__ == "__main__":
file_name = "sales_rossetti.xlsx"
# Formatting numbers (e.g. $1,000,000)
pd.options.display.float_format = '${:,.0f}'.format
# Reading Excel file
df = pd.read_excel(file_name, index_col = 0, convert_float = False)
print ("Welcome to Rossetti's Sales program\n")
print ("1) Search by State")
print ("2) Search by Jan Sales")
print ("3) Search by Q2 sales")
print ("4) Exit")
my_option = input ("Please select a menu option:")
if (my_option=="2"):
my_columns = ["Name", "City", "State", "Jan"]
your_sales = input("please enter the minimum sale: ")
your_sales = input("please enter the maxium sale: ")
print (df[my_columns][df.Jan>int(your_sales)][df.Jan<int(your_sales)])`
You're overwriting the your_sales variable as you're reusing it, so you should use a different variable name for the min and max params. You then need to generate a proper boolean mask using loc and enclosing your boolean conditions using parentheses and & to and the array of boolean values:
if (my_option=="2"):
my_columns = ["Name", "City", "State", "Jan"]
min_sales = input("please enter the minimum sale: ")
max_sales = input("please enter the maxium sale: ")
print (df.loc[(df.Jan > int(min_sales) ) & (df.Jan < int(max_sales)), my_columns])
the above should work
Related
I'm making a program in which you can store your data and it will have a unique code from which you can load that back. So I've made way to make a unique code by just putting the date and then putting the entry number. For example: The date is 24 April 2021 and it is the first entry of the day then it'll generate the code as 202104241. The "1" at the end means entry number 1. So i want that to change every time you make a new entry in that day. I tried it doing like this but it gives an error. Is there any to do it?
def New_Document():
LUD = 1 # LAST UNIQUE DIGIT
unique = []
date = datetime.date.today()
unique.append(date)
unique_id = str(unique[0])
unique_id = unique_id.replace('-', '')
unique_id = unique_id + str(LUD)
folder = r'E:\\Programming related\\DATASAVER'
destination = r'E:\\Programming related\\DATASAVER\\DATA'
filenames = os.listdir(destination)
print(filenames)
for file in filenames:
if filenames[file] in unique_id:
LUD += 1
unique_id = unique_id + str(LUD)
break
else:
continue
print(f"Your unique id is: {unique_id}")
pickle.dump(unique_id, open(unique_id, 'wb'))
shutil.move(folder, destination)
print("Please choose a NUMBER:")
print("1: New Document")
print("2: Existing Document")
while True:
try:
ask = int(input("Please enter a NUMBER: "))
if ask == 1:
break
elif ask == 2:
break
else:
print("Please enter '1' OR '2'")
continue
except:
print("Please '1' OR '2' NOT a WORD")
if ask == 1:
New_Document()
else:
pass
I was just wondering if there was a way so that
def main():
SIZE = 7
people = ["bob", "john", "amy", "jose", "kai", "joe", "leia"]
#phoneNumbers = ['1231111111', '1232222222', '1233333333', '1234444444', '1235555555', '1236666666', '1237777777']
# name validation
index = 0
nameInput = input("Enter a person's name: ")
while (nameInput.lower() != people[index]):
if (nameInput.lower() == people[index]):
input("Error: Please enter a name: ")
else:
index = index + 1
# find the name
found = False
index = 0
while (found == False and index <= SIZE - 1):
if (people[index] == nameInput.lower()):
found = True
else:
index = index + 1
if found:
print("The person's name and phone number is:", people[index], index + 1)
else:
print('No user found at ', index + 1)
main()
would print an error and ask for reinput upon the error and have this iterate
input("Error: Please enter a name: ")
Or I guess my main goal would be so that it'll cycle through the list of names and make sure the name validation goes through
Things I've tried:
Setting the conditions and trying to find which condition would allow that
Deleting the if portion nested in the while statement, but gets rid of the resulting code that shows which place the names are, and only allows "bob" to work
Pardon for the messy code, writing this atm
people = ["bob", "john", "amy", "jose", "kai", "joe", "leia"]
phoneNumbers = ['1231111111', '1232222222', '1233333333', '1234444444', '1235555555', '1236666666', '1237777777']
index = None
while index is None:
nameInput = input("Enter a person's name: ")
if nameInput in people:
index = phoneNumbers.index(nameInput)
print("The person's name and phone number is:", people[index], phoneNumbers[index], index + 1)
else:
print('No user found')
I don't know exactly what you are trying to do and more information would be great, but it sounds like a dictionary would be the perfect data structure, because it is easier to implement and fast to parse. For example if you had three people, say "Emily", "Bob" and "John", then you could assign their names to their phone numbers.
# Parallel lists, each index of one list corresponds to the same index of the other list
people = ["bob", "emily", "john"]
phones = ["123", "124", "125"]
people_dict = {}
for i in range(len(people)):
people_dict[people[i]] = phones[i]
print(people_dict) # prints "{'bob': '123', 'emily': '124', 'john': '125'}"
while True:
in_name = input("Person's name: ")
try:
print(f"{in_name}'s phone number is: {people_dict[in_name]}")
break
except KeyError:
print("The name you provided was not in the list\nPlease retry.\n")
This should work then. Easy enough and faster than looping in a list. The for loop I used was just to create the dictionary. Also to create the dictionary this way, there have to be the same number of people and phone numbers, or the program will exit with an IndexError inside the for loop.
If you had to use lists, you could still try to find the index of a name and if it is not found, retry.
# Parallel lists, each index of one list corresponds to the same index of the other list
people = ["bob", "emily", "john"]
phones = ["123", "124", "125"]
while True:
in_name = input("Person's name: ")
try:
print(f"{in_name}'s phone number is {phones[people.index(in_name)]}")
break
except ValueError:
print("The name you provided was not in the list\nPlease retry.\n")
def main():
SIZE = 7
people = ["bob", "john", "amy", "jose", "kai", "joe", "leia"]
phoneNumbers = ['121', '122', '123', '124', '125', '126', '127']
nameInput = input("Enter a person's name: ")
# find the name and phone number
found = False
index = 0
while (found == False and index <= SIZE - 1):
if (people[index] == nameInput.lower()):
found = True
else:
index = index + 1
if found:
print("The person's name and phone number is:", people[index], phoneNumbers[index])
else:
print('No user found')
# call main to run
main()
well i guess i got it to work
Thanks for those who pitched in an answer
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 attempting to create a coronavirus temp scan compare program. I want to open an excel file and create a small database each day of scanned employees. When I execute I am just getting the first input prompt and my excel spreadsheet is not opening. My goal was to have each line of code under the while statement nested and would continue to loop until the program operator ended the loop. My code is below. Any help is appreciated.
from datetime import date
from xlwt import Workbook
# Workbook is created
wb = Workbook()
# add sheet
sheet1 = wb.add_sheet('Temperature Scans')
sheet1.write(0, 0, 'First Name')
sheet1.write(0, 1, 'Last Name')
sheet1.write(0, 2, 'Date')
sheet1.write(0, 3, 'Temperature')
Normal = 98.6
Recording = input("Are you Recording Temperature Today? 1 if yes; 0 if no: ")
while Recording == 1:
Employee_First = input("Enter First Name: ")
Employee_Last = input("Enter Last Name: ")
Temp = float(input("Input Scanned Temperature (Example if 99 degrees enter 99): "))
if Temp > Normal:
print("Elevated Temperature Detected! Entrance Not Permitted")
else:
print("Temperature Within Acceptable Limits. Entrance Permitted")
Date = today.strftime("%m/%d/%y")
for i in range(0, 15000):
sheet1.write(i+1, 0, Employee_First)
sheet1.write(i+1, 1, Employee_Last)
sheet1.write(i+1, 2, Date)
sheet1.write(i+1, 3, Temp)
Day = today.strftime("%d")
Month = today.strftime("%m")
Year = today.strftime("%y")
wb.save(Month, _ , Day, _ , Year, 'Temp Scans.xlsx')
break
continue
The input statement will only take input as a string, it is up to you to convert it into different formats:
Recording = input("Are you Recording Temperature Today? 1 if yes; 0 if no: ")
while Recording == '1':
# do something
Change this of your code:
Recording = input("Are you Recording Temperature Today? 1 if yes; 0 if no: ")
To:
try:
Recording = int(input("Are you Recording Temperature Today? 1 if yes; 0 if no: "))
except:
print("Please enter a valid number (either 1 or 0)")
in order to make sure that you enter the while loop:
...
while Recording == 1:
Employee_First = input("Enter First Name: ")
...
Since the input() will always return a string variable and you are making the comparison on the while loop with an integer.
EDIT
Here is a mofification of the code you provided using the openpyxl library. The code below will interactively ask for the employee's first name, last name and temperature and finally overwrite the temperaturescans.xlsx file (or create it if it doesn't exist and you run the python script for the first time).
from openpyxl import Workbook
from datetime import datetime
#Create workbook
wb = Workbook()
# grab the active worksheet
ws = wb.active
# Fill up the headers on the first row
ws['A1'] = 'First Name'
ws['B1'] = 'Last Name'
ws['C1'] = 'Date'
ws['D1'] = 'Temperature'
#Define some constant values
normal_temperature = 98.6
date = datetime.today().strftime('%m/%d/%y')
try:
recording = int(input("Are you Recording Temperature Today? 1 if yes; 0 if no: "))
except:
print('Please enter a number: either 1 or 0')
while recording == 1:
#Get employees First Name
employee_first = input('Enter First Name:')
#Get employees Last Name
employee_last = input('Enter Last Name:')
#Get temperature
try:
temperature = float(input('Input Scanned Temperature (example if 99 degrees enter 99):'))
except:
print('Please enter a valid value for the temperature (99.2, 98.6)')
#Check if the employee has a fever
if temperature > normal_temperature:
print('Elevated Temperature Detected! Entrance Not Permitted')
else:
print("Temperature Within Acceptable Limits. Entrance Permitted")
#Add the employees row to the sheet
ws.append([employee_first,employee_last,date,temperature])
try:
recording = int(input("Are you Recording Temperature Today? 1 if yes; 0 if no: "))
except:
print('All recordings have been made. Saving the file.')
#Save the file
print('Check the temperaturescans.xlsx file for the results.')
wb.save("temperaturescans.xlsx")
Here is the problem statement:
There is a record of 'n' students, each record having name of student, percent marks obtained in Maths, Physics and Chemistry. The user enters an integer 'n' followed by names and marks for the 'n' students. I am required to save the record in a dictionary data type. The user then enters name of a student and you are required to print the average percentage marks obtained by that student, correct to two decimal places.
what I have tried so far:
num_students = int(raw_input("Please enter number of students:"))
print "you entered %s students" %num_students
student_info = {}
student_data = ['studentname', 'mathmarks', 'physicsmarks', 'chemistrymarks']
for i in range(0,num_students):
for entry in student_data:
student_info[entry] = raw_input(entry )
print student_info
print"please enter student name"
name = raw_input("student name")
if student_info['studentname'] == name:
print "Average student marks:", (int(student_info['mathmarks']) + int(student_info['physicsmarks']) + int(student_info['chemistrymarks']))/3
else:
print"please enter valid name"
This code is working is num_students = 1, However if num_students >1 the code fails.
I am unable to save the entry of each student in dictionary.
I am pretty new to python, would be glad if any one can help me with this.
Actually you need to create a nested dictionary with name as values and another dict as keys, in pretty way the nested dict may look like:
{
'anmol': {'chemistrymarks': 3, 'physicsmarks': 2, 'mathmarks': 1},
'uppal': {'chemistrymarks': 6, 'physicsmarks': 5, 'mathmarks': 4}
}
So you need to add the following lines to create a nested dictionary.
num_students = int(raw_input("Please enter number of students:"))
print "you entered %s students" %num_students
student_info = {}
student_data = ['Math marks : ', 'Physics marks : ', 'Chemistry marks : ']
for i in range(0,num_students):
student_name = raw_input("Name :")
student_info[student_name] = {}
for entry in student_data:
student_info[student_name][entry] = int(raw_input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.
#print student_info
print"Please enter student name ?"
name = raw_input("Student name : ")
if name in student_info.keys():
print "Average student marks : ", str(sum(student_info[name].values())/3.0)
else:
print"please enter valid name"
#youcan use print stmts. acording to your problem
n = raw_input()
grades = []
for entry in range(int(n)):
grades.append([i for i in raw_input().split()])
query = raw_input()
# Find list where first item matches name in query and
# assign grades to queryResult
queryResult = [x[1:] for x in grades if x[0] == query]
total = 0
scores = 0
for x in queryResult:
for y in x:
total += float(y)
scores += 1
print "%.2f" % (float(total/scores))
#Another way
num_of_student = int(raw_input())
dir_student = {}
for i in range(0,num_of_student):
student_info = raw_input()
name = student_info.split()
dir_student[name[0]] = [float(name[1]),float(name[2]),float(name[3])]
find_name = raw_input()
if dir_student.has_key(find_name):
print "{0:.2f}".format(sum(dir_student[find_name])/3.0)