I have to use the append method to get info from the user however I am only suppose to take 10 lines from the user and not suppose to ask them if they have another set of information to enter. Can anyone tell me how to stop a list_append without asking the user to stop it?
The following is my code in python.
#set limit
num_grades = 10
def main():
#making of the list
grades = [0] * num_grades
#hold the index
index = 0
#ask the user for the info
print('Please enter the final grades for 10 students: ')
#put the info into the list with a loop
while index < num_grades:
grade = input('Enter a grade: ')
grades.append(grade)
main()
Your given code is missing only one thing: you forgot to increment the index each time through the loop.
Do this better with a for loop:
for index in range(num_grades):
grade = input('Enter a grade: ')
grades.append(grade)
Your issue is that you are forgetting to increment index inside the while loop you have created, and hence it is always zero.
Just adding a index += 1 line inside the loop will fix your issue.
As stated by #Prune, a for loop would be much more suitable in this situation.
This kind of thing is easily handled by for loops. Here is your code edited:
num_grades = 10
def main():
#making of the list
grades = []
#ask the user for the info
print('Please enter the final grades for 10 students: ')
#put the info into the list with a loop
for i in range(num_grades):
grade = input('Enter a grade: ')
grades.append(grade)
main()
As #Wintro has mentioned, the issue was that you forgot to increment the index inside the while loop.
So the working solution looks as follows:
num_grades = 10
def main():
#making of the list
grades = [0] * num_grades
#hold the index
index = 0
#ask the user for the info
print('Please enter the final grades for 10 students: ')
#put the info into the list with a loop
while index < num_grades:
grade = input('Enter a grade: ')
grades.append(grade)
index += 1
main()
Related
i just started programming in Python and i'm trying to do a program that prints names n times through a while loop, the condition is when the user input yes the program keeps adding n names to a list, if the users inputs something else it simply prints all the elements added in the list
eg: list_input = "Enrique"
count = 3 #Times
lista = ['Enrique', 'Enrique', 'Enrique']
def nameTries():
list_input = input("Enter the name:")
lista = []
count = int(input("How many times you want to repeat it?"))
lista.append(f'{list_input * count}')
confirm = input("Wanna add more? yes/no")
while confirm == "yes":
list_input = input("Enter the name:")
count = int(input("How many times you want to repeat it?"))
lista.append(f'{list_input * count}')
confirm = input("Wanna add more? yes/no")
if confirm != "yes":
print(lista)
break
else:
print(lista)
the problem is it's adding ONLY in an element of the list like this:
>>>['EnriqueEnriqueEnrique']
how can i solve this? Thanks in advance.
the append method only adds 1 element to a list. If you want to add several elements at once, you must concatenate, which is done with the + operator.
Also, your looping procedure is not very "sexy" because the instructions are the same two times. You could do it better like this :
def nameTries():
lista = []
while True:
list_input = input('Enter the name: ')
count = int(input('How many times you want to repeat it? '))
lista += [list_input] * count
confirm = input('Wanna add more? (y/n): ')
if confirm != 'y':
return lista
>>> nameTries()
Enter the name: Enrique
How many times you want to repeat it? 3
Wanna add more? (y/n): y
Enter the name: Pedro
How many times you want to repeat it? 5
Wanna add more? (y/n): n
['Enrique', 'Enrique', 'Enrique', 'Pedro', 'Pedro', 'Pedro', 'Pedro', 'Pedro']
I'm doing a small program that has the job of a school's subjects and marks management.
HOW IT WORKS
I've created 4 variables: a dictionary, an initialized empty string(for subjects) and two initialized empty integers(one for the marks, the other one for the subjects number). The program asks the user to input the numbers of subjects to work with. After that, it enters in a for loop that repeats itself in the range of the subjects number. And it works fine. Now the problem comes when the user inputs a mark over the range specified. Let's suppose we have a school and the marks we can input are between 1 and 10. The user can't write 11,12 and so on..
CODE
pagella = {}
materia = ""
voti = 0
length = 0
print("Insert the number of subjects, the subjects and the marks-")
num = int(input("Number of subjects: "))
length = len(pagella)
length = num
for i in range(length):
materia = input("Subject: ")
voto = eval(input("Mark: "))
if(voto > 10):
print("Number between 1 and 10")
else:
pagella[materia] = voto
print(pagella)
As you can see, there's the for loop that asks the user to input the subjects and the marks in the range of num(the number of subjects). If I try to input 12 on a mark, the program tells me to input a mark between 1 and 10 so it repeat again the cycle from the beginning. But the problem is that in this case, if I want to have 3 subjects with 3 marks (that means 3 iterations), one is lost because of the wrong mark, so I will not have 3 subjects and marks to input correctly, but only 2.
I hope I've explained correctly everything and someone can help me!
Thanks in advice
I suggest you the following solution that handles also the cases of non-numeric values as input for marks:
pagella = {}
materia = ""
length = 0
print("Insert the number of subjects, the subjects and the marks-")
num = int(input("Number of subjects: "))
length = num
for i in range(num):
# Ask for subject
materia = input("Subject: ")
# Ask for mark until the input is correct
voto = None
while (voto is None):
try:
voto = int(input("Mark: "))
if (voto > 10):
print("Number between 1 and 10")
voto = None
except:
print("Pleaser enter an integer")
# Store in dictionary pagella (if mark is correct)
pagella[materia] = voto
print(pagella)
This is the output of the code I am trying to write. I have seen this done for C++, but not python with a dictionary. The key here is the dictionary is not optional. I need to use it to fulfill the assignment.
ID Candidate Votes Received % of Total Vote
1 Johnson 5000 55.55
2 Miller 4000 44.44
Total 9000
and the winner is Johnson!
I need to use a dictionary and a loop to create this. However, I am stuck on 3 points.
1.The percent- current code returns the percent before it has the whole total ex: first candidate always has 100%.
2. Declare a winner- code finds the max votes and returns the number value but I need it to return the name.
3. How to format the dictionary values so it lines up under the header. I don't think is possible, but it must be a requirement to use a dictionary for a reason. I am thinking I need to make a copy of the dictionary and format that?
Here is what I have so far:
totalVotes=[]
dct = {}
i = 1
while(True):
name = input('Please enter a name: ')
if name == '':
break
votes = input('Please enter vote total for canidate: ')
totalVotes.append(votes)
totalVotesInt= map(int, totalVotes)
total = sum(totalVotesInt)
dct[i] = {name,votes,int(votes)/total*100}
i += 1
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(header)
print("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+max(totalVotes))
Which returns:
Please enter a name: Smith
Please enter vote total for canidate: 100
Please enter a name: Frieda
Please enter vote total for canidate: 200
Please enter a name: West
Please enter vote total for canidate: 10
Please enter a name:
ID Name Votes % of Total Vote
1 {'Smith', '100', 100.0}
2 {'Frieda', 66.66666666666666, '200'}
3 {3.225806451612903, '10', 'West'}
Total 310
The Winner of the Election is 200
You add the number of each candidates votes at the same time you calculate the percent vote for each candidate. You need to find the total votes first, then divide each candidates votes by the total
You are returning the max of a list of integers. Obviously you aren't going to get a string. You need some way to connect the number votes with the candidate.
Don't bother. You can try to figure out how many tabs you need to get the whole thing lined up, but from experience, it is basically impossible. You could separate them with commas and open it in excel as a csv, or you could just make the user figure out what number goes with what.
The other answer uses data tables, so I will take another, more vanilla and cool approach to getting what you want.
class candidate():
def __init__(self, name, votes):
self.name = name
self.votes = int(votes)
def percentvotes(self, total):
self.percent = self.votes/total
def printself(self, i):
print('{}\t{}\t\t{}\t\t{}'.format(i, self.name, self.votes, self.percent))
def getinput():
inp = input('Please enter your candidates name and votes')
return inp
candidates = []
inp = getinput()
s = 0
while inp != '':
s+=1
candidates.append(candidate(*inp.split(" ")))
inp = getinput()
for c in candidates:
c.percentvotes(s)
candidates.sort(key = lambda x:-x.percent)
print('ID\tname\t\tvotes\t\tpercentage')
for i, c in enumerate(candidates):
c.printself(i+1)
I have added very little changes to your code to make it work:
I have mentioned the changes as comments in the code.
Edit: It's more efficient to use objects for each candidate if you require scaling in the future.
totalVotes=[]
dct = {}
i = 1
while(True):
name = input('Please enter a name: ')
if name == '':
break
votes = input('Please enter vote total for canidate: ')
totalVotes.append(votes)
totalVotesInt= map(int, totalVotes)
total = sum(totalVotesInt)
# I change it to a list so it's much easier to append to it later
dct[i] = list((name,int(votes)))
i += 1
# I calculate the total percent of votes in the end and append to the candidate
maxVal = 0
for i in range(1, len(dct) + 1):
if dct[i][1] > maxVal:
maxInd = i
dct[i].append(int((dct[i][len(dct[i]) - 1]) / total * 100))
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(dct)
print(header)
print("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+ dct[maxInd][0]))
I believe that this is the solution you are looking for. Just change the input statements in case you are using Python 2.x. Using Dataframe, the output will be exactly how you wanted.
import pandas as pd
import numpy as np
df = pd.DataFrame(columns=["Candidate", "Votes Received","Percentage of total votes"])
names=list()
votes=list()
while True:
name = str(input("Enter Name of Candidate."))
if name=='':
break
else:
vote = int(input("Enter the number of votes obtained."))
names.append(name)
votes.append(vote)
s=sum(votes)
xx=(votes.index(max(votes)))
myArray = np.array(votes)
percent = myArray/s*100
for i in range(len(names)):
df1 = pd.DataFrame(data=[[names[i],votes[i],percent[i]]],columns=["Candidate", "Votes Received","Percentage of total votes"])
df = pd.concat([df,df1], axis=0)
df.index = range(len(df.index))
print (df)
print ("Total votes = ",s)
print ("The man who won is ",names[xx])
I need to ask the final grade of 10 students (while) incrementing their values:
So something like:
Please enter final grade for student 1
Please enter final grade for student 2
and so on... till 10
Then I need to get the grades they entered, and find average.
This is what I have so far:
def main():
x = []
for i in range(10):
final_grades = x.append(int(input('Please enter final grade for student: ')))
##average_final_grade = final_grades / 10
##print(average_final_grade)
main()
# list of grades
x = []
# count of students
n = 10
# fill list with grades from console input
# using pythonic generator
x = [int(input('Please enter final grade for student {}: '.format(i+1))) for i in range(n)]
# count average,
# sum is builtin way to sum values in list
# float required for python 2.x to make avg float, not int
average_final_grade = sum(x) / float(n)
print('Avg grade is {}'.format(average_final_grade))
Online demo.
First, you need to get the values, as you have already done:
x = []
for i in range(10):
x.append(int(input('Please enter final grade for student: ')))
Now you need to sum the values of x:
total_sum = sum(x)
Then, you get the average:
average_final_grade = total_sum/len(sum)
total=sum(x)
average=total/10
print(average)
tack this at the bottom and it should work
This question already has answers here:
Python: raw_input and unsupported operand type(s)
(3 answers)
Closed 7 years ago.
I am trying to ask the user to enter any number and then ask the user to enter any names, then store this input in a list.
However, when I enter any number, it asks to enter name only one time and shows the output in list:
def main():
# a = 4
a = input("Enter number of players: ")
tmplist = []
i = 1
for i in a:
pl = input("Enter name: " )
tmplist.append(pl)
print(tmplist)
if __name__== "__main__":
main()
output:
Enter number of players: 5
Enter name: Tess
['Tess']
The for loop should run 5 times and user entered 5 values get stored in a list.
You need to convert the number of players to integer and then loop for that much amount of times, you can use the range() function for this . Example -
def main():
num=int(input("Enter number of players: "))
tmplist=[]
for _ in range(num):
pl=input("Enter name: " )
tmplist.append(pl)
print(tmplist)
Since you are using Python3
a=input("Enter number of players: ")
means a is a string "5". Since this is only one character long - the loop will run just once
You need to use
a = int(input("Enter number of players: "))
You'll also need to change the loop
for i in range(a):
I recommend using more meaningful variable names - especially if this is homework
def main():
number_of_players = int(input("Enter number of players: "))
player_list = []
for i in range(number_of_players):
player = input("Enter name: " )
player_list.append(player)
print(player_listlist)
if __name__== "__main__":
main()
You got a string a which presumably contained something like '5'. Then you initialize a counter i. Then you loop through this string, which, since it's '5', resulted in one iteration, because there's only one character in '5'.
First you have to change it into a number, with a = int(a).
With a as a number, you still can't loop through that, because a number isn't an iterable.
So then you should create a range object to loop over, with for i in range(a):.
Then you will be able to carry out your operations as expected.
Since the input a is a string
you need to convert it to a number and then use a different for.
it should be
def main():
#a=4
a=int(input("Enter number of players: "))
tmplist=[]
i=0
while i < a:
pl=input("Enter name: ")
tmplist.append(pl)
i+=1
print(tmplist)
main()