I'm running a file with 2 functions, it Works correctly but it display the following when I run it:
Enter your weight (in Kilograms): 81
Enter your height (in Centimeters): 175
Enter your age: 20
Enter 5 if you are a male or -161 if you are female: 5
('You have to consume between: ', 1447.0, 'and', 1537.4375, 'calories a day.')
Below is my code:
def calBurned(weight:float, height:float, age: int, genderValue:float)->str:
TMB = (10*weight)+(6.25*height)-(5*age) + genderValue
minCal = TMB*0.80
maxCal = TMB*0.85
text = "You have to consume between ", minCal, "and", maxCal, "calories a day."
return text
def calRec()->None:
weight = float(input("Enter the your weight (in Kilograms): " ))
height = float(input("Enter your height (in Centimeters): "))
age = int(input("Enter your age: "))
genderValue = float(input("Enter 5 if you are a male or -161 if you are female: "))
calRecom= calBurned(weight, height, age, genderValue)
print(calRecom)
calRec()
Is it posible to return just the text without the all the (',')?
Your text is a tuple. You can convert each of its items to a string and return the concatenation of them:
text = " ".join(map(str, text))
You can also build text as a string in the first place:
text = f"You have to consume between {minCal} and {maxCal} calories a day."
Last but not least, a function should not return formatted text; it should return the results of computations (minCal,maxCal). Formatting should be done by the caller.
Use:
text = "You have to consume between {} and {} calories a day.".format(minCal, maxCal)
In calcBurned you didn't concatenate the strings, rather you made it a tuple, in this line:
text = "You have to consume between ", minCal, "and", maxCal, "calories a day."
change all the commas (,) to pluses (+), and change minCal and maxCal to str(minCal) and str(maxCal), and it should work:
text = "You have to consume between " + str(minCal) + " and " + str(maxCal) + " calories a day."
Just change
text = "You have to consume between ", minCal, "and", maxCal, "calories a day."
to
text = f"You have to consume between {minCal} and {maxCal} calories a day."
Related
I'm a beginner and this is my first receiving this message "IndexError: list index out of range," can someone please tell me how to fix it? and what exactly did I do wrong? Also if someone can run it and make sure it does what it's supposed to because I need another person other than me to run it(Professor's instruction)
This is the output it gave me -
Traceback (most recent call last):
File "", line 74, in
File "", line 24, in user
IndexError: list index out of range
Here's my code:
print ("Dish No. Dish Name Price ")
print (" -------- --------- ------")
print (" 1 Gang Gai $10.00")
print (" 2 Pad Thai $8.75")
print (" 3 Pad Cashew $9.50")
print (" 4 Pad Prik $10.25")
print (" 5 Peanut Curry $9.50")
print (" 6 Curry Noodles $11.25")
def user():
array = [10,8.75,9.50,10.25,9.50,11.25]
cart = []
while True:
x = int(input("Enter the item number you want (1-6):"))
check = checker(x)
if check == "wrong number":
print("Enter a valid number")
pass
cart.append(array[x-1])
xx=input("Would you like to order another item( Yes or No)?: ")
if xx.lower() == "no":
break
checkout(cart)
# if xx=='No'.lower():
# return array[x-1]
# else:
# return array[x-1]+user(array)
def seniorCitizen():
print("Are you 65 years or older(Yes or No)? ")
xsenior = input()
if xsenior.lower() == "yes":
senior = True
else:
senior = False
return senior
def checker(num):
if num > 6 or num < 1:
return "wrong number"
def checkout(cart):
senior = seniorCitizen()
titems = 0
for item in cart:
titems = titems + item
print(" Bill Information ")
print("-------------------------------")
print("Total of all items: $",titems)
if senior == True:
boomercount = titems * 0.1
boomercount = round(boomercount, 2)
print("Total senior discounts:-$", boomercount)
tax = round((titems-boomercount)*0.06, 2)
print("Taxes: $",tax)
print(" Bill: $", round(((titems-boomercount)+tax), 2))
else:
tax = round(titems*0.06, 2)
print("Taxes: $",tax)
print(" Bill: $", round((titems+tax), 2))
user()
while True:
x = int(input("Enter the item number you want (1-6):"))
check = checker(x)
if check == "wrong number":
print("Enter a valid number")
pass
cart.append(array[x-1])
The problem is the pass statement. It does not restart the loop -- it does nothing at all. So if the user enters a wrong number, it prints an error message but then it keeps going and tries to access array[x-1] which is out of range.
Use continue which will start the loop over, instead of pass.
I am trying to create a basic online store in python. But whenever I try to 'buy' an item it shows an error with my dictionary or something I am not sure.
The error: users[n]["Transactions"] = users[n]["Transactions"] + str(names_f, "bought", quanti, "of", final[choice*3], "with a total price of $"+price)
TypeError: str() takes at most 3 arguments (6 given)
coun = 0
users = [{"name":"Jack","username":"ja", "cc":'12345',"email":'whwhwwhh', "code": '111', "Transactions": ""}]
def sign_in():
username = input("Enter username")
for i in range (len(users)):
for x in users[i].values():
if x == username:
pin = input("Enter pin")
if pin == users[i].get("code"):
print("Welcome", users[i].get("name"))
menu(username,users[i].get("name"))
break
else:
print("Wrong pin")
sign_in()
def menu (usern, names_f):
global coun
if coun == 0:
order = ''
total = 0
for i in range (len(categories)):
print(str(i+1)+".", categories[i])
choice = int(input("Choose a category by typing the number beside the categories name."))-1
print("Items in this list are")
print("Itemname \t Price \t Stock")
final = location[choice]
for c in range((int(len(final)/3))):
print(str(c+1)+'.',str(final[c*3]),"\t",'$'+str(final[c*3+1])), "\t", str(final[(c*3)+2])
choice = int(input("Which item (Type number on left of the item name)"))-1
while True:
quanti = int(input("How many do you want to buy"))
if quanti > final[choice*3+2]:
print("Sorry your request for", quanti, "Is more than we have at the store please try again")
continue
else:
price = str(quanti*final[choice*3+1])
final[choice*3+2] = final[choice*3+2]-quanti
print("Thank you for your purchasing",quanti,"of", final[choice*3], "Your total price of this buy is", '$'+price)
for n in range (len(users)):
if usern == users[n].get("username"):
users[n]["Transactions"] = users[n]["Transactions"] + str(names_f, "bought", quanti, "of", final[choice*3], "with a total price of $"+price)
order += str(quanti, 'of', final[choice*3])
price += int(price)
done = input("Do you want to check out then type '1' if you want to continue type '2'")
if done == '1':
print("Thank you")
print ("Invoice:", order, "/n total price (HKD) $"+str(price))
else:
coun += 1
menu(usern,names_f)
variable_name = users[n]["Transactions"] + str(names_f) + "bought" + str(quanti) + "of" + str(final[choice*3]) + "with a total price of $"+ str(price)
users[n]["Transactions"] = variable_name
You will maybe need to declare variable_name somewhere.
Problem is that str usage is following
str(object, encoding=encoding, errors=errors)
but whenever you pass comma it count it as another parameter.
P.S. I'm not sure if you need all those str in my solution.
str is a class, and as stated in the docs you can pass up to 3 parameters to it:
class str(object=b'', encoding='utf-8', errors='strict')
Also, it also says what it does:
Return a string version of object. If object is not provided, returns the empty string.
Meaning it is used to cast other types to string. Thus, you need to convert every int individually:
users[n]["Transactions"] = users[n]["Transactions"] + str(names_f) + " bought " + str(quanti) + " of " + str(final[choice*3]) + " with a total price of " + str(price)
Note the spaces before and after every string. Alternatively, you can format your string:
users[n]["Transactions"] = users[n]["Transactions"] + '%s bought %s of %s with a total price of %s' % (names_f, quanti, final[choice*3], price)
As a side note, it's worth checking what happens when the first transaction is made. If the key Transactions does not yet exist, you need to add an initial value before accessing it.
I usually do it like:
if key not in dict_:
dict_[key] = 'my initial value'
dict_[key] += 'add my stuff'
another solution would be using the get method, which allows you to add a default value:
dict_.get(key, 'default')
Note that this will not add the key to the dictionary, meaning that trying to access its value later on will still result in a Key Error.
In my program I need to make simple math calc, but my variables are defind at str and i need to make it int for the calc and sum .
ex:
When age=40, in return I got 404040404040 (6 times the num 40)
is read the res like "str" and I need "int".
def check_age(age):
age = int(age)
return 30 * 6 if age >= 30 else 0
def just_married():
sum_married = 0
woman_age = int(input("Please enter the wife age [we know that is not ok ask woman about she's age] : ").strip())
sum_married = sum_married + check_age(woman_age)
husband = int(input("Please enter the husband age : ").strip())
sum_married = sum_married + check_age(husband)
return int(sum_married)
def children_age(number_of_children):
sum_children = number_of_children*50
return int(sum_children)
def work_hard():
print("for WIFE - Are you working part-time (0.5) or full-time (1)? : ")
wife_work = input()
print("for HUSBAND = Are you working part-time (0.5) or full-time (1)? : ")
husband_work = input()
sum_work = (wife_work+husband_work)*75
return int(sum_work)
def main():
sum_func = 0
print("The following is a program aimed at examining eligibility conditions "
"for participation in the tender Housing for the occupant.")
sum_func += just_married()
print("How many children over the age of 18 do you have? : ")
children = input()
sum_func += children_age(children)
sum_func += work_hard()
program_number = 599
if sum_func > program_number:
print("you got : " + str(sum_func) + " points ")
else:
print("sorry, but you need " + str(program_number-sum_func) + " point to join the program. try next time.")
main()
edit:
i edit the code, with the new change at func"check_age", and update the full code.
this is the input :
The following is a program aimed at examining eligibility conditions for participation in the tender Housing for the occupant.
Please enter the wife age [we know that is not ok ask woman about she's age] : 40
Please enter the husband age : 50
How many children over the age of 18 do you have? :
4
for WIFE - Are you working part-time (0.5) or full-time (1)? :
1
for HUSBAND = Are you working part-time (0.5) or full-time (1)? :
1
you got : 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111155555555555555555555555555555555555555555555555915 points
Process finished with exit code 0
In your function check_age:
def check_age(age):
age = int(age)
return 30 * 6 if age >= 30 else 0
Also, consider changing these lines:
print("Please enter the wife age [we know that is not ok ask woman about she's age] : ")
woman_age = input(int)
To this:
woman_age = int(input("Please enter the wife age [we know that is not ok ask woman about she's age] : ").strip())
Explanation:
input takes a string, prints it and wait for user input.
str.strip removes trailing spaces
int convert a variable to an integer
Once you've sanitized your inputs, you can remove the explicit conversion to int in check_age:
def check_age(age):
return 30 * 6 if age >= 30 else 0
[EDIT] A few more suggestion:
create a function sanitize_input that takes a text, ask for input
ad returns an integer. Then use it anywhere to replace print...input
create logic blocks that make sense: For example, the main function contains all the texts that print out to the screen and store all inputs for later. Then, only process the variables in one function like check_eligibility or something where you do all the calculations. If you do that, you code will be more understandable and less error prone, for you and for the people who try to help you
The string -> number conversions have to be done before you attempt any calculations, it is too late at the time of return, as the strange things have happened already. Remember/learn that Python can add strings (which is common to many languages, "1"+"1" is "11" in various other languages too), and on top of that, it can also multiply them with integer numbers, "1"*5 is "11111".
If you assume correct input from the user, the simplest thing is to do the conversion in the input lines, which already happens in just_married, but not in the other places.
And of course remember that when you expect an input like 0.5, those should be converted to float.
def check_age(age):
#age = int(age) - removed this one, should happen at input
return 30 * 6 if age >= 30 else 0
def just_married():
sum_married = 0
woman_age = int(input("Please enter the wife age [we know that is not ok ask woman about she's age] : ").strip())
sum_married = sum_married + check_age(woman_age)
husband = int(input("Please enter the husband age : ").strip())
sum_married = sum_married + check_age(husband)
return sum_married # removed int(), it is already an integer
def children_age(number_of_children):
sum_children = number_of_children*50
return sum_children # removed int(), it was too late here
# and it should happen at input
def work_hard():
print("for WIFE - Are you working part-time (0.5) or full-time (1)? : ")
wife_work = float(input()) # added float()
print("for HUSBAND = Are you working part-time (0.5) or full-time (1)? : ")
husband_work = float(input()) # added float()
sum_work = (wife_work+husband_work)*75
return int(sum_work) # int() may stay, depending on what should happen
# with fractions - they are just thrown away now
def main():
sum_func = 0
print("The following is a program aimed at examining eligibility conditions "
"for participation in the tender Housing for the occupant.")
sum_func += just_married()
print("How many children over the age of 18 do you have? : ")
children = int(input()) # added int()
sum_func += children_age(children)
sum_func += work_hard()
program_number = 599
if sum_func > program_number:
print("you got : " + str(sum_func) + " points ")
else:
print("sorry, but you need " + str(program_number-sum_func) + " point to join the program. try next time.")
main()
I think I'm almost there with my assignment. I'm trying to print:
"Hi John,(new line)
You have a 89.6% in your principle of programming course." However, when I print the below, it shows as follows:
"Hi John,(new line) You have a 89.4 % in your principle of programming course."
So could you guys help me how to put % sign without space? Are there better way to print these words?
student_name = input("Enter student's name: ")
course_name = input("Enter course name: ")
quizzes_weight = input("Enter quizzes weight: ")
projects_weight = input("Enter projects weight: ")
activities_weight = input("Enter activities weight: ")
attendance_weight = input("Enter attendance weight: ")
exams_weight = input("Enter exams weight: ")
quizzes_average = input("Enter quizzes average: ")
projects_average = input("Enter projects average: ")
activities_average = input("Enter activities average: ")
attendance_average = input("Enter attendance average: ")
exams_average = input("Enter exams average: ")
quizzes_weight = float(quizzes_weight)
projects_weight = float(projects_weight)
activities_weight = float(activities_weight)
attendance_weight = float(attendance_weight)
exams_weight = float(exams_weight)
quizzes_average = float(quizzes_average)
projects_average = float(projects_average)
activities_average = float(projects_average)
attendance_average = float(attendance_average)
exams_average = float(exams_average)
average_score_for_course = ((quizzes_weight * quizzes_average) +
(projects_weight * projects_average) + (activities_weight *
activities_average) + (attendance_weight * attendance_average) +
(exams_weight * exams_average)) * 100
print("Hi",student_name +",","\nYou have a",
average_score_for_course,"% in your", course_name,"course.")
for this assignment my above programming should produce output as below according to my input coding.
For example:
Enter student's name: Ryan
Enter course name: Advanced Quantum Mechanics
Enter quizzes weight: .1
Enter projects weight: .2
Enter activities weight: .3
Enter attendance weight: .1
Enter exams weight: .3
Enter quizzes average: 1
Enter projects average: .85
Enter activities average: .9
Enter attendance average: .95
Enter exams average: .87
the output should be something like this:
Hi Ryan,
You have a 89.6% in your Advanced Quantum Mechanics course.
Looking at your code:
print("Hi",student_name +",","\nYou have a",
average_score_for_course,"% in your", course_name,"course.")
When you use a comma delimiter for the print function, it adds a space by default. Replace your comma with a +:
print(average_score_for_course + "% in your")
By replacing the comma with +, it removes the space that Python adds by default.
Using Emma's solution (string formatting) is a better and more pythonic solution to your problem. Hopefully I helped you to understand why this is happening, though.
Just for a different answer:
You can try this as well
average_score_for_course = str(((quizzes_weight * quizzes_average) +
(projects_weight * projects_average) + (activities_weight *
activities_average) + (attendance_weight * attendance_average) +
(exams_weight * exams_average)) * 100)+"%"
print("Hi",student_name +",","\nYou have a",
average_score_for_course,"in your", course_name,"course.")
change the result to string and concatenate "%" to it.
print("Hi" + str(student_name) +"," + "\nYou have a" + str(average_score_for_course) +"% in your" + str(course_name) + "course.")
For me i will try to avoid using comma because it hard to visualize how your printing looks like and for safe it is better to convert "average_score_for_course" into str before printing.
You can format a string with the 3 variables you want to print:
print("Hi {},\nYou have a {}% in your {} course".format(student_name, average_score_for_course, course_name))
I am trying to get my program to limit what the user can type in. It keeps returning an "Expected an indented block" error from my code below.
deliverydetails = input("Is your order for delivery?\n Press 1 for delivery. Press 2 for pickup")
if deliverydetails == "1":
## def delivery ():
print ("Order for Delivery")
customerfirstname = " "
while len(customerfirstname) <3 or len(customerfirstname)>30 or customerfirstname.isalpha() != True:
customerfirstname = input("Customer First Name: ** must be 4 characters long + " ")
while len(customersurname) < 3 or len(customersurname) > 30 or customerfirstname.isalpha() != True:
customersurname = input("Customer Surname:" + " ")
customerstreet = input("Street name:" + " ")
customerstreetnumber = input("Street number:" + " ")
customercity = input("City:" + " ")
customersuburb = input("Suburb (If none, leave blank):" + " ")
latestOrder.append(customerfirstname)
latestOrder.append(customersurname)
latestOrder.append(customerstreet)
latestOrder.append(customerstreetnumber)
latestOrder.append(customercity)
latestOrder.append(customersuburb)
Python uses indentation to group blocks of code. After the while statements, you want to indent the lines below it that should be executed inside the while loop.
Here are some other tips that may be useful:
- Use pylint to check your syntax. It will uncover a lot of errors that you would otherwise only find out during runtime.
- Use spaces to indent. Don't use tabs. That's a PEP 8 style recommendation
Here is the corrected version of your code:
deliverydetails = input("Is your order for delivery?\n Press 1 for delivery. Press 2 for pickup")
if deliverydetails == "1":
## def delivery ():
print ("Order for Delivery")
customerfirstname = " "
customersurname = " "
while len(customerfirstname) <3 or len(customerfirstname)>30 or customerfirstname.isalpha() != True:
customerfirstname = input("Customer First Name: ** must be 4 characters long + " ")
while len(customersurname) < 3 or len(customersurname) > 30 or customerfirstname.isalpha() != True:
customersurname = input("Customer Surname:" + " ")
customerstreet = input("Street name:" + " ")
customerstreetnumber = input("Street number:" + " ")
customercity = input("City:" + " ")
customersuburb = input("Suburb (If none, leave blank):" + " ")
latestOrder.append(customerfirstname)
latestOrder.append(customersurname)
latestOrder.append(customerstreet)
latestOrder.append(customerstreetnumber)
latestOrder.append(customercity)
latestOrder.append(customersuburb)
Python uses intentation instead of {} or begin/end, so for example this line
while len(customerfirstname) <3 or len(customerfirstname)>30 or customerfirstname.isalpha() != True:
should be followed by an indented block. An indented block can be as short as a single line, usually you should indent it 4 spaces more than the while
Aside: it may be clearer to write that line as
while not (3 <= len(customerfirstname) <= 30 and customerfirstname.isalpha()):
Make sure to indent the lines that are part of the loop. That's the only way Python has to know what part you want to loop.
delivery_details = input("Is your order for delivery?\n Press 1 for delivery. Press 2 for pickup")
if delivery_details == "1":
print "Order for Delivery"
customer_first_name = ""
while len(customer_first_name) < 3 or len(customer_first_name) > 30 or not customer_first_name.isalpha():
customer_first_name = input("First name (must be 4 characters long): ")
customer_surname = input("Surname: ")
customer_street = input("Street name: ")
customer_street_number = input("Street number: ")
customer_city = input("City: ")
customer_suburb = input("Suburb (If none, leave blank): ")
latest_order.append(customer_first_name)
latest_order.append(customer_surname)
latest_order.append(customer_street)
latest_order.append(customer_street_number)
latest_order.append(customer_city)
latest_order.append(customer_suburb)
For what it's worth I've made some stylistic changes for readability. Some extra spacing, blank lines, and underscores in variable names make everything a bit easier on the eyes.