I'm a beginner at python and wanted to have a crack at my first personal project which is a score calculator for a student's subjects. I wanted to run a for loop that asks the user to input their scores for each of the individual subjects through an input() within a for loop. However, it would only take a singular string argument.
scores = {}
total = 0
years = int(input("How subjects have you completed? "))
for sub in range(0, years):
scores = input("Score for subject?",x)
total += int(scores)
Any help would be great, thanks!
If you wanted to keep track of scores by subject and find total score then...
subjects = dict( Math = 0, English = 0, Science = 0, History = 0 )
scores = dict()
total = 0
for sub in subjects.keys():
score = input( f"Score for {sub}? >" )
if score:
total += int( score )
scores[sub] = score
print( total )
for sub,tot in scores.items():
if tot > 0:
print( sub, tot )
The variable x never defined and used, just remove it may solve your problem.
scores first defined as a dict, then you re-define it without using it.Remove it make code more clear.
code:
total = 0
years = int(input("How subjects have you completed? "))
for sub in range(years):
scores = input("Score for subject?")
total += int(scores)
print(total)
result:
How subjects have you completed? 5
Score for subject?1
Score for subject?2
Score for subject?3
Score for subject?4
Score for subject?5
15
In the code sample:
x is an undefined variable.
scores = {} the 'scores' dictionary is useless as later you redefine it as a string.
Just removing the ,x in line 5 will make the code execute properly.
>>> total = 0
>>> for i in range(int(input("How many subjects have you completed? "))):
... total += int(input("Score for subject? "))
...
How many subjects have you completed? 3
Score for subject? 70
Score for subject? 80
Score for subject? 90
>>> total
240
Related
def sum_digits(user_input):
total = 0
for c in user_input:
if c.isdigit():
total += int(c)
print(total)
The problem I'm having is that when lets say the user enters car888 the program will output (8, 16 and 24)
But all I want it to output is the sum of the numbers so just 24.
I think your print is simply place in the wrong position. You currently have it nested under the if statement and so it will return each individual iteration.
Try this:
def sum_digits(user_input):
total = 0
for c in user_input:
if c.isdigit():
total += int(c)
print(total)
I have run this code and changed it more times than I can count but it always results in a loop. I'm not quite sure what I've done wrong nor how to end the loop.
"""
WeeklyPay.py: generate payroll stubs for all hourly paid employees and summarizes them
"""
def main():
"""
total_gross_pay = 0
hours_worked = 0
gross_pay = 0
hourly_rate= 0
:return: None
"""
employee = input("Did the employee work this week? Y or y for yes: ")
while employee == "Y" or "y":
hours_worked = int(input("How many hours did the employee work this week? "))
hourly_rate = int(input("What is the employee's hourly rate? "))
gross_pay = hours_worked * hourly_rate
print("Your weekly pay is: "+ gross_pay)
main()
You might find the while loop shown below works more like what your program should do:
def main():
"""Help the user calculate the weekly pay of an employee."""
while input('Did the employee work this week? ') in {'Y', 'y'}:
hours_worked = int(input('How many hours? '))
hourly_rate = int(input('At what hourly rate? '))
gross_pay = hours_worked * hourly_rate
print('The weekly pay is:', gross_pay)
if __name__ == '__main__':
main()
You are using a while loop, in which the variable employee is never changed, so the condition stays True. It should work if you replace the while with an if.
I have a homework that tells this:
A hawker has to decide what products to take on his next trip. Unfortunately, you have a weight limit that you can carry, and having this in mind, you have to choose the best combination of products with at most this weight that will allow you to have maximum revenue.
You will receive the weight limit that the seller can carry, followed by a list of products from which he can choose (assume you have an unlimited stock of each product at your disposal). For each product will be listed its name, its value, and its weight. You should print the maximum revenue you can get if you sell all the products you choose to carry, followed by the list of products you should take to get that revenue (including replicates, if appropriate), sorted alphabetically. If there are 2 products with the same profitability / weight should give priority to the products that appear first in the entry list.
I am reading the input from a file.
Input:
14
bible 20 2
microwave 150 10
television 200 15
toaster 40 3
Output: 190 bible bible microwave
I have made this code to reach the maximum value the hawker can carry with him:
import sys
def knapsack(list_values,list_weight,limit_weight,n):
matrix = [[0 for x in range(limit_weight+1)] for y in range (n+1)]
res = []
for i in range(n+1):
for j in range(limit_weight+1):
if i == 0 or j == 0:
matrix[i][j] = 0
elif list_weight[i-1]<= j:
matrix[i][j] = max(list_values[i-1] + matrix[i-1][j-list_weight[i-1]], matrix[i-1][j])
else:
matrix[i][j] = matrix[i-1][j]
return matrix[n][limit_weight], matrix
def main():
txt = sys.stdin.readlines()
limit_weight = int(txt[0])
list_names = []
list_values = []
list_weight = []
picked = []
for lines in txt[1:]:
lines = lines.split()
list_weight.append(int(lines[2]))
list_values.append(int(lines[1]))
list_names.append(lines[0])
result, matrix = knapsack(list_values,list_weight, limit_weight, len(list_values))
print(result)
main()
I can not figure out which items are chosen.
Can you help me?
How does one answer this question.
1. A dramatic society wants to record the number of tickets sold for each of their four performances. Ask the user to enter the number of tickets sold for each performance. The number must be between 0 and 120. Print an error message if an invalid number is entered and ask them to re-enter until they enter a valid number. Print the total number of tickets sold and the average attendance for a performance.
import re
affirm = False
p = 0
total = 0
for p in range(4):
p = input("Please enter the total number of tickets sold for the performance.")
while affirm != True:
try:
int(p)
except ValueError:
print("This is not a number")
else:
valid = re.match("[0-120]",p)
if valid:
total += p
affirm = True
else:
p = input("Please enter the total number of tickets sold for the performance.")
average = (total/480) * 100
average = round(average,2)
print("""
The total number of tickets sold is: """,total"""
The average attendance is : """,average)
My python book didn't really explain the correct syntax for the re module and the try except else function. Can someone point out if there is anything wrong with the code. This was my first go at validating user input.
You cannot use regular expression to see whether a number is between a certain range, and even if you did, it would be silly considering how easy it is to check if a number is between numbers in Python:
valid = 0 < p < 120
Here is your code after the fix:
affirm = False
p = 0
total = 0
for p in range(4):
p = input("Please enter the total number of tickets sold for the performance.")
while affirm != True:
try:
int(p)
except ValueError:
print("This is not a number")
else:
valid = 0 < p < 120
if valid:
total += p
affirm = True
else:
p = input("Please enter the total number of tickets sold for the performance.")
average = (total/480) * 100
average = round(average,2)
print("""
The total number of tickets sold is: """,total"""
The average attendance is : """, average)
More on: Expressions in Python 3
Trying to return to data question is user enters incorrect number.
I need need to know how to return to the question again if incorrect number is entered
import math
p=float(input('Please enter the price of the phone: '))
print('')
data=int(input('Enter the amount of the data you will use, 1 gig, 3 gigs, 6 gigs: '))
tax=p*.0925
Total=p+tax
print('')
print ('If your phone cost',p,',the after tax total in Tennessee is',round(Total,2))
print('')
if data==1:
datap=30
print('The price of one gig is $30.')
elif data==3:
datap=45
print('The price of three gig is $45.')
elif data==6:
datap=60
print('The price of six gigs is $60.')
else:
print(data, 'Is not an option.')
#I need need to know how to return to the question again if incorrect number is entered
pmt=Total/24
bill=(datap+20)*1.13
total_bill=bill+pmt
print('')
print('With the phone payments over 24 months of $',round(pmt,2),'and data at $',datap,
'a month and line access of $20. Your total cost after tax is $',round(total_bill,2))
You should enter an infinite loop and only break out of it when the user has entered a valid input.
import math
costmap = {1: 30, 3: 45, 6: 60}
price = float(input('Please enter the price of the phone: '))
datamsg = 'Enter the amount of the data you will use, 1 gig, 3 gigs, 6 gigs: '
while True:
try:
data = int(input(datamsg))
except ValueError:
print('must input a number')
continue
tax = price * .0925
total = price + tax
print('If your phone cost {}, the after tax total in Tennessee is {}'
.format(price, round(total, 2)))
try:
datap = costmap[data]
print('The price of one gig is ${}.'.format(datap))
break
except KeyError:
print('{} is not an option try again.'.format(data))
pmt = total / 24
bill = (datap + 20) * 1.13
total_bill = bill + pmt
print('With the phone payments over 24 months of ${}'.format(round(pmt, 2)))
print('and data at ${} a month and line access of $20.'.format(datap))
print('Your total cost after tax is ${}'.format(round(total_bill, 2)))
You can also simplify your if/else clause by defining a dict to map inputs to cost values. If the value does not exist it throws an exception which you can catch, issue an error and go around the loop again.
Finally I'd recommend you try running your code through a pep-8 checker such as http://pep8online.com/. It will teach you how to format your code to make it easier to read. At present your code is more difficult to read than it could be.