So I was given a problem by my Computer Science teacher, but I have been sat here for ages and cannot for the life of me figure it out. There are plenty of tasks within the problem, but there is only one I'm having trouble with.
So, I am coding a program for a carpet shop, and the part that I am stuck on is this.
2: For each floor you need to carpet, ask the user for the name of the room that the floor is located in.
Basically X number of rooms; need to loop a sentence asking for the name of the room multiplied by X. So if the user has 3 rooms they need carpeted, I would end up with the name of 3 rooms (Lounge, Bedroom etc.), and be able to display these results back to the user later. Here is what I have so far...
#Generating An Estimate.
#Welcome message + setting base price to 0 + defining "getting_estimate" variable.
def getting_estimate ():
overallPrice = 0
print("Welcome!")
#Getting the information about the customer.
custID = input ("\n1. Please enter the customer's ID: ")
estimateDate = input ("\n2. Please enter the date: ")
numberOfRooms = input (int("\n3. Please enter the number of rooms that need to be carpeted: "))
#Add input allowing user to enter the
#name of the room, looped by the integer entered
#in the Variable "numberOfRooms", and possibly
#adding 1st room, 2nd room etc??
If someone can work this out they are helping me loads. Thanks :)
Perhaps using a for loop perhaps?
for i in range(numberOfrooms):
roomName = input("Blah blah")
Full code:
def getting_estimate ():
overallPrice = 0
print("Welcome!")
custID = input ("\n1. Please enter the customer's ID: ")
estimateDate = input ("\n2. Please enter the date: ")
numberOfRooms = int (input("\n3. Please enter the number of rooms that need to be carpeted: "))
cust_roster = {custID:[]}
for i in range(numberOfRooms):
roomName = input("Enter the name of room number "+str(i+1))
cust_roster[custID].append(roomName)
print("{} has {} rooms called: {}".format(custID,
len(cust_roster[custID]),
cust_roster[custID]))
Btw I'm doing a similar task for my OCR computing coursework ;) so good luck!
Related
I'm not sure how to phrase the question so instead I will copy/paste the prompt from my homework and hopefully that will make my question clear. I am very new to python and am almost totally lost in how to complete this task. The task is as follows:
I am stuck on part B.
a. Three Strikes Bowling Lanes hosts an annual tournament for 12 teams Design a program that accepts each team's name and total score for the tournament and stores them in parallel arrays. Display the names of top three teams.
b. Modify the bowling tournament program so that, instead of the team's total score, the program accepts the score of each of the four team members. Display the names of the five top scorers in the tournament as well as their team names
Here is what I have so far for part A, though I still cant get it to sort by the highest score while displaying the correct team name.
scores = range(0,12)
names = range(0,12)
teamScore = []
teamName = []
for names in names:
name = input("Please enter the team name: ")
teamName.append(name)
print("\n" + "Please enter the team scores here: ")
for scores in scores:
score = input("Please enter the team score: ")
teamScore.append(score)
result = sorted(zip((teamName, teamScore)))
print(result)
Welcome to the SO community!
This is obviously not a complete answer bit should help you make some progress.
count = 3 # Pretend there are only 3 teams for ease in debugging
names = [] # The team names (we don't need long names in a simple program)
for i in range(count): # Do this for each of "count" teams.
name = input("Please enter the team name: ") # Get the name
names.append(name) # Add it at the end of the names list.
print(names)
Session output:
Please enter the team name: The Bulldogs
Please enter the team name: Strikers
Please enter the team name: Out of this world
['The Bulldogs', 'Strikers', 'Out of this world']
Try improving this as much as you can and come back with any questions.
I am writing a programme for my class where I must take get input data from a user and put that data into a record which in turn goes into an array.
def createArray0fRecords(length):
city_records = ["", "", 0.0,""]#Create record
#City, Country, Population in Millions, Main Language
city_array = [city_records]*length #Create Array of Records
return city_array
def populateRecords(city_array):
for counter in range (0, len(city_array)):
print("")
print("Please enter the city")
city=input()
print('Please enter the country')
country=input()
print("Please enter the population in millions")
population=float(input())
while population < 0:
print(population," isn't a valid answer. Please input a number greater than 0.")
population=input()
print("Please enter the main language")
language = input()
city_array[counter] = [city, country, population, language]
return city_array
def main_program():
print("How many cities will you be entering?")
length = int(input())
city_array = createArray0fRecords(length)
city_array = populateRecords(city_array)
print("What city would you like the information about?")
city=input()
if city in (city_array[1]):
print(city_array[city])
main_program()
I believe I am almost there and it is just the las few lines that must now be changed. Thanks
Sorry, I am new to stack overflow and I have realised I worded my question wrong, what I must do is Take all of the information in, then I must input what city I would like to get the information about and the program will give me the information about that city
You can filter city_array by the relevant city name like so (you can read on list comprehensions here)
relevant_cities = [c for c in city_array if c[0] == city]
relevant_cities will now be an list of all records having city equal to the user's input. You can now check if this list is empty and do whatever you'd like with it.
My program is supposed to store contacts. When I enter the number I need the program to keep asking for the number if there is no user input. For now my program considers the contact added even if there is no number entered by user input.
I tried to use a while True or if not. The closest I got to solving the problem was when the program asked a second time for to enter a number but that's all.
def add_contact(name_to_phone):
# Name...
names = input("Enter the name of a new contact:")
# Number...
numbers = input("Enter the new contact's phone number:")
# Store info + confirmation
name_to_phone[names]= numbers
print ("New contact correctly added")
return
Select an option [add, query, list, exit]:add
Enter the name of a new contact:Bob
Enter the new contact's phone number:
New contact correctly added
Select an option [add, query, list, exit]:
As I said the program should keep asking for a number if there is no user input and go to the next step only when there is a user input.
Use a loop.
def add_contact(name_to_phone):
while True:
name = input("Enter the name of a new contact: ")
if name:
break
while True:
number = input("Enter the new contact's phone number: ")
if number:
break
name_to_phone[name] = number
print("New contact correctly added")
You may want to do a more thorough check for the name and number beyond checking if the input is empty or not.
In Python 3.8 or later, you can simply each loop a bit. Maybe this will become an standard idiom; maybe not.
while not (name := input("Enter the name...: ")):
pass
I have to make this program:
Write a program that allows a teacher to input how many students are in his/ her class, then allow them to enter in a name and mark for each student in the class using a for loop. Please note you do not need to record all of the names for later use, this is beyond the scope of the course * so just ask them each name, have it save the names over top of each other in ONE name variable.
i.e.)
INSIDE OF A LOOP
name = input (“Please enter student name: “)
Calculate the average mark for the entire class – this will require you to use totaling.
Output the class average at the end of the program, and ask if they would like to enter marks for another class. If they say yes, re-loop the program, if no, stop the program there.
So I started writing the program and it looks like this
studentamount = int(input("Please enter how many students are in your class: "))
for count in range():
name = input ("Please enter student name: ")
mark = int(input("Please enter the student's mark"))
I ran into the following problem: how would I allow the set of code under the for loop to loop for each student? I was thinking I could just enter in the studentamount variable as the range but I can't since python does not allow you to enter in a variable as a range.
How would I get the for loop to loop for the amount of students typed in? e.g. if 20 students for student amount was typed in, I would want the for loop to loop 20 times. Your help and knowledge is much appreciated.
Read the user input, convert it to int and pass it as a parameter to range:
studentamount = input("Please enter how many students ...: ") # this is a str
studentamount = int(studentamount) # cast to int ...
for count in range(studentamount): # ... because that's what range expects
# ...
Python does not allow you to enter in a variable as a range.
Python does allow you to enter variables as a range, but they must be numbers. Input () reads input in as string, so you need to cast it.
So, this is correct:
```Python
studentamount = int(input("Please enter how many students are in your class: "))
for count in range(studentamount):
name = input ("Please enter student name: ")
mark = int(input("Please enter the student's mark)
```
P.S a try - except clause would be useful here to catch people entering a non-integer data in [TypeError]
P.S.P.S #schwobaseggl 's example is good too, it is possibly more pythonistic to use the nested function studentamount = int(input("Text") than
studentamount = input("Text")
studentamount = int(studentamount)
You can store each student name and mark in a dictionary or tuple and store each dictionary (or tuple) into a list, see code sample (at the end enter "no" to exit or any other value to re-loop the program):
response = None
while response != 'no':
student_count = int(input('Please enter the number of students: '))
students = []
mark_sum = 0
print('There are {} student(s).'.format(student_count))
for student_index in range(student_count):
student_order = student_index + 1
student_name = input('Please enter the name of student number {}: '.format(student_order))
student_mark = float(input('Please enter the mark of student number {}: '.format(student_order)))
students.append({'name': student_name, 'mark': student_mark})
mark_sum += student_mark
print('The average mark for {} student(s) is: {}'.format(student_count, mark_sum / student_count))
response = input('Do you want to enter marks for another class [yes][no]: ')
I've asked a similar question but to no avail.
I am a novice programming student and I've only been taught some basic techniques. Part of a task is to create a recipe program which I've mostly done, there is just one part preventing me from finishing.
I am supposed to allow a user to call a previously created text file (I've done this bit), then after this the contents of this file should be displayed for them to see (I've also done this bit), however the user should be able to recalculate the servings and therefore change the quantity of the ingredients. So if the user entered: "I want 2 servings" and the original quantity for 1 serving was 100g it should now output 200g.
It is really frustrating me and my teacher expects this work tomorrow. Below is what I am supposed to allow the user to do.
The user should be able to retrieve the recipe and have the ingredients recalculated for a different number of people.
• The program should ask the user to input the number of people.
• The program should output:
• the recipe name
• the new number of people
• the revised quantities with units for this number of people.
I will post my actual code below to show what I have done so far, which is to allow a user to view and make a new recipe. But the revised quantities bit is missing.
I apologise if the code is messy or unorganised, I am new to this.
Code so far:
#!/usr/bin/env python
import time
def start():
while True:
user_input = input("\nWhat would you like to do? " "\n 1) - Enter N to enter a new recipe. \n 2 - Enter V to view an exisiting recipe, \n 3 - Enter E - to edit a recipe to your liking. \n 4 - Or enter quit to halt the program " "\n ")
if user_input == "N":
print("\nOkay, it looks like you want to create a new recipe. Give me a moment..." "\n")
time.sleep(1.5)
new_recipe()
elif user_input == "V":
print("\nOkay, Let's proceed to let you view an existing recipe stored on the computer")
time.sleep(1.5)
exist_recipe()
elif user_input == "E":
print("\nOkay, it looks like you want to edit a recipe's servings. Let's proceed ")
time.sleep(1.5)
modify_recipe()
elif user_input == "quit":
return
else:
print("\nThat is not a valid command, please try again with the commands allowed ")
def new_recipe():
new_recipe = input("Please enter the name of the new recipe you wish to add! ")
recipe_data = open(new_recipe, 'w')
ingredients = input("Enter the number of ingredients ")
servings = input("Enter the servings required for this recipe ")
for n in range (1,int(ingredients)+1):
ingredient = input("Enter the name of the ingredient ")
recipe_data.write("\nIngrendient # " +str(n)+": \n")
print("\n")
recipe_data.write(ingredient)
recipe_data.write("\n")
quantities = input("Enter the quantity needed for this ingredient ")
print("\n")
recipe_data.write(quantities)
recipe_data.write("\n")
unit = input("Please enter the unit for this quantity (i.e. g, kg) ")
recipe_data.write(unit)
print("\n")
for n in range (1,int(ingredients)+1):
steps = input("\nEnter step " + str(n)+ ": ")
print("\n")
recipe_data.write("\nStep " +str(n) + " is to: \n")
recipe_data.write("\n")
recipe_data.write(steps)
recipe_data.close()
def exist_recipe():
choice_exist= input("\nOkay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. ")
exist_recipe = open(choice_exist, "r+")
print("\nThis recipe makes " + choice_exist)
print(exist_recipe.read())
time.sleep(1)
def modify_recipe():
choice_exist = input("\nOkay, it looks like you want to modify a recipe. Please enter the name of this recipe ")
exist_recipe = open(choice_exist, "r+")
servrequire = int(input("Please enter how many servings you would like "))
start()
EDIT:
Below is an example creation of a text file (recipe) and it's output (the file is called bread.txt) Note the outputs are a bit messy, I will fix that once I can get the core of the program to work.
Creating a recipe
What would you like to do?
1) - Enter N to enter a new recipe.
2 - Enter V to view an exisiting recipe,
3 - Enter E - to edit a recipe to your liking.
4 - Or enter quit to halt the program
N
Okay, it looks like you want to create a new recipe. Give me a moment...
Please enter the name of the new recipe you wish to add! bread.txt
Enter the number of ingredients 3
Enter the servings required for this recipe 1
Enter the name of the ingredient flour
Enter the quantity needed for this ingredient 300
Please enter the unit for this quantity (i.e. g, kg) g
Enter the name of the ingredient salt
Enter the quantity needed for this ingredient 50
Please enter the unit for this quantity (i.e. g, kg) g
Enter the name of the ingredient water
Enter the quantity needed for this ingredient 1
Please enter the unit for this quantity (i.e. g, kg) l
Enter step 1: pour all ingredients into a bowl
Enter step 2: mix together
Enter step 3: put in a bread tin and bake
Viewing a recipe
What would you like to do?
1) - Enter N to enter a new recipe.
2 - Enter V to view an exisiting recipe,
3 - Enter E - to edit a recipe to your liking.
4 - Or enter quit to halt the program
V
Okay, Let's proceed to let you view an existing recipe stored on the computer
Okay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. bread.txt
This recipe makes bread.txt
Ingrendient # 1:
flour
300
g
Ingrendient # 2:
salt
50
g
Ingrendient # 3:
water
1
l
Step 1 is to:
pour all ingredients into a bowl
Step 2 is to:
mix together
Step 3 is to:
put in a bread tin and bake
And here is the output if you enter V:
This recipe makes bread.txt
Ingrendient # 1:
flour
300
g
Ingrendient # 2:
salt
50
g
Ingrendient # 3:
water
1
l
Step 1 is to:
pour all ingredients into a bowl
Step 2 is to:
mix together
Step 3 is to:
put in a bread tin and bake
I look forward to your replies.
It looks like your recipe files look like this:
Ingrendient # N:
{INGREDIENT}
{AMOUNT}
{METRIC}
...
(After N ingredients...)
Step N:
{INSTRUCTIONS}
So basically you want to read four lines at a time, discard the first, then assign the rest to something useful.
with open(path_to_recipe) as infile:
ingredients = []
while True:
try:
sentinel = next(infile) # skip a line
if sentinel.startswith("Step"):
# we're past the ingredients, so
break
name = next(infile)
amount = next(infile)
metric = next(infile)
except StopIteration:
# you've reached the end of the file
break
ingredients.append({'name':name, 'amount':float(amount), 'metric':metric})
# use a dictionary for easier access
When we exit the with block, ingredients will be a list of dictionaries that can be used as follows:
for ingredient in ingredients:
scaled_volume = ingredient['amount'] * scale # double portions? etc...
print(scaled_volume, ingredient['metric'], " ", ingredient['name'])
# # RESULT IS:
300g flour
50g salt
1l water
You should be able to leverage all that to finish your assignment!