How to keep repeating a program until a specific input? - python

I want to write a program to compute the average of a group of numbers entered (one at a time) by the user. Each group should end when the user enters the sentinel value '' (ENTER without input). Two consecutive sentinel values should quit the program. The number of each group should be displayed along side with their average:
This is my code :
x = eval(input('Enter a number: '))
lis = []
while x != '':
lis.append(x)
if x == '':
avg = sum(lis) / len(lis)
print(avg)

Just move the input into the loop:
x = None
lis = []
while x != '':
x = input('Enter a number: ')
if x != '':
lis.append(int(x))
avg = sum(lis) / len(lis)
print(avg)
Also you don't need the if statement as x must be equal to '' anyway so that the while loop terminates.

Related

how to maek it so that if a for loop ends without triggering an if statement the loop begins again (python)

my for loop is looping through a list and i want tomake it so that if a value a user enters a value it its is not found in the list iwant to get another value from the user to check for in the list
import datetime as date
x = date.datetime.now()
D = []
d = int((x.strftime("%d")))
M = (x.strftime("%B"))
for i in range(1,8):
d = d + 1D.append(d)
print (M+", "+str(d))
z = str(input("enter date for booking"))
for i in D :
if i == z:
break
while True:
x = int(input("Enter a Value : "))
if x not in list:
print("Try again")
continue
print("Whatever you want to print")
break
This could help you with your project. If the variables are integers, keep it as int but you could switch it to str or float according with your variable types.

get sum of the 3 sorted numbers from a user inputted list

i recently started to learn python and i wrote this code to sort numbers least to greatest inputted by the user but after the second number, i get the error "NameError: name 'minimum' is not defined" any help is appreciated. also, I cannot use any built-in functions to sort the numbers as this is a challenge for a class
unsorted_list = []
sorted_list = []
while True:
unsortednum = input("enter a number or 0 to stop: ")
if unsortednum == 0:
while unsorted_list:
minimum = unsorted_list[0]
for item in unsorted_list:
if item < minimum:
minimum = item
sorted_list.append(minimum)
unsorted_list.remove(minimum)
print(sorted_list)
else:
unsorted_list.append(unsortednum)
This is one way to do it.
sorted_list = []
while True:
# The input you get is a string so you need to convert it to int
unsortednum = int(input("enter a number or 0 to stop: "))
# Use break to exit if the user input's 0
if unsortednum == 0:
break
else:
# This first creates a list of all numbers lesser than equal to unsortednum then joins the first list with a second list
# that only contains unsortednum. After that a third list with all numbers greater than unsortednum is joined as well.
sorted_list = [i for i in sorted_list if i <= unsortednum] + [unsortednum] + [i for i in sorted_list if i > unsortednum];
print("Current => ",sorted_list)
print("Final => ",sorted_list)
Doing the least amount of editing to your code:
unsorted_list = []
sorted_list = []
while True:
unsortednum = int(input("enter a number or 0 to stop: "))
if unsortednum == 0:
while unsorted_list:
minimum = unsorted_list[0]
for item in unsorted_list[1:]:
if item < minimum:
minimum = item
sorted_list.append(minimum)
unsorted_list.remove(minimum)
print(sorted_list)
else:
unsorted_list.append(unsortednum)
The only thing missing was assigning unsortednum as an int done by unsortednum = int(input())
Also, in order to not check a value with itself, in the for loop I changed unsorted_list to unsorted_list[1:], representing every value in the list except unsorted_list[0]

I don't get this simple for-loop exercise

I have to write a program that calculates and displays the highest and second highest value entered by te user. The program must also work with zero or one values entered.
Here are some sample runs:
enter a value or 'stop' -3.2
enter a value or 'stop' -5.6
enter a value or 'stop' 0.5
enter a value or 'stop' 0.3
enter a value or 'stop' stop
the highest value = 0.5
the second highest value = 0.3
and
enter a value or 'stop' stop
the highest value could not be calculated
the second highest value could not be calculated
So i got a code, but it only gives me the minimum and the maximum.
all i got so far is this:
minimum = None
maximum = None
a = int(input("Enter a value or 'stop': "))
while True:
a = input("Enter a value or stop: ")
if a == 'stop':
break
try:
number = int(a)
except:
print("Invalid input")
continue
if minimum is None or number < minimum:
minimum = number
if maximum is None or number > maximum:
maximum = number
print('Maximum= ', maximum)
print('Minimum= ', minimum)
Would be awesome if someone could help me out!
value_list = list()
while True:
a = input("Enter a value or stop: ")
if a == 'stop':
break
else:
try:
value_list.append(float(a))
except:
print("Invalid input")
continue
sorted_list = sorted(value_list)
if len(sorted_list) > 0:
print('the highest value = ', sorted_list[-1])
else:
print('the highest value could not be calculated')
if len(sorted_list) > 1:
print('the second highest value = ', sorted_list[-2])
else:
print('the second highest value could not be calculated')
This should work. You might want to handle float/int scenarios
So, the code actually uses Python list to store the input values in the form of float. Once the user enters stop, we are sorting the values in the list in the ascending order and finally displaying only the top two values i.e at index -1 and -2. Enjoy!
As #rkta said, you don't need line 3 (as the program will ask the same question twice when you start it up).
You only need to alter your code slightly to get your desired program. Instead of using this block:
if minimum is None or number < minimum:
minimum = number
if maximum is None or number > maximum:
maximum = number
Use this block:
if highest is None or number > highest:
highest = number
elif second_highest is None or number > second_highest:
second_highest = number
Obviously you will need to set highest and second_highest to None at the beginning of your program, and change your print statements at the end.
I add my two cents:
# declare a list
inputs = []
while True:
a = input("Enter a value or stop: ")
if a == 'stop':
break
try:
# check if input is float or integer
if isinstance(a, int) or isinstance(a, float):
# append number to the list
inputs.append(a)
except:
print("Invalid input")
continue
# sort list
inputs = sorted(inputs)
# print result if list has at least two values
if len(inputs) >= 2:
# cut the list to the last two items
maxs = inputs[-2:]
print 'Max 1 = ', maxs[1]
print 'Max 2 =', maxs[0]
else:
print 'not enough numbers'

Find the Number of even intergers in a sequence

enter an arbitrary sequence of integers at the keyboard, and then prints the number of positive even integers user enters.
def find_even_count():
count = 0
x = raw_input("Enter a value, or q to quit: ")
while (x != "q") and (x > 0):
for num in x:
if (int(x) % 2 == 0):
count += 1
entry = raw_input("Enter a value, or q to quit: ")
return count
I have gotten this so far but it is not working any ideas?
If you are counting them as they are entered there is no need to iterate.
def find_even_count():
count = 0
x = raw_input("Enter a value, or q to quit: ")
while (x != "q") and (x > 0):
if (int(x) % 2 == 0):
count += 1
x = raw_input("Enter a value, or q to quit: ")
return count
on the other hand if you had a sequence of numbers getting the number of evens is O(n) and can be written one pythonic line.
numberOfEvens = sum([1 if k%2==0 else 0 for k in sequence])
The problem is You are getting wrong input, in the Loop, You are Using different variable for second Input. Just change the Variable name inside the Loop as x there You Go.
def find_even_count():
count = 0
x = raw_input("Enter a value, or q to quit: ")
while (x != "q") and (int(x) > 0):
if (int(x) % 2 == 0):
count += 1
x = raw_input("Enter a value, or q to quit: ")
return count
In your code, the line entry = raw_input("Enter a value, or q to quit: ") might be causing issues. if you noticed, in kpie's code, the line is inline with the if statement. in your code it will only be executed if x is even. if x is odd, your code will loop forever. additionally, entry is never used, so, again, x won't change.

Making a list in sentinel loop (beginnger) PYTHON

after much google'ing and note searching I have yet to come upon an answer for making this List of mine work, if you do answer could you explain what I was doing wrong because this problem is determined to not let me work.
code:
def main():
x = int(input("Enter a number (0 to stop) "))
y = x
l = []
while x != 0:
x = int(input("Enter a number (0 to stop) "))
l = [x]
print(l[x])
main()
I thought I was supposed to initialize the list outside of the loop, and in the loop I thought it would take whatever X is inputted as and store it to later be printed out after it, but that wasn't the case. Any pointers?
You would need to append to the list each time:
def main():
x = int(input("Enter a number (0 to stop) "))
l = [x] # add first x, we will add to the is list not reassign l inside the loop
while x != 0:
x = int(input("Enter a number (0 to stop) "))
l.append(x) # append each time
print(l) # print all when user enters 0
l = [x] reassigns l to a list containing whatever the value of x is each time through the loop, to get all numbers you have to append to the list l initialised outside the loop.
You could also use iter with a sentinel value of "0":
def main():
l = []
print("Enter a number (0 to stop) ")
for x in iter(input,"0"):
print("Enter a number (0 to stop) ")
l.append(int(x))
print(l)

Categories

Resources