Having trouble with a List-loop - python

Basically, you input the names and they are saved to the list. Say I input "a, b, c, d and e. After printing the list it comes out with "a, a, a, a, and a"
Then, when it asks if the student has paid or not, it doesn't matter what value you input, the name won't be moved to the designated list.
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name == raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
print "List full"
print name_list
paid_list = []
unpaid_list = []
for names in name_list:
print "Has " + name + " paid? Input y or n: "
input == raw_input()
if input == "y":
paid_list.append[input]
name_list.next
elif input == "n":
unpaid_list.append[input]
name_list.next
print "The students who have paid are", paid_list
print "The students who have not paid are", unpaid_list

Your populating loop is:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name == raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
You first assign the value received through raw_input to name.
Then, for count from 0 to 4, you check if name is equal to the input, and then, append it to name_list.
Instead of checking the equality by writing name == raw_input(...), what you want is to assign the input value into name.
Therefore, you mustn't use ==, but =.
Your loop should be:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name = raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
Now here is a more Pythonic way:
names_list = [] # there are more than one name in the list
for _ in range(5): # the loop index is not needed, so I use the anonymous underscore
name = raw_input("Enter the student's name: ")
names_list.append(name)

you can try:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5:
name = raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
print "List full"
print name_list
paid_list = []
unpaid_list = []
for names in name_list:
print "Has " + names + " paid? Input y or n: "
input = raw_input()
if input == "y":
paid_list.append[input]
elif input == "n":
unpaid_list.append[input]
Note: raw_input() is not there in python 3.x. Instead use: input() (documentation).

Related

How to track scores of list items if each item is unknown (it is users input)

I try to create a simple program for tracking students scores. This is my code, but I have no idea how to track students scores. Almost of the students are unknown and will always be different.
I am trying to detect wether the students' score is equal to 10.
name_list = []
enter_name = True
while enter_name:
name = input("Name: ")
name_list.append(name)
if name == "end":
enter_name = False
name_list = name_list[:-1]
#score = 0
#for word in name_list:
#score = int(input(f"{word} = {score}"))
#I am not sure about the last part, i think i turned to wrong direction
You should be using a dictionary keyed on student name. Values should be the student's score as an integer (because you want to compare against a constant value of 10).
As you're going to want integer input from the user, you'll need to validate it in order to avoid unwanted exceptions.
Consider this:
DB = {}
while (name := input('Enter student name: ')) != 'end':
while True:
try:
DB[name] = int(input(f'Enter score for {name}: '))
break
except ValueError:
print('Score should be an integer')
for k, v in DB.items():
print(f'{k} {"Genius" if v >= 10 else v}')
Sample:
Enter student name: Fred
Enter score for Fred: abc
Score should be an integer
Enter score for Fred: 10
Enter student name: Mick
Enter score for Mick: 5
Enter student name: end
Fred Genius
Mick 5
You should use a python dictionary:
students_scores = {}
while True:
name = input("Name: ")
if name == "end":
break
score = int(input("Score: "))
students_scores[name] = score
If you want to know whether a student has a score of 10, you can use if students_scores[student] == 10:.

How to randomly generate numbers each time the program is run and store those values in a list?

I am writing a program that asks the user to input a list of students. Once the list is made the user can input a student's name that was listed before to show 4 random integers from 1 to 100 that represent 4 different marks on assignments. When I run this program, however, the mark is the same number each time. How do I run the program so that each number for the mark is different, also how can I store these values in a separate list? Thank You!
def printMark(studentMark, studentName):
print("Enter the names of your students")
print("Press the enter key to store another name. print q or Q when you're done.")
names = input("Enter student name: \n")
classlist = []
while True:
names = input("")
if str.lower(names) == 'q':
break
classlist.append(names)
for name in classlist:
print(name)
student_choice = input("Enter a students in your classlist: ")
if student_choice not in classlist:
print("That students is not in your class")
elif student_choice in classlist:
mark = list(range(1, 101))
print("A1:" + str(studentMark) + "\nA2:" + str(studentMark) + "\nA3:" + str(studentMark) + "\nA4:" + str(studentMark))
classlist = []
import random
mark = list(range(1, 101))
printMark(random.sample(mark, k=4), classlist)
It seems like the error is in print("A1:" + str(studentMark) + "\nA2:" + str(studentMark) + "\nA3:" + str(studentMark) + "\nA4:" + str(studentMark)).
If studentMark is a list, which is what I gather from my last moment research on random.sample, it seems like the problem is that you are using the same value each time rather than different list elements from studentMark. (Note that I'm assuming the random.sample technique would work like mark = [random.randint(1, 101) for _ in range(4)], but without repeated values.)
Instead maybe use:
print("A1:" + str(studentMark[0]) + "\nA2:" + str(studentMark[1]) + "\nA3:" + str(studentMark[2]) + "\nA4:" + str(studentMark[3]))
You could also use:
print(*[f"A{i+1}: {mark}" for i, mark in enumerate(studentMark)])
This would simplify things but is more complicated than the original idea.
Your printMark function shouldn't take a studentMark argument if the intent is for it to generate a different set of marks each time. It also shouldn't take a studentName argument since it doesn't use it. You could very easily write this script without any functions at all, and it'd be more straightfoward:
import random
print("Enter the names of your students")
print("Press the enter key to store another name. print q or Q when you're done.")
classlist = []
while True:
names = input()
if str.lower(names) == 'q':
break
classlist.append(names)
print(*classlist, sep='\n')
student_choice = input("Enter a students in your classlist: ")
if student_choice not in classlist:
print("That student is not in your class")
else:
for a in range(1, 5):
print(f"A{a}:", random.sample(range(1, 101), k=4))
If you were going to use functions in this script, I'd suggest having one function to enter the class list and another to print a chosen set of marks given a class list:
import random
def get_class_list() -> list[str]:
print("Enter the names of your students")
print(
"Press the enter key to store another name. "
"Enter q or Q when you're done."
)
classlist = []
while True:
name = input()
if str.lower(name) == 'q':
return classlist
classlist.append(name)
def print_mark(classlist: list[str]) -> None:
student_choice = input("Enter a student in your classlist: ")
if student_choice not in classlist:
print("That student is not in your class")
return
for i in range(1, 5):
print(f"A{i}:", random.sample(range(1, 101), k=4))
print_mark(get_class_list())
Hi firstly 2 questions 1: why you put this program inside a def it just makes it more complicated 2: if the students mark are random why you are taking them as a argument to the def? any ways here is the solution i came up with
def printMark(studentName):
print("Enter the names of your students")
print("Press the enter key to store another name. print q or Q when you're done.")
names = input("Enter student name: \n")
classlist = []
while True:
names = input("")
if str.lower(names) == 'q':
break
classlist.append(names)
for name in classlist:
print(name)
student_choice = input("Enter a students in your classlist: ")
if student_choice not in classlist:
print("That students is not in your class")
elif student_choice in classlist:
mark = list(range(1, 101))
print("A1:" + str(random.sample(mark, k=4)) + "\nA2:" + str(random.sample(mark, k=4)) + "\nA3:" + str(random.sample(mark, k=4)) + "\nA4:" + str(random.sample(mark, k=4)))
classlist = []
import random
mark = list(range(1, 101))
printMark(classlist)
Here: instead of taking student marks a argument i generated them when they are printed this way it generates every time it prints one previously it was taking one random mark and using it 4 times now its all different.
Jhon, looks like your code was really close. I've made one edit:
def printMark(studentMark, studentName):
print("Enter the names of your students")
print("Press the enter key to store another name. print q or Q when you're done.")
names = input("Enter student name: \n")
classlist = []
while True:
names = input("")
if str.lower(names) == 'q':
break
classlist.append(names)
for name in classlist:
print(name)
student_choice = input("Enter a students in your classlist: ")
if student_choice not in classlist:
print("That students is not in your class")
elif student_choice in classlist:
mark = list(range(1, 101))
print("A1:" + str(studentMark[0]) + "\nA2:" + str(studentMark[1]) + "\nA3:" + str(studentMark[2]) + "\nA4:" + str(studentMark[3]))
classlist = []
import random
mark = list(range(1, 101))
printMark(random.sample(mark, k=4), classlist)
Here's a sample run:
Enter the names of your students
Press the enter key to store another name. print q or Q when you're done.
Enter student name:
a
b
c
q
b
c
Enter a students in your classlist: b
A1:7
A2:93
A3:63
A4:86
You should probably store the students in a dictionary when you want to bind their name to a list of their marks.
Here is the solution I came up with:
import random
students = {}
while True:
names = input("")
if names.lower() == 'q':
break
# this is list comprehension, you can write 4 times random.randint(1, 100) as well
students[names] = [random.randint(1, 100) for _ in range(4)]
student_choice = input("Enter a student from your list: ")
if student_choice not in students.keys():
print("This student is not in your list.")
else:
print(f"{student_choice}:\n"
f"A1: {students[student_choice][0]}\n"
f"A2: {students[student_choice][1]}\n"
f"A3: {students[student_choice][2]}\n"
f"A4: {students[student_choice][3]}")
It generates a list of 4 integers with random values every time a new user is added to the dictionary.
This means that you can access the student's marks later in the code - unlike your solution, where you only decided what the student's mark was while printing it.

create student database in python

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

Prompt user to enter names and prints out the list in python

trying to make a program that prompts user to enter a famous peoples names and continues asking until they type "done" and prints out the list with the names and the number of names. could anyone give me a little help?
def main():
cList = []
cName = []
while cName != ("done"):
cList.append(cName)
cName = input("Enter another name: ")
print("# of names entered: "), [cList]
i = 0
while i < len(cList):
print myList[i]
i += 1
return
main()
Like this?
names = []
while True:
names.append(raw_input('Enter name: '))
if names[-1] == 'done':
names.pop()
break
print("# of names %i" % len(names))
for name in names:
print(name)

Python: Ask user to enter 5 different marks

The question is Write a program that asks the user to enter 5 different students and their mark out of 100. If the user tries to enter a student twice, the program should detect this and ask them to enter a unique student name (and their mark).
my program is..
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
else:
name = raw_input("Enter a unique name: ")
mark = input("Enter the mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
print dictionary
my problem is how do you loop the else: code if the user keeps entering the same name and mark?
You mix input and raw_input, that's a bad thing. Usually you use raw_input in Python 2 and input in Python 3. The quick and dirty way to solve your problem is:
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = raw_input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
else:
print("You already used that name, enter an unique name.")
print dictionary
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
name = name.strip().lower() # store name in lower case, e.g. aamir and Aamir consider duplicate
if not dictionary.get(name):
mark = input("Enter your mark out of 100: ")
dictionary[name] = mark
count += 1
else:
print "please enter unique name"
print dictionary
Store name in lowercase so that aamir and Aamir both should be consider duplicate
the duplicate check should be performed earlier than step Enter your mark to save one step for end user
i think you only need todo this:
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
print dictionary

Categories