I have this program:
def NoOfPeople(people):
if people.isdigit() and (int(people)>=1) and (int(people)<=1000):
return True
else:
print('invalid')
while True:
people = input('No. of people:')
if NoOfPeople(people):
break
How do I use data from it to a new defined function as I have this menu and program which I am stuck at right now on how to continue to get the data from the previous one.It is to check if the selected room can accommodate to the number of people that are entered in NoOfPeople(people). So how can I compare the number of people with which room it can accommodate:
Room
[1] Room A (10 person)
[2] Room B (30 person)
[3] Room C (50 person)
venue = input('Please select a venue:')
def validateVenue(venue):
if venueList == '1':
(what should I continue from here?)
Help and suggestion please as I am new in using python.Thanks
This is pretty open ended but I will try and help you out.
in general you can pass a variable / data_structure to another function and return it out of the function back to whatever called the function like this...
def function_name(var1, var2):
var3 = var1*var2
return var3
new_var = function_name(3, 5)
print(new_var)
output
15
1) I don't know what venuList looks like you might want to make a Key value pair (dictionary)
def select_venue(num_of_people):
#this is your venue key value dictionary, IE your available venues and their size
venues = {10:"Venue Small Conf Room" , 30:"Venue Ballroom", 50:"Venue Large Conf Room", 3:"Venue Office"}
venue_options = []
for occupancy in venues:
if occupancy >= num_of_people:
venue_options.append(occupancy)
venue = min(venue_options)
venue_name = venues[venue]
print("Please Use {} for your event with {} people (max occupancy {})".format(venue_name,num_of_people, venue))
if __name__ == "__main__":
people = 4 #change this value to test
select_venue(people)
your output should look like this
Please Use Venue Small Conf Room for your event with 4 people (max
occupancy 10)
You will notice the key is the max occupancy of a venue and the value is the name of the venue.
You should also take note they don't have to be in order (small office is last)
Related
I am a newbie to Python, and trying to create an input form using a nested dictionary with the following flow, but really struggling to cope with how to code having multiple values (as a list) that can be associated per topic within the dictionary:
Steps
Ask the user to input a topic / issue which is stored in an empty dictionary
Immediately after entering a topic / problem, prompt user to enter an action to resolve the problem, associate it with a due date entered by the user to complete by, and then linked to the topic / issue (key) created in step 1 as value to that key
Prompt user to add another action to the same topic if required with y/n or move to add another topic
add another topic / issue if required
print the dictionary with the topic / issues (keys) and associated values or multiple values with due dates.
Note I have not added due dates, and code to loop through the completed dictionary to list problems / actions with the due dates to amend, delete or change.
Any help really appreciated!! :)
here is a sample of my incomplete code:
problems = {}
problems_open = True
actions_open = True
while problems_open:
issue = input("\nPlease enter a topic / problem? ")
while actions_open:
action = input("What action are you going to take for this topic? ")
problems[issue] = action
repeat = input("Would you like to add another action y/n?")
if repeat == 'n':
actions_open = False
""" This is not appending multiple actions to the dictionary problems, just the
last entry """
""" Not sure how to add a due date to each action """
repeat = input("Would you like to add another topic / problem? ")
if repeat == "n":
problems_open = False
print("\n--- List of problems and actions with dates ---")
for issue, action in problems.items():
print("The problem: " + issue + " has " + "the following actions: " + action)
The problem in your code were the nested lists. The problem with nested lists is, that you can't iterate through them with numbers. That means to identify the specific value in the list would be very difficult.
The solution is to use lists (the ones with the square brackets).
I made a working code for your problem:
problems = []
actions = []
problems_open = True
actions_open = True
offset = -1
while problems_open:
issue = input("\nPlease enter a topic / problem? ")
problems.append(issue)
while actions_open == True:
action = input("What action are you going to take for this topic? ")
actions.append(action)
actions_open = False
repeat = input("Would you like to add another topic / problem? y/n ")
if repeat == "n":
problems_open = False
elif repeat == "y":
problems_open = True
actions_open = True
print("\n--- List of problems and actions with dates ---")
for problems, actions in zip(problems, actions):
print("The problem: " + problems + " has " + "the following actions: " + actions)
The only difference in this code is that you are not asked multiple times for taking another action on one problem again. I just made a working list for you. I hope it helped.
I am writing a code for a time table maker. This code takes the subjects that you want to study and the preference of studying(morning,afternoon,evening). Then I take total hours to be studied(20 hours) in a week. Then I divide it by 7 to calculate the study per day. Then I want to assign a random subject to my random time slot.
# Time Table Creator
import random
def TimeTableCreator(subjects,day,time_slots,total_hours):
day = {}
studyperday = total_hours/7
studyperday = round(studyperday)
subjects_study = random.sample(subjects,k=studyperday) # subjects that are selected randomly
final_time_slots = random.sample(time_slots,k=studyperday) # list of my time slots
#trying to add both these items using for loop in a dictionary
for subject in subjects_study:
for i in range(studyperday):
day[subject] = final_time_slots[i]
print(day)
subjects = []
while True:
subject = input("Enter a subject:\n")
if subject=="":
break
subjects.append(subject)
total_hours = 20
print("What is your preference of studying: Morning or afternoon or evening:")
time_preference = input()
if time_preference.lower()=="morning":
time_slots = ["7:00-8:00","8:00-9:00","9:00-10:00","10:00-11:00","2:00-3:00"]
elif time_preference.lower()=="afternoon":
time_slots = ["12:00-13:00","13:00-14:00","15:00-16:00","16:00-17:00","18:00-19:00"]
elif time_preference.lower()=="evening":
time_slots = ["16:00-17:00","18:00-19:00","19:00-20:00","20:00-21:00","21:00-22:00"]
else:
print("Invalid preference")
TimeTableCreator(subjects,"Monday",time_slots,total_hours)
Program output
Enter a subject:
phy
Enter a subject:
chem
Enter a subject:
bio
Enter a subject:
What is your preference of studying: Morning or afternoon or evening:
morning
**{'chem': '2:00-3:00', 'phy': '2:00-3:00', 'bio': '2:00-3:00'}**
Process finished with exit code 0
As you can see the time slot is the same that is assigned to different subjects. But I want that time slots should be different for each subject.I want that the time slots should be different for each subject. It is showing 2:00 to 3:00 for each subject. But I want different slots to be assigned for different subjects
Please help.
The problem in your code is dictionary creation. You don't need the nested loop. You can use zip()
Just change this to
for subject in subjects_study:
for i in range(studyperday):
day[subject] = final_time_slots[i]
this
for x, y in zip(subjects_study, final_time_slots):
day[x] = y
One liner solution:
day = dict(zip(subjects_study, final_time_slots))
# Time Table Creator
import random
def TimeTableCreator(subjects,day,time_slots,total_hours):
day = {}
studyperday = round(total_hours/7)
subjects_study = random.sample(subjects,k=studyperday) # subjects that are selected randomly
final_time_slots = random.sample(time_slots,k=studyperday) # list of my time slots
#trying to add both these items using for loop in a dictionary
i = 0
for subject in subjects_study:
day[subject] = final_time_slots[i]
i += 1
print(day)
You were using a nested for loop, that assigned each value of subject from each final_total_hours and therefore it ended up at the same random value (the last one).
This only needed a single for loop as above.
You are looping using nested loops so are going through all the i values for each subject and ending up with the value for the last value of i for all the subjects:
for subject in subjects_study:
for i in range(studyperday):
day[subject] = final_time_slots[i]
what you are wanting is to loop together using enumerate:
for i, subject in enumerate(subjects_study):
day[subject] = final_time_slots[i]
I'm very new to Python and programming in general, so excuse me if the code is terrible and the problem rather easy to solve.
I have written code to allow a user to have employee data printed based on 3 different inputs, which they are allowed to choose from.
The options the user has available to them are to pick employees based on their payroll number; a minimum and maximum salary range; their job title.
I made two functions for the formatting. The first one turns the lines of the text file into lists, then the second function grabs those individual lists and formats them.
Then the code requests the user to input the file name. If the file cannot be found, they get to try again. If it is correct, the file is loaded and then runs through the functions to print out a neat table.
Then the user is asked what method they want to choose from to select specific employees. They are given 4 options, 3 are mentioned at the start and the fourth is to just end the program.
I managed to successfully get the first option to print out the employees without hassle, as is the same for the fourth option to end the program. I almost have the third one completed, I just need to find a way to print the name without a comma. My problem resides within the second option: how do I print the employees and their details if they fall between the minimum and maximum salary ranges entered by the user if the range isn't an integer since it has to include a '£' sign?
Here's the code. It's the biggest chunk in the program because I just have no clue how to make it work properly -
def detailsPrint(field) : #takes tuple and prints
print("{:30}" "{:6}" "{:15}" "{:7}".format(field[3] + ", " + field[4], field[0], field[2], "£" + field[1]))
if display == 2 :
maxSalary = "£1000000"
minpay = input("Enter the minimum pay : ")
maxpay = input("Enter the maximum pay : ")
if len(minpay) and len(maxpay) < maxSalary :
for s in employeeList :
if s[1] >= minpay :
detailsPrint(s)
The outcome should be something like (example) Simpson, Bart 12345 Consultant £55000 if the minpay were to be £50000 and maxpay £60000
edit: Managed to get it working. Here's the code
if display == 2 :
x = False
maxSalary = 1000000
minpay = int(input("Enter the minimum pay: "))
maxpay = int(input("Enter the maximum pay: "))
if int(minpay) > int(maxSalary) or int(maxpay) > int(maxSalary) :
x = False
print("No employees earn over £1000000. Try again.")
if int(minpay) or int(maxpay) < int(maxSalary) :
for s in employeeList :
if int(s[1]) >= minpay and int(s[1]) <= maxpay :
detailsPrint(s)
x = True
if x == False :
print("No employees could be found within that range. Try again")
print("\n")
Simplest solution: don't ask for the £ char ;-)
A solution that work with your requirement is to change the line
if len(minpay) or len(maxpay) > maxSalary :
with something like
if int(minpay[1:]) > int(maxSalary[1:]) or int(maxpay[1:]) > int(maxSalary[1:]) :
which check the numeric value of the strings (your condition seems wrong anyway to me)
You could replace all "£" signs to "" in a string.
YourString.replace("£", "")
Im new to python and Im creating this gambling game where a user will have the choice to bet on symbols that will be generated (eventually- haven't gotten there yet). Im creating a dictionary to hold my data for how much the user is betting (the value) and the number corresponding to the symbol they are betting on (the key). Each player has the option to place more than 1 bet per turn. I am running into a problem where if two different players input the same bet&symbol combination (for example $10 on 1 (Crown)) then the dictionary wont update to contain 2 separate entries of 1:10, it will only have one entry of 1:10. This is what Im working with right now
def getPlayers():
print("Hello and Welcome to the Crown and Anchor Game")
num = int(input('Please enter the number of people playing today: ')) # takes the number of people who are playing from the user
scoreInit = [] # creating an empty list for the players inital score of 10
for i in range(num): # for loop to append the inital score of 10 to the empty list scoerInit for the amount of players input
scoreInit += i * [10]
return scoreInit # returns the list of inital scores for the amount of players playing
def collectBets(balance):
bets = {}
index = 0
for i in balance:
index += 1
print('Player %d, what would you like to do this round?' % (index))
print('1: Bet on a symbol')
print('2: Skip this round')
userOpt = int(input('Please enter 1 or 2 depending on your choice: ')) # assigning what the user inputs as the variable 'usesrOpt'
if userOpt == 1: # if user decides to bet:
betTimes = int(input('How many times would you like to bet this round?: '))
for a in range(betTimes):
betAmount = int(input('Enter the amount you would like to bet this round: $1, $2, $5, or $10: '))
symbol = int(input('Enter the number corresponding to the symbol you would like to bet on\n' # asking user what symbol they want to bet on - assigning it to a variable
'1: Crown\n'
'2: Anchor\n'
'3: Heart\n'
'4: Diamond\n'
'5: Club\n'
'6: Spade\n'
))
bets.update({symbol:betAmount})
print(bets)
def main():
balance1 = getPlayers()
collectBets(balance1)
main()
Any help would be much appreciated! Thank you!
It is best to think of a Python Dictionary as "an un ordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)." https://docs.python.org/3/tutorial/datastructures.html
With that being said, whenever user A chooses 10, and then user B chooses 10; user A choice is literally being overwritten by user B's choice. A single dictionary can only hold 10 once as a key. In order to resolve your solution you'll have to use some other data structures. The key within a dictionary should be unique.
A solution to your problem could be to use different levels of dictionaries. You could have a dictionary of player names that holds a dictionary of their value, and their symbol. However, your player names would have to be unique, otherwise you would run into the same issue.
I am trying to create an attendance logger where I create a dictionary which I fill with student names. The names will be lists where I append their class attendance data (whether they attended class or not). The code I have so far is displayed below`
#! /bin/python3
#add student to dict
def add_student(_dict):
student=input('Add student :')
_dict[student]=[]
return _dict
#collect outcomes
def collector(student,_dict, outcome):
_dict[student].append(outcome)
return _dict
#counts target
def count(_dict,target):
for i in _dict:
# records total attendance names
attendance_stat = len(_dict[i])
# records total instances absent
freq_of_absence=_dict[i].count(target)
# records percentage of absence
perc_absence = float((freq_of_absence/attendance_stat)*100)
print(i,'DAYS ABSENT =',freq_of_absence)
print('TOTAL DAYS: ', i, attendance_stat)
print('PERCENTAGE OF ABSENCE:', i, str(round(perc_absence, 2))+'%')
#main function
def main():
#date=input('DATE: ')
outcomes=['Y','N']
student_names = {}
try:
totalstudents = int(input('NO. OF STUDENTS: '))
except ValueError:
print('input an integer')
totalstudents = int(input('NO. OF STUDENTS: '))
while len(student_names) < totalstudents:
add_student(student_names)
print(student_names)
i = 0
while i < totalstudents:
i = i + 1
target='Y'
student=str(input('student :'))
outcome=str(input('outcome :'))
collector(student,student_names,outcome)
count(student_names,target)
if __name__=='__main__':
main()
`
The code works well so far but the problem is when the number of students is too large, time taken to input is extensive cutting in on class time. Since the number of absentees is usually less than those present, is it possible to select from the dictionary students absent which will append the value Y for each selected absent, while appending N to the remaining lists in dictionary.
This isn't exactly what you're asking for, but I think it will help. Instead of asking the user to input a name each time for the second part, why not just print the name yourself, and only ask for the outcome? Your last while loop would then become a for loop instead, like this:
for student_name in student_names:
outcome = input("Outcome for {}: ".format(sudent_name))
collector(student_name, student_names, outcome)
You could also add some logic to check if outcome is an empty string, and if so, set it to 'N'. This would just allow you to hit enter for most of the names, and only have to type in 'Y' for the certain ones that are absent. That would look like this:
for student_name in student_names:
outcome = input("Outcome for {}: ".format(sudent_name))
if outcome = "":
outcome = "N"
collector(student_name, student_names, outcome)