I am having a trouble of making a while-loop to store all inputs in the list and break the loop while it inputs "quit" and then show ALL the inputs that users have done. my codes are as followings but it only shows ["quit"] after all.
while True:
list_names = []
enter_names = input("what's the name ")
list_names.append(enter_names)
if enter_names == "quit":
break
print(list_names)
You main problem is that you need to make the list before the loop. Otherwise it will be recreated each time it loops. It's also a good habit to format the input as well.
#Need to create list before loop
list_names = []
while True:
names = str(raw_input("what's the name "))
list_names.append(names)
if names == "quit":
break
print(list_names)
Related
How I can achieve this
enter image description here
Create a List variable and append each Input in the variable. Something like that
a = []
a.append(int(input("Enter Message")))
print(a)
inputs = [] # create an empty list
while True: # loop forever
inp = input("Enter a number or...") # take user input
if inp == "": # if the user simply pressed enter the input would be empty
break # exit the loop
inputs.append(int(inp)) # add the input to the list of inputs
print(inputs) # display the current list of inputs
print("Exiting") # after the loop
Sorry ahead of time if my wording is basic, I'm a college student doing this for fun.
I'm trying to use a while loop to create a list of lists (LoL) by appending an "updating list" which clears, updates, and then appends again to the list of lists.
However, this will update the LoL and create a list that consists of the (updating list * how many times I have appended it).
This is what I mean:
fulllst = [] # List of Lists
temp = [] # Updating List
while True:
temp.clear()
while True:
item = input("Enter item: ")
if item == "done": #Ends the updating list and sends it back to be cleared.
fulllst.append(temp)
print(fulllst)
break
else:
temp.append(item)
print(fulllst)
continue
So my question is: What can I do to go around this? I need it so that I can append that same list multiple times with different values each time.
Thanks.
edit:
so, for example, I want to make 1 list of lists consisting of 3 lists with different values inside. It won't work with this code because since I appended the "updating list," whenever I clear it at the beginning of the loop, it clears the list inside the LoL. I tried to show this in this image:
Image of attempting to make three different lists.
Areas to fix in your code:
temp = [] needs to be inside the main while loop.
You are not exiting from the main while loop. Your break statement only exits from the inner while loop
See my changes to address these:
If you want multiple list of lists, you need to go back into the loop. In this case, you are not exiting the main loop at all.
fulllst = [] # List of Lists
ans = 'y'
while ans.lower().startswith('y'):
temp = [] # Updating List
while True:
item = input("Enter item: ")
if item == "done": #Ends the updating list and sends it back to be cleared.
fulllst.append(temp)
break
else:
temp.append(item)
ans = input ('do you want another list of list item [Y/N] : ')
print (fulllst)
The below will give you the following answer:
Enter item: apple
Enter item: banana
Enter item: done
do you want another list of list item [Y/N] : y
Enter item: cake
Enter item: sugar
Enter item: done
do you want another list of list item [Y/N] : n
[['apple', 'banana'], ['cake', 'sugar']]
Move temp to the inner while loop:
fulllst = [] # List of Lists
while True:
temp = [] # Updating List
while True:
item = input("Enter item: ")
if item == "done": #Ends the updating list and sends it back to be cleared.
fulllst.append(temp)
print(fulllst)
break
else:
temp.append(item)
print(fulllst)
continue
I am trying to create a multiple choice quiz using python. I have an external .txt file that has 20 questions in and I want it to select 10 random questions from that file, which it currently does. The file has the layout:
1,Who was the first man to walk on the moon?,A.Michael Jackson,B.Buzz Lightyear,C.Neil Armstrong,D.Nobody,C
The problem i'm having is that I don't want it to print the same question twice.
The only way I can think to solve this is to add detail[0], which is the question number, to a list defined in python and then check within that list to make sure that the question number isn't duplicated.
import random
qno = []
def quiz():
i = 0
global score #makes the score variable global so it can be used outside of the function
score=0 #defines the score variable as '0'
for i in range (1,11): #creates a loop that makes the program print 10 questions
quiz=open('space_quiz_test.txt').read().splitlines() #opens the file containing the questions, reads it and then splits the lines to make them seperate entities
question=random.choice(quiz)
detail = question.split(",")
print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
print(" ")
qno.append(detail[0])
print(qno)
if detail[0] in qno is False:
continue
qno.append(detail[0])
print(qno)
elif detail[0] in qno is True:
if detail[0] not in qno == True:
print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
print(" ")
qno.append(detail[0])
print(qno)
while True:
answer=input("Answer: ")
if answer.upper() not in ('A','B','C','D'):
print("Answer not valid, try again")
else:
break
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
continue
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
continue
quiz()
When I run this code I expect that no question is repeated twice but it always seems to do that, i'm struggling to think of a way to do this. Any help would be grateful, Thank you!
Use this:
questions = random.sample(quiz, 10)
It will select a random sublist of length 10, from the quiz list.
Also:
You should read the file, and make the question list outside the loop, then just loop over the questions:
with open('space_quiz_test.txt') as f:
quiz = f.readlines()
questions = random.sample(quiz, 10)
for question in questions:
...
Read all the questions:
with open('space_quiz_test.txt') as f:
quiz = f.readlines()
Shuffle the list of questions in place:
random.shuffle(quiz)
Loop on the shuffled list:
for question in quiz:
print(question)
This is because random.choice can give the same output more than once. Instead of using random.choice try
random.shuffle(list) and then choosing the first 10 records from the shuffled list.
quiz=open('space_quiz_test.txt').read().splitlines()
random.shuffle(quiz)
for question in quiz[1:11]:
detail = question.split(",")
print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
You can accomplish this by drawing the questions all at once with choice without replacement, then iterating over those.
import numpy as np
quiz=open('space_quiz_test.txt').read().splitlines() #opens the file containing the questions, reads it and then splits the lines to make them seperate entities
questions=np.random.choice(quiz, size=10, replace=False)
for question in quesions: #creates a loop that makes the program print 10 questions
#rest of your code
Instead of opening the file 10 times, get 10 questions from it and loop asking them:
def get_questions(fn, number):
with open(fn) as f:
# remove empty lines and string the \n from it - else you get
# A\n as last split-value - and your comparisons wont work
# because A\n != A
q = [x.strip() for x in f.readlines() if x.strip()]
random.shuffle(q)
return q[:number]
def quiz():
i = 0
global score # makes the score variable global so it can be used outside of the function
score=0 # defines the score variable as '0'
q = get_questions('space_quiz_test.txt', 10) # gets 10 random questions
for question in q:
detail = question.split(",")
print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
print(" ")
# etc ....
Doku:
inplace list shuffling: random.shuffle
There are several other things to fix:
# global score # not needed, simply return the score from quiz():
my_score = quiz() # now my_score holds the score that you returned in quiz()
...
# logic errors - but that part can be deleted anyway:
elif detail[0] in qno is True: # why `is True`? `elif detail[0] in qno:` is enough
if detail[0] not in qno == True: # you just made sure that `detail[0]` is in it
...
while True:
answer=input("Answer: ").upper() # make it upper once here
if answer not in ('A','B','C','D'): # and remove the .upper() downstream
print("Answer not valid, try again")
else:
break
I'm very new to python and trying to write some code so that the user enters something. If it's an integer it's sorted into the Numbers list, if it's a string it goes into the String list.
I want to be able to find the mean of all the numbers that are in the list and print out the result.
And in the String section I want to be able to print out everything within the string and its length.
User types 'save' to exit and if input is valid that's caught.
Numbers = []
String = []
while(True):
user_input = input("What's your input? ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(user_input)
for i in range(len(Numbers)):
Numbers[i] = int(Numbers[i])
print(sum(Numbers)/len(Numbers)
elif isinstance(user_input, str):
String.append(user_input)
print(String)
print (len(String)-1)
else:
print("Invalid input.")
break
#use isalpha to check enterted input is string or not
#isalpha returns a boolean value
Numbers = []
String = []
while(True):
user_input = input("input : ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(int(user_input))
print(sum(Numbers)/len(Numbers))
elif user_input.isalpha():
String.append(user_input)
print(String)
print (len(String))
else:
print("Invalid input.")
break
There is good thing called statistics.mean:
from statistics import mean
mean(your_list)
You are using Length, which has not been defined. I think what you wanted was
print(sum(Numbers)/len(Numbers))
and you probably don't want it inside the loop, but just after it (although that might be another typo).
I found other more convenient way to produce the mean: Use statistics model and output the mean.
#import useful packages
import statistics
#Create an empty list
user_list = []
#get user request
user_input = input("Welcome to the average game. The computer is clever enough to get the average of the list of numbers you give. Please press enter to have a try.")
#game start
while True:
#user will input their number into a the empty list
user_number = input("Type the number you want to input or type 'a' to get the average and quit the game:")
#help the user to get an average number
if user_number == 'a':
num_average = statistics.mean(user_list)
print("The mean is: {}.".format(num_average))
break #Game break
else:
user_list.append(int(user_number))
print(user_list)
This is a problem I am working on for a class (below is my question and the code I wrote):
The program should accept a series of students and their exam scores in response to a
"?" prompt. Enter the two digit exam score (no one ever gets 100 or less than 10), a single
space and the name of the student. Keep entering these until the user enters "Stop" –
your program should be able to handle any form of "Stop" – for example, "stop", "Stop",
"STOP", "sTOP", etc.
You should then display a list of student names ordered by their exam scores (low to
high).
For instance (user input is underlined):
? 23 Warren
? 44 Dona
? 33 Tom
? stop
Warren
Tom
Dona
So I understand everything I've written and I understand that this is not an especially complicated problem. Though, the way my code is written, when I input "stop" to show the program that I am finished with inputs, it runs the input "stop" in the for loop creating a index out of range error. How can I make it run "stop" only in the while loop and not in the for loop?
students = []
nameScore = ""
while (nameScore.lower() != "stop"):
nameScore = input ("? ")
students.append(nameScore)
students.sort()
for student in students:
x = student.split()
print (x[1])
If you "break" before you append, then "stop" will not be included in students.
while True:
nameScore = input ("? ")
if nameScore.lower() == "stop": break
students.append(nameScore)
Moreover, if you write the while-loop this way, you won't need to pre-initialize nameScore.
You can change the flow of the program just a bit and have it "prime" the input string before entering the while loop; that way it'll check before it appends the input:
students = []
nameScore = input("? ")
while nameScore.lower() != "stop":
students.append(nameScore)
nameScore = input ("? ")
students.sort()
for student in students:
x = student.split()
print (x[1])
A bit of code repetition, but it does the job.
Another way to do it is to use a list slice to remove the last element:
students = []
nameScore = ""
while nameScore.lower() != "stop":
students.append(nameScore)
nameScore = input ("? ")
students = students[:-1] # Remove the last element
students.sort()
for student in students:
x = student.split()
print (x[1])
By the way, the parenthesis around the while condition aren't necessary in Python.