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))
Related
I am still very new to python and having trouble with this code. the idea is that you can input a persons first name, last name, age, and gender, and save it in a list. then retrieve all the data about a person just by entering their first name. I have tried a couple of different things like using the collection library but nothing has worked so far. any help would be great.
code:
person =[]
cl = input(": ")
if cl == "new.person":
newpersonfname = input("first name: ")
newpersonlname = input("last name: ")
newpersonage = str(int(input("age: ")))
newpersongen = str(input("first letter of gender(f, m, nb, o): "))
value = "{", newpersonfname, newpersonlname, newpersonage, newpersongen, "}"
person.extend(value)
print("successfuly added")
if cl == "retrieve.person.by.name":
RPBN = str(input("name(first): "))
#???
Use a dictionary like so:
person = {}
cl = input(": ")
if cl == "new.person":
newpersonfname = input("first name: ")
newpersonlname = input("last name: ")
newpersonage = str(int(input("age: ")))
newpersongen = str(input("first letter of gender(f, m, nb, o): "))
person['newpersonfname'] = {'newpersonlname':newpersonlname, 'newpersonage':newpersonage,'newpersongen':newpersongen}
print("successfuly added")
if cl == "retrieve.person.by.name":
RPBN = str(input("name(first): "))
print(person[RPBN])
In addition to #aaossa comment. If you are asked to do it only with a list. You can take a input for the first name from the user, equate it to the List[1] and if it matches, display the rest of the contents of the list. I do however recommed using Dictonary for such tasks.
person = {}
cl = input(": ")
if cl == "new.person":
newpersonfname = input("first name: ")
newpersonlname = input("last name: ")
newpersonage = str(int(input("age: ")))
newpersongen = str(input("first letter of gender(f, m, nb, o): "))
value = "{", newpersonfname, newpersonlname, newpersonage, newpersongen, "}"
person.extend(value)
print("successfuly added")
if cl == "retrieve.person.by.name":
RPBN = str(input("name(first): "))
if value[1].equals(RPBN):
for i=2; i<len(value)-1; i++ :
print(value[i]);
I'm new to coding/Python so any help is greatly appreciated. I'm trying to figure out how to calculate sales tax r but I can't figure out how to do is.
import math
class userEntry:
userName = input("Enter Customer Name: ")
userQuantityPurchased = int(input("Enter Quantity Purchased: "))
userPrice = int(input("Enter Price per Unit: "))
class taxCalculator:
stateTax = .09
salesAmount = float(str(userEntry.userQuantityPurchased*userEntry.userPrice))
stateCalculator = str(salesAmount*stateTax)
class programOutput:
print("------------------------------")
print("Here is your Net Sale!")
print("------------------------------")
print("Customer Name: " + userEntry.userName)
print("Sales Amount: " + taxCalculator.salesAmount)
print("State Tax: " + taxCalculator.stateTax)
You'd need to convert the float to str:
print("Sales Amount: " + str(taxCalculator.salesAmount))
But actually, it's easier to have print do it for you, along with the joining:
print("Customer Name:", userEntry.userName)
print("Sales Amount:", taxCalculator.salesAmount)
print("State Tax:", taxCalculator.stateTax)
P.S. This usage of classes is highly non-idiomatic, and I would recommend avoiding it unless it's required for a class or something. And there are other problems with your code I won't go into.
I am guessing you are coming from a java/C background and can answer your question. You are trying to concatenate a str type with a float. Also the making sales amount a str first and then a float is redundant and importing the math library here is not needed. I made you an example class with some common naming conventions that follow the 'Zen of Python' and the PEP 8 guidelines.
class SalesTax:
def __init__(self):
# class variables
self.user_name = None
self.user_quantity_purchased = None
self.user_price = None
self.state_tax = None
self.sales_amount = None
self.calculated_state = None
def ask_user(self):
self.user_name = input("Enter Customer Name: ")
self.user_quantity_purchased = int(input("Enter Quantity Purchased: "))
self.user_price = int(input("Enter Price per Unit: "))
def calculate_tax(self, state_tax: float):
self.state_tax = state_tax
self.sales_amount = float(self.user_quantity_purchased * self.user_price) *
(1 + self.state_tax)
def print_result(self):
print("------------------------------")
print("Here is your Net Sale!")
print("------------------------------")
print("Customer Name: " + self.user_name)
print("Sales Amount: " + str(self.sales_amount))
print("State Tax: " + str(self.state_tax))
example = SalesTax()
example.ask_user()
example.calculate_tax(0.09)
example.print_result()
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."
Filename=open('StudentBio.txt','w')
Name=1
fathername=1
Nationality=1
religion=1
if Name==1 and fathername==0 and Nationality==1 and religion==1:
print('You are Eligible for Admission\nCongratualation')
else:
print('Tick All The Above boxes That You Have To fill')
def StudentBiography(Name,fathername,Nationality,religion):
Name=input('Enter Name Of student : ')
fathername=input('Enter Name Of father : ')
Nationality=input('Enter Nationality :')
religion=input('Enter Religion : ')
all_info=[Name,fathername,Nationality,religion]
return all_info
def Grading(Maths,Islamiat,English):
A=Maths+Islamiat+English
B=(A/300)*100
C=[Maths,Islamiat,English]
return (B,C)
for i in range(2):
a=StudentBiography(Name,fathername,Nationality,religion)
f=str(a)
Filename.write(f)
for j in range(2):
Maths = eval(input('Enter no : '))
Islamiat = eval(input('Enter no : '))
English = eval(input('Enter no : '))
b=Grading(Maths,Islamiat,English)
g=str(b)
Filename.write(g)
Filename.close()
please Help me I need Serious Help
From what I can understand you would like to write student information to a text file. First of all, I think you should read more about Python syntax and work on your scripting. For example in Python variables and functions should start with lowercase letters and you need spaces around = sign and things like that. I will try my best to help you out.
def get_student_bio():
name = input('Enter Name Of student : ')
father_name = input('Enter Name Of father : ')
nationality = input('Enter Nationality :')
religion = input('Enter Religion : ')
return ' '.join([name, father_name, nationality, religion])
def get_student_grade():
math = input('Enter no : ')
islamiat = input('Enter no : ')
english = input('Enter no : ')
avg = str(sum(float(math) + float(islamiat) + float(english)) / 3)
return ' '.join([avg, math, islamiat, english])
fileobj = open('StudentBio.txt','w')
for i in range(2):
bio = get_student_bio()
grades = get_student_grades()
fileobj.write(bio + ' ' + grades + '\n')
fileobj.close()
I assume you are trying to enter student bio and grades one by one and write them in a text file. Here is one way you can achieve this. I tried to keep it similar to the way you were doing it so maybe it's easier to understand. I got rid of the initial if statement though because I wasn't sure what you were trying to achieve with that. Anyways, hope this is useful.
I'm trying to make a few scripts of my own to practice what I'm learning. But I'm coming up with some issues on the following script.
#!/usr/bin/python
def empInfoEntry():
firstName = input("Enter Employee's First Name: ")
lastName = input("Enter Employee's Last Name: ")
address = input("Enter Employee's Address: ")
city = input("Enter Employee's City: ")
state = input("Enter Employee's Complete State: ")
zip = input("Enter Employee's Zip Code: ")
def empInfo():
empFirstName = empInfoEntry.firstName
empLastName = empInfoEntry.lastName
print (empFirstName + " " + empLastName)
empAddress = empInfoEntry.address
print (empAddress)
empCity = empInfoEntry.city
empState = empInfoEntry.state
empZip = empInfoEntry.zip
print (empCity + ", " + empState + " " + empZip)
empInfoEntry()
empInfo()
According to the error "unhandled AttributeError "'function; object has no attribute 'firstName'"
I've looked it up but most of the results I find are quite complex and confusing to grasp my issue here.
I know that when this script runs it starts with empInfoEntry()
It works since I can type all the info in.
however, empInfo() seems to give me that function error. I have tried also using a simple print (firstName) although I know that it's outside of the function. Even when I append it to print (empInfoEntry.firstName) it gives me an error.
I can imagine it's because there is no return but i'm still a bit confused about returns as simple as people claim.
Any eli5 responses would be appreciated but a full explanation will work as well.
Thanks.
Also using python 3.4 and eric 6 on windows 8
Firstly, try to use raw_input() instead of input().
According to the official documentation, input() is actually eval(raw_input()). You might want to know what is eval(), check the documentation, we do not discuss it here. Sorry I thought it was Python 2.
As it seems you are not far from start learning Python, I would not write a class for you. Just using functions and basic data structures.
If you are interested, check pep8 for the naming convention in Python.
#!/usr/bin/python
def enter_employee_info_and_print():
# use a dictionary to store the information
employee_info = {}
employee_info['first_name'] = input("Enter Employee's First Name: ")
employee_info['last_name'] = input("Enter Employee's Last Name: ")
employee_info['address'] = input("Enter Employee's Address: ")
employee_info['city'] = input("Enter Employee's City: ")
employee_info['state'] = input("Enter Employee's Complete State: ")
employee_info['zip'] = input("Enter Employee's Zip Code: ")
first_name = employee_info['first_name']
last_name = employee_info['last_name']
# pay attention that there is no space between `print` and `(`
print(first_name + " " + last_name)
address = employee_info['address']
print(address)
city = employee_info['city']
state = employee_info['state']
zip = employee_info['zip']
print(city + ", " + state + " " + zip)
# use this statement to run a main function when you are directly running the script.
if __name__ == '__main__':
enter_employee_info_and_print()
Try this. I think this is the sort of thing your'e looking for.
class InfoEntry(object):
def __init__(self):
self.first_name = input("Enter your first name:")
self.last_name = input("Enter your last name:")
def __str__(self):
return self.first_name + " " + self.last_name
me = InfoEntry()
print(me)
Although functions can have attributes, when you want something to hold information, the format of which you know a priori, the thing you want is a class