Dealing with two cases when a condition is met? [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
If the number variable is an integer, an input that is equal to zero should become 'None' and any other value should stay as is. The code below works but for learning purposes I would like to see how this can be achieved differently?
while True:
try:
number = int(input('Type an integer: '))
if type(number) == int: # If the value is an integer, it proceeds.
if number == 0: # Here is another 'if' in case the value is zero which has to turn to the 'None' value
number = None
break
else: # For any other case it should just keep the value from the input above
break
except ValueError:
print("Type an integer")
print(number)

Try
number = number if number != 0 else None
Therefore the complete loop might look like:
while True:
try:
number = int(input('Type an integer: '))
print(number if number != 0 else None)
except ValueError:
print("Type an integer")

No need to check for the type(number) == int because you already passed it to int, which did not raise a ValueError. If this line of code is reached, it must be an int already at this point.
Breaking logic is often hard to follow. IMO this logic would be better suited to a method where you return it, making it more clear what the result of the loop will eventually be.
The prompt for incorrect text is confusing, you should comment that it was incorrect.
The return logic could use an if/else expression to reduce the code.
def ask_for_int():
while True:
try:
number = int(input('Type an integer: '))
return None if number == 0 else number
except ValueError:
print("Invalid input. Try again")
print(ask_for_int())

Related

Is there any way to shorten it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 14 days ago.
Improve this question
n = [1,2,3,4,5,6]
while True:
num = (input("enter your choice(from 1 to 6) "))
if num not in str(n) or num.isdigit == "False":
print("enter valid chice ")
os.system('cls')
pr()
else:
break
I want it to loop if the input is string and not in n
n = [1,2,3,4,5,6]
while True:
num = input("enter your choice(from 1 to 6) ")
if not num.isdigit() or int(num) not in n:
print("enter a valid choice ")
else:
break
The issue in the original code was checking isdigit as a string instead of calling the method on num. Also, the condition to check if num is not in n was incorrect. The corrected code checks if num is not a digit and also checks if the integer form of num is not in n.
Your code is convoluted, here's a simpler version:
# use try/except to get an int, or set our var outside the bounds in the while loop
try:
num = int(input("Enter your number (1-6):"))
except ValueError:
num = 0
# while our input isn't in the 1-6 range, ask for a number
while num not in [1,2,3,4,5,6]:
# same as before, if this is not a number, just set it to something that's not in [1-6] so we stay in the while loop
try:
num = int(input("Enter a valid choice please (1-6):"))
except ValueError:
num = 0
# your code here

As I do so as not to show the -1 in the Python list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Write a function to enter from the keyboard a series of numbers between 1 and 20 and save them in a list.In case of entering an out-of-range value the program will display an error message and ask for a new number.To finish loading you must enter -1.La function does not receive any parameters, and returns the loaded list (or empty, if the user did not enter anything) as the return value.
def funcion():
list = []
num = 0
while num != -1:
num = int(input("Enter a number between 1 and 20: "))
while num > 20 :
num = int(input("Please re-enter the number: "))
list.append(num)
return lista
result = funcion()
print(result)
My question is how I do not show the -1 in the list
It's easier to have an infinite loop and break out of it when the user enters -1:
def funcion():
lista = []
num = 0
while True:
num = int(input("Enter a number between 1 and 20: "))
while num > 20:
num = int(input("Please re-enter the number: "))
if num == -1:
break
else:
lista.append(num)
return lista
result = funcion()
print(result)
The trick is saving the list except the last item like this:
return lista[:-1]
you can read more here:
https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/
The minimal change to your code would just use the list slicing syntax to return all elements of lista apart from the last one:
return lista[:-1]
See [1] below. This is a pythonic way of writing the slightly more intuitive, but more verbose statement:
return lista[:len(lista)-1]
... which in turn is short for the even longer:
return lista[0:len(lista)-1]
You seem to be new to python. I really recommend looking up "list slicing" and "list comprehensions": if you already know a programming language that doesn't have these, once you learn these, you'll wonder how you ever did without them!
[1] http://knowledgehills.com/python/negative-indexing-slicing-stepping-comparing-lists.htm

Value error storing user input Integer into an array in Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm creating an application for my programming class and I'm unable to get it to run properly. Essentially, the application should take 8 numbers from the user and store them in an array and then add those numbers. However, if the user does not provide a number, or press Q, the program should stop.
userNumberList = []
counter = 0
while counter < 8:
try:
userNumber = int(input("Welcome! Please provide numbers or press q to quit. "))
except ValueError:
print("Not a number. Closing application.")
break
else:
if userNumber == 'q':
break
else:
userNumberList.append(int(userNumber))
counter += 1
print(sum(userNumberList))
This is the error I get when running typing a String instead of a number in the prompt:
userNumber = int(input("Welcome! Please provide numbers or press q to quit. "))
ValueError: invalid literal for int() with base 10:
Try this:
Do not convert to int before checking to q.
userNumberList = []
counter = 0
while counter < 8:
userNumber = input("Welcome! Please provide numbers or press q to quit. ")
if userNumber == 'q':
print("Entered command to quit!! closing the application")
break
else:
try:
userNumberList.append(int(userNumber))
counter += 1
except ValueError:
print("Not a number. Closing application.")
break
print(sum(userNumberList))
Don't cast the input to an int straight away. You're handling that when appending anyway.
And apprently input evaluates input as python code. Use raw_input instead. This answer may be helpful Python 2.7 getting user input and manipulating as string without quotations
userNumber = raw_input("Welcome! Please provide numbers or press q to quit. ")
Changing this line fixes the program.

Disregarding bad input within 'for' statement in Python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to write a program that loops a prompt 10 times or until the correct input is entered. Wrong input entered should not count towards the 10 tries to enter the correct input.
I am not sure if I should keep the prompt within the for statement or not. Here is what I have so far regarding the bad input issue:
for i in range(10):
value=input("Enter a numerical value: ")
if value.isdigit()==False:
print("Error.")
A better construct to use would be a while loop.
Instead of looping for 10 times, you could loop until you have a valid input, i.e.
while True:
value = input("Enter a number:")
if value.isdigit() == False:
print "Error"
else:
break
However, that said, if you only want to loop for a maximum of 10 times, the construct that you have is perfectly fine - you just need a way of exiting the loop when a valid number is entered,
for i in range(10):
value=input("Enter a numerical value: ")
if value.isdigit()==False:
print("Error.")
else:#is a digit
break
After seeing your comment, I would still advise using while loop, just with an extra variable (and a few changes made from DarinDouglass's comment
times_correct = 0
while times_corrent < 10:
value = input("Enter a number:")
if value.isdigit() == False:
print "Error"
else:
times_corrent += 1
You need to break the loop when you get the correct input:
for i in range(10):
value=input("Enter a numerical value: ")
if not value.isdigit(): # PEP8 says to use `not` instead of `== False`
print("Error.")
else:
break # If we get here, the input was good. So, break the loop.
See a demonstration below:
>>> for i in range(10):
... value=input("Enter a numerical value: ")
... if not value.isdigit():
... print("Error.")
... else:
... break
...
Enter a numerical value: a
Error.
Enter a numerical value: b
Error.
Enter a numerical value: 12
>>>

How do I write a function that repeatedly prompts the user for a number and then average the numbers? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm pretty new to programming, and I have no idea how to go about this.
Basically I need a function that repeatedly prompts a user to input an integer until they enter a non-numerical characters, then it takes the numbers and averages them.
This what I have so far, the ave function is to average the numbers, that's not the problem
def ioAve():
L = input("Enter your number: ")
if L == int:
print(L)
if L != int:
ave(L)
The program doesn't return anything at all.
This is probably the most pythonic way I can think of to solve this. Your approach of checking if an entered number is of a certain type is less desirable than catching the exceptions that might be raised when trying to convert (e.g. in this case a ValueError is raised when an invalid value is passed to int() ). You can learn more about exceptions in Python at the Python wiki.
The solution below also uses a list, which is an object that can contain multiple values. You can learn more about lists at effbot.org.
numbers = list()
while True:
try:
number = int(input("Enter a number: "))
numbers.append(number)
except ValueError:
break
print ("The average is", sum(numbers) / len(numbers))
cont = True
nums = []
while cont:
entered = input("Enter a number: ")
cont = all(char.isdigit() for char in entered)
if cont:
nums.append(int(entered))
print("The average is:", sum(nums)/len(nums))
Something like this:
print('Average: ',(lambda x:sum(x)/len(x))
([x for x in iter(lambda:(lambda x:int(x)
if x and all(x.isdigit() for x in x)else
...)(input('Enter a number: ')),...)]))
Sorry, I couldn't resist.
Something like this maybe. I'm sure there is a more pythonic way thou.
#import sys instead of using sys for program termination
def main():
sum = 0
iterations = 0
while True:
try:
num = int(raw_input("Input an integer: "))
iterations += 1
sum += num
except:
print "Average: "+str(sum//iterations)
#sys.exit() use break to "jump" out of an infinite loop
break
if __name__ == "__main__":
main()

Categories

Resources