How can I stop a program when the user wants to? - python

So I made a program which asks the user the amount of numbers he wants, which numbers he wants and creates a list. I now want to make it so that if the user puts in the number 0 the program will stop there and print the previous numbers he has put if it's possible (note: I want the 0 to not be printed only the previous numbers he entered). Because this is my first time posting I'm not sure what else information is needed other than what version of Python I'm using (which is 2.7). If there's more information that's needed just ask. Also if it's needed I'll write the code I have written down.
lst = []
x = int(input("Enter number of elements : "))
for i in range(0, x):
num = int(input())
lst.append(num)
print(lst)

Before lst.append(num)
if num == 0:
break

Add a if-else statement:
if num != 0:
lst.append(num)
else:
break

Related

I wrote a code that would print the odd numbers or the even numbers in a list according to users choice. But the append not working inside the def

I created a code that takes a list from the user and then asks the user to choose from printing only the odd numbers or the even numbers. But whenever the user choice is taken, the execution freezes. Using keyboard interrupt, I find that the execution stopped in either the odd or even function. Please help !!!
here is the code:
from os import lstat
def odd(lst,oddlst):
for i in range(0,n):
while(lst[i]%2!=0):
oddlst.append(lst[i])
return oddlst
def even(lst,evenlst):
for i in range (0,n):
while(lst[i]%2==0):
evenlst.append(lst[i])
return evenlst
lst = []
oddlst = []
evenlst = []
n = int(input("enter number of elements \n"))
print("\nenter the elements \n")
for i in range(0,n):
num = int(input())
lst.append(num)
print(lst)
choice = input(" Do you want to print odd elements or even elements \n (odd/even)
\n")
if(choice=="odd"):
odd(lst,oddlst)
print(oddlst)
elif(choice=="even"):
even(lst,evenlst)
print(evenlst)
else:
print("invalid choice")
Perhaps you meant to use an if instead of a while in your odd and even functions.
The reason your execution "freezes", is that you run into an infinite loop.
In either while, the i-th element gets checked, then appended to a list. But the condition, against which you are checking, doesn't change, neither does the index i.
Changing your whiles to ifs should solve your problem.
Also, for a more elegant solution to your problem, have a look at:
https://docs.python.org/3/library/functions.html#filter
How to filter a list

creating a python program which ask the user for a number - even odd

I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0

Loop and validation in number guessing game

I have previously studied Visual Basic for Applications and am slowly getting up to speed with python this week. As I am a new programmer, please bear with me. I understand most of the concepts so far that I've encountered but currently am at a brick wall.
I've written a few functions to help me code a number guessing game. The user enters a 4 digit number. If it matches the programs generated one (I've coded this already) a Y is appended to the output list. If not, an N.
EG. I enter 4567, number is 4568. Output printed from the list is YYYN.
import random
def A():
digit = random.randint(0, 9)
return digit
def B():
numList = list()
for counter in range(0,4):
numList.append(A())
return numList
def X():
output = []
number = input("Please enter the first 4 digit number: ")
number2= B()
for i in range(0, len(number)):
if number[i] == number2[i]:
results.append("Y")
else:
results.append("N")
print(output)
X()
I've coded all this however theres a few things it lacks:
A loop. I don't know how I can loop it so I can get it to ask again. I only want the person to be able to guess 5 times. I'm imagining some sort of for loop with a counter like "From counter 1-5, when I reach 5 I end" but uncertain how to program this.
I've coded a standalone validation code snippet but don't know how I could integrate this in the loop, so for instance if someone entered 444a it should say that this is not a valid entry and let them try again. I made an attempt at this below.
while myNumber.isnumeric() == True and len(myNumber) == 4:
for i in range(0, 4)):
if myNumber[i] == progsNumber[i]:
outputList.append("Y")
else:
outputList.append("N")
Made some good attempts at trying to work this out but struggling to patch it all together. Is anyone able to show me some direction into getting this all together to form a working program? I hope these core elements that I've coded might help you help me!
To answer both your questions:
Loops, luckily, are easy. To loop over some code five times you can set tries = 5, then do while tries > 0: and somewhere inside the loop do a tries -= 1.
If you want to get out of the loop ahead of time (when the user answered correctly), you can simply use the break keyword to "break" out of the loop. You could also, if you'd prefer, set tries = 0 so loop doesn't continue iterating.
You'd probably want to put your validation inside the loop in an if (with the same statements as the while loop you tried). Only check if the input is valid and otherwise continue to stop with the current iteration of your loop and continue on to the next one (restart the while).
So in code:
answer = [random.randint(0, 9) for i in range(4)]
tries = 5
while tries > 0:
number = input("Please enter the first 4 digit number: ")
if not number.isnumeric() or not len(number) == len(answer):
print('Invalid input!')
continue
out = ''
for i in range(len(answer)):
out += 'Y' if int(number[i]) == answer[i] else 'N'
if out == 'Y' * len(answer):
print('Good job!')
break
tries -= 1
print(out)
else:
print('Aww, you failed')
I also added an else after the while for when tries reaches zero to catch a failure (see the Python docs or maybe this SO answer)

python - an alternative way to not have repetitive elements print without break command?

First, in my code i'm asked to enter a value from user and the program should place it in the correct orderly position without using the built-in python sort().
My completed code can do this without repetitively inserting the same element, only with the break command. Now i once i remove the break command the number i enter outputs in the list 3 times instead of 1.
Note: we aren't allowed to use the break statement in this Python course
Currently my code looks like this:
#List of numbers
myList = [1,9,16,24]
#Enter a number to be placed in the list
num = int(input("Enter a number: "))
#For loop to check the placement of entered number
#to compare it and see if it is less than or
#equal to the each and every element in myList
for x in range(0, len(myList)-1):
if num < myList[x]:
myList.insert(x,num)
#break
elif num > myList[x]:
myList.append(num)
#break
print(myList)
ex. output:
[-1,-1,-1,1,9,16,24]
Simple. Have an external condition that you can test at each insertion attempt. If you insert the item, set the condition to false. Then, outside of the loop, if the condition is still true you know the item goes at the end. No breaks involved.
myList = [1,9,16,24]
num = int(input("Enter a number: "))
condition = True
for index, x in enumerate(myList):
if condition and num < x:
myList.insert(index, num)
condition = False
if condition:
myList.append(num)
print(myList)

Extract element from a shuffled list (based off of user's input)

I have something like this:
s=[7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
random.shuffle(s)
ans=input('Press a number from 0 to 9')
I want to associate the input number ans with the s[ans] element. I can do it with 10 if loops, is this the only chance? //SOLVED this
Done that, I want to repeat the random extraction until user digits something like "stop" (here I am) and then sum all the value extracted until "stop" string. How can I do this last point?
Thanks all!
from random import choice
elem = choice (some_list)
If you are only trying to select a random number (and asking for input is only a means to achieve that goal), then you should really look into random.choice. It does exactly what you need, and you won't have to spend time shuffling your list
You can directly access values of an array like so:
s[ans]
But first you may have to convert ans to an integer (and handle cases where a user sends something that's not a number!)
try:
i = int(s)
except ValueError:
i = 0
You've edited your question to declare the original version "solved" and then added a second one. In the future, don't do that; accept the answer that solved the problem for you, then create a new question. (And you should still accept the answer that solved your original problem!) But this time only, here's a second answer:
Done that, I want to repeat the random extraction until user digits something like "stop" (here I am) and then sum all the value extracted until "stop" string. How can I do this last point?
I'm assuming you're on Python 2, and using the input function so the user can just type 2 and you get the number 2 instead of the string "2". (If you're using Python 3, input works like Python 2's raw_input, so see the second version.)
So:
s=[7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
random.shuffle(s)
values = []
while True:
ans=input('Press a number from 0 to 9')
if ans == 'stop':
break
values.append(s[ans])
print sum(values)
Note that the user will have to type "stop" with the quotes this way. If the user instead types stop (or 10, for that matter), the program will quit with an exception. It would be much better to use raw_input instead, and do something like this:
s=[7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
random.shuffle(s)
values = []
while True:
ans=raw_input('Press a number from 0 to 9, or stop when done')
if ans == 'stop':
break
try:
index = int(ans)
values.append(s[ans])
except ValueError:
print '{} is not a number or the word stop'.format(ans)
except IndexError:
print '{} is not between 0 and 9.'.format(ans)
print sum(values)
You may recognize that this values = [], while, values.append pattern is exactly what list comprehensions and iterators are for. And you can easily factor out all the user input into a generator function that just yields each s[ans], and then just print sum(userChoices()), without having to build up a list at all. But I'll leave that as an exercise for the reader.
ans = 0
s = [7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
ans_sums = []
while ans != 'stop': # while the input is not 'stop'
random.shuffle(s)
ans = raw_input('Press a number from 0 to 9: ') # this returns the input as a string
if ans == 'stop':
break
else:
ans_sums.append(int(s[ans])) # adds s[ans] to ans_sums.
# it must be converted to an integer first because raw_input returns it as a string
return sum(s[ans])
Alternatively, you can do something like:
ans = 0
s = [7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
ans_sums = 0
while ans != 'stop': # while the input is not 'stop'
random.shuffle(s)
ans = input('Press a number from 0 to 9: ')
if ans == 'stop':
break
else:
ans_sums += s[ans] # adds s[ans] to ans_sums
return ans_sums
This avoids creating a list and accomplishes the same job: finds the sum of all the input.

Categories