I am writing a program using the while loop. I'm trying to write a program to ask the marital status and age of 3 people. The problem I am having is that if I put in an input other than "married", it doesn't add it to the right output. So what I'm asking is how do I make it so that when I put in an input of, for example, "single", the output says, the number of people who are single is: 1?
Here's my code:
marriedstud=0
sepstud=0
marriedover50=0
married40s=0
married30s = 0
married20s = 0
sepover50=0
sep40s=0
sep30s = 0
sep20s = 0
divorcedstud=0
divorcedover50=0
divorced40s = 0
divorced30s = 0
divorced20s = 0
singleover50=0
single40s=0
single30s=0
single20s = 0
singlestud=0
age=0
count = 0
while (count < 2):
maritalstatus= input("Please enter persons marital status:")
age =input("Please enter perons age: ")
if (maritalstatus=="MARRIED") or (maritalstatus=="married"): #I tried using 'and' and 'or' but neither work
marriedstud = marriedstud + 1
if (age>=50):
marriedover50 = marriedover50 + 1
elif (age>=40) and (age<50):
married40s = married40s + 1
elif (age>=30) and (age<40):
married30s = married30s + 1
elif (age>=20) and (age<30):
married20s = married20s + 1
else:
if (maritalstatus=="SINGLE") or (maritalstatus=="single"):
singlestud = singlestud + 1
if (age>=50):
singleover50 = singleover50 + 1
elif (age>=40) and (age<50):
single40s = single40s + 1
elif (age>=30) and (age<40):
single30s = single30s + 1
elif (age>=20) and (age<30):
single20s = single20s + 1
else:
if (maritalstatus=="DIVORCED") or (maritalstatus=="divorced"):
divorcedstud = divorcedstud + 1
if (age>=50):
divorcedover50 = divorcedover50 + 1
elif (age>=40) and (age<50):
divorced40s = divorced40s + 1
elif (age>=30) and (age<40):
divorced30s = divorced30s + 1
elif (age>=20) and (age<30):
divorced20s = divorced20s + 1
else:
if(maritalstatus=="SEPARATED") or (maritalstatus=="separated"):
sepstud = sepstud + 1
if (age>=50):
sepover50 = sepover50 + 1
elif (age>=40) and (age<50):
sep40s = sep40s + 1
elif (age>=30) and (age<40):
sep30s = sep30s + 1
elif (age>=20) and (age<30):
sep20s = sep20s + 1
count += 1
print("The number of pepole who are married is: " +str(marriedstud))
print("The number of pepole who are married and over the 50 is: " +str(marriedover50))
print("The number of pepole who are married and in the age group of 40's is: " +str(married40s))
print("The number of pepole who are married and in the age group of 30's is: " +str(married30s))
print("The number of pepole who are married and in the age group of 20's is: " +str(married20s))
print("*****")
print("The number of pepole who are single is: " +str(singlestud))
print("The number of pepole who are single and over the 50 is: " + str(singleover50))
print("The number of pepole who are single and in the age group of 40's is: " +str(single40s))
print("The number of pepole who are single and in the age group of 30's is: " +str(single30s))
print("The number of pepole who are single and in the age group of 20's is: " +str(single20s))
print("*****")
print("The number of pepole who are divorced is: " +str(divorcedstud))
print("The number of pepole who are divorced and over the 50 is: " +str(divorcedover50))
print("The number of pepole who are divorced and in the age group of 40's is: " +str(divorced40s))
print("The number of pepole who are divorced and in the age group of 30's is: " +str(divorced30s))
print("The number of pepole who are divorced and in the age group of 20's is: " +str(divorced20s))
print("*****")
print("The number of pepole who are separated is: " +str(sepstud))
print("The number of pepole who are separated and over the 50 is: " +str(sepover50))
print("The number of pepole who are separated and in the age group of 40's is: " +str(sep40s))
print("The number of pepole who are separated and in the age group of 30's is: " +str(sep30s))
print("The number of pepole who are separated and in the age group of 20's is: " +str(sep20s))
print("*****")
This is a clash between data types. When the user enters the age after marital status, they enter it as a string, which you cannot compare with integers like 20,30,40, etc. you need to do this:
int(age)
instead of just:
age
please mark as correct if this helps
Related
So, i'm new to python and trying to learn it, i've watched some clips on youtube and came up with this, but the last part to check in the quantity is or is not in the list range is not working....
print ("Hello, my name is Dave, welcome to our coffe shop!!")
name = input ("What is your name?\n")
print("Hello " + name + ", thank you for comming to our coffe shop!")
print ("What can i get you ?")
menu = str("caffe latte, " + "tea, " + "black coffe")
menu_choice = ["caffe latte","tea","black coffe"]
choice1 = input() # anything
print ("This is our menu:")
print (menu)
unavailable = True
# order loop for the coffe
while unavailable:
order = input ()
if order in menu_choice:
unavailable = False
print ("And how many " + order + " would you like?")
else:
print ("Sorry we dont have " + order + ", this is our menu :\n" + menu)
if order == "caffe latte":
price = 13
elif order == "tea":
price = 9
elif order == "black coffe":
price = 15
#quantity loop
list(range(1, 10))
#here is the problem i'm having RN, the part with if not in in list is skipped
choice_number = True
while choice_number:
quantity = input()
total = price * int(quantity)
if quantity not in {list} :
choice_number = False
if quantity == "1" :
print ("Alright " + name, "that will be " + str(total) +"$,", "a", order + " comming at you!")
elif quantity >= "2" :
print ("Alright " + name, "that will be " + str(total) +"$,", quantity + " " + order + " comming at you!")
else:
print ("Quantity invalid, please select a number from 1 to 10.")
Assign this list(range(1, 10)) in a variable like qty_lst = list(range(1, 10)).
or you can simnply write:
if quantity not in list(range(1, 10)):
quantity = input("Enter Quantity")
total = price * int(quantity)
if quantity not in range(1,10) :
print ("Quantity invalid, please select a number from 1 to 10.")
else:
if quantity == "1":
print("Alright " + name, "that will be " + str(total) + "$,", "a", order + " comming at you!")
elif quantity >= "2":
print("Alright " + name, "that will be " + str(total) + "$,", quantity + " " + order + " comming at you!")
I would recommend getting rid of the listed range and just doing it like this, also you don't need a while True loop its not really needed
if quantity < 1 or quantity > 10:
# not in range
else:
# in range
Dont use if ... in range(), i'm not sure about this, but i think that doing so, python will not know that the sequence is in order and will check your value against all the sequence.
If i'm wrong, let's say i learned something :D
im learning python and for my homework i wanna make a food ordering program and get the receipt of the products purchased with the prices for the total. im struggling to get the billing process as i cannot get all the products chosen by the user displayed on the receipt
import datetime
x = datetime.datetime.now()
name = input("Enter your name: ")
address = input("Enter your address: ")
contact = input("Enter your phone number: ")
print("Hello " + name)
print("*"*31 + "Welcome, these are the items on on the menu."+"*" * 32 )
print("Menu:\n"
"1.Burger:150.\n"
"2.Fried Momo:120.\n"
"3.coffee:60.\n"
"4.Pizza:180.\n"
"5.Fried Rice:150.\n"
"6.French Fries:90.\n"
"7.Steamed Dumplings:150.\n"
"8.Chicken drumsticks:120.\n"
"9.Chicken Pakoras:120.\n"
"10.American Chop Suey:200.\n")
prices = {"1.Burger":150,
"2.Fried Momo":120,
"3.coffee":60,
"4.Pizza":180,
"5.Fried Rice":150,
"6.French Fries":90,
"7.Steamed dumplings":150,
"8.Chicken drumsticks":120,
"9.Chicken Pakoras":120,
"10.American Chop Suey":200
}
continue_order = 1
total_cost, total = 0, 0
cart = []
while continue_order != 0:
option = int(input("Which item would you like to purchase?: "))
cart.append(option)
if option >= 10:
print('we do not serve that here')
break
elif option == 1:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: ₹" + str(total))
elif option == 2:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 3:
quantity = int(input("Enter the quantity: "))
total = quantity * 60
print("The price is: " + str(total))
elif option == 4:
qquantity = int(input("Enter the quantity: "))
total = quantity * 180
print("The price is: " + str(total))
elif option == 5:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 6:
quantity = int(input("Enter the quantity: "))
total = quantity * 90
print("The price is: " + str(total))
elif option == 7:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 8:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 9:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 10:
quantity = int(input("Enter the quantity: "))
total = quantity * 200
print("The price is: " + str(total))
total_cost += total
continue_order = int(input("Would you like another item? enter Yes--> (1) or--> No (0):"))
print('='*30)
print('='*30)
print("Your receipt:\n")
print("Date: " + str(x))
print("Name: " + name.title())
print("Adress: " + address)
print("Contact number: " + contact)
for option in cart:
print ("Item: %s. Price: %s") % (option, prices[option])
print("Quantity: ",quantity)
print("Total Price: ", total_cost)
print('='*30)
print("Thank you for shopping here, have a great day ")
print('='*30)
but i get an error line 95, in
print ("Item: %s. Price: %s") % (option, prices[option])
KeyError: 1
any solution or better ways to improve the code would be really great
Try using F-Strings. They let you format text far more easily. Here's an example.
x = "hello!"
print(f"shr4pnel says {x}")
>>> shr4pnel says hello!
The problem in this case is that option == 1. 1 isn't a key in the dictionary so nothing is output. Hope this helps. This is because the dictionary does not have 1 as a key. To access the item the dictionary would have to be formatted like this.
prices = {1: "burger", 2: "hot dog"}
print(prices[1])
>>> burger
I'm a beginner in python. I have created a database for student in python. I'm not able to get the output for all iterations in dict.
my source code:-
n = int(raw_input("Please enter number of students:"))
student_data = ['stud_name', 'stud_rollno', 'mark1', 'mark2','mark3','total', 'average'] for i in range(0,n):
stud_name=raw_input('Enter the name of student: ')
print stud_name
stud_rollno=input('Enter the roll number of student: ')
print stud_rollno
mark1=input('Enter the marks in subject 1: ')
print mark1
mark2=input('Enter the marks in subject 2: ')
print mark2
mark3=input('Enter the marks in subject 3: ')
print mark3
total=(mark1+mark2+mark3)
print"Total is: ", total
average=total/3
print "Average is :", average
dict = {'Name': stud_name, 'Rollno':stud_rollno, 'Mark1':mark1, 'Mark2':mark2,'Mark3':mark3, 'Total':total, 'Average':average} print "dict['Name']: ", dict['Name'] print "dict['Rollno']: ", dict['Rollno'] print "dict['Mark1']: ", dict['Mark1'] print "dict['Mark2']: ", dict['Mark2'] print "dict['Mark3']: ", dict['Mark3'] print "dict['Total']: ", dict['Total'] print "dict['Average']: ", dict['Average']
if i give no of students as 2, I'm getting dict for 2nd database only and not for 1st one too.
output that i got
Please enter number of students:2
Enter the name of student: a
a
Enter the roll number of student:1
1
Enter the marks in subject 1:1
1
Enter the marks in subject 2:1
1
Enter the marks in subject 3:1
1
Total is:3
Average is :1
Enter the name of student:b
b
Enter the roll number of student:2
2
Enter the marks in subject 1:2
2
Enter the marks in subject 2:2
2
Enter the marks in subject 3:2
2
Total is:6
Average is :2
dict['Name']:b
dict['Rollno']:2
dict['Mark1']:2
dict['Mark2']:2
dict['Mark3']:2
dict['Total']:6
dict['Average']:2
Your current code overwrites dict for every i. In addition, you shouldn't use the name dict as this causes confusion with the data type dict in Python.
One solution for you is to use a list of dictionaries, something like the following:
n = int(raw_input("Please enter number of students:"))
all_students = []
for i in range(0, n):
stud_name = raw_input('Enter the name of student: ')
print stud_name
stud_rollno = input('Enter the roll number of student: ')
print stud_rollno
mark1 = input('Enter the marks in subject 1: ')
print mark1
mark2 = input('Enter the marks in subject 2: ')
print mark2
mark3 = input('Enter the marks in subject 3: ')
print mark3
total = (mark1 + mark2 + mark3)
print"Total is: ", total
average = total / 3
print "Average is :", average
all_students.append({
'Name': stud_name,
'Rollno': stud_rollno,
'Mark1': mark1,
'Mark2': mark2,
'Mark3': mark3,
'Total': total,
'Average': average
})
for student in all_students:
print '\n'
for key, value in student.items():
print '{0}: {1}'.format(key, value)
By adding the responses for each new student onto the end of the list, we track all of them in turn. Finally, we print them out using the keys and values stored in the dictionary. This prints, with your inputs:
Name: a
Rollno: 1
Average: 1
Mark1: 1
Mark2: 1
Mark3: 1
Total: 3
Name: b
Rollno: 2
Average: 2
Mark1: 2
Mark2: 2
Mark3: 2
Total: 6
stud = {}
mrk = []
print("ENTER ZERO NUMBER FOR EXIT !!!!!!!!!!!!")
print("ENTER STUDENT INFORMATION ------------------------ ")
while True :
rno = int(input("enter roll no.. :: -- "))
if rno == 0 :
break
else:
for i in range(3):
print("enter marks ",i+1," :: -- ",end = " ")
n = int(input())
mrk.append(n)
stud[rno] = mrk
mrk = []
print("Records are ------ ",stud)
print("\nRollNo\t Mark1\t Mark2\t Mark3\t Total")
tot = 0
for r in stud:
print(r,"\t",end=" ")
for m in stud[r]:
tot = tot + m
print(m,"\t",end=" ")
print(tot)
tot = 0
How would a computer program deal with user misspelling of words in such a way that forces them to reenter until it is correct? e.g. Entering Male and Female for a gender argument. I'm using this Python code:
def mean(values):
length = len(values)
total_sum = 0
for i in range(length):
total_sum += values[i]
total_sum = sum (values)
average = total_sum*1.0/length
return average
name = " "
Age = " "
Gender = " "
people = []
ages = []
while name != "":
### This is the Raw data input portion and the ablity to stop the program and exit
name = input("Enter a name or type done:")
if name == 'done' : break
Age = int(input('How old are they?'))
Gender = input("What is their gender Male or Female?")
### This is where I use .append to create the entry of the list
people.append(name)
people.append(Age)
ages.append(Age)
people.append(Gender)
### print("list of People:", people)
#### useing the . count to call how many m of F they are in the list
print ("Count for Males is : ", people.count('Male'))
print ("Count for Females is : ", people.count('Female'))
### print("There ages are",ages)
### This is where I put the code to find the average age
x= (ages)
n = mean(x)
print ("The average age is:", n)
I would like to also force an age in the 18-25 range.
"... that forces them to reenter until it is correct?... "
Since you also asked for a way to re-enter, the following snippet uses an escape sequence of the form \033[<N>A which moves the cursor up N lines and the Carriage Return escape sequence, \r, to print over the invalid data and take input again.
import sys
age = 0
gender = ""
agePrompt = "How old are they? "
genderPrompt = "What is their gender Male or Female? "
#Input for age
print("")
while not ( 18 <= age <= 25 ):
sys.stdout.write( "\033[1A\r" + " " * (len(agePrompt) + len(str(age))) )
sys.stdout.write( "\r" + agePrompt )
sys.stdout.flush()
age=int(input())
#Input for gender
print("")
while not ( gender == "Male" or gender == "Female" ) :
sys.stdout.write( "\033[1A\r" + " " * (len(genderPrompt) + len(str(gender))) )
sys.stdout.write( "\r" + genderPrompt )
sys.stdout.flush()
gender=str(input())
Another solution would be to use the escape sequence of the form \033[<N>D which moves the cursor backward N columns.
Simply use a while operator that continues until you have satisfied the condition you wish be satisfied.
Gender = ""
while Gender != "Male" or Gender != "Female":
Gender = raw_input("What is your gender, Male or Female?")
Just keep looping until they give a valid input. Do the same for the gender.
Age = ""
while True:
Age = int(input('How old are they?'))
if int(Age) >= 18 and int(Age) <= 25:
break
Here is a small chunk of a code I have:
studentName = ""
def getExamPoints (total):
for i in range (4):
total = 0.0
examPoints = input ("Enter exam score for " + studentName + str(i+1) + ": ")
total = ?????
total = total/.50
total = total * 100
where the ????? is I can't figure out how to get the string to add the four scores
student name I inputed later and it is required that later in the program I use examPoints = getExamPoints(studentName).
Without any error checking for bad input:
total = 0.0
for i in range (4):
total += int(input ("Enter exam score for " + studentName + str(i+1) + ": "))
total = total/.50
total = total * 100
Did you try
total += int(examPoints);