need stopping if input not number [closed] - python

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 3 years ago.
Improve this question
my code not stop in line 9-10 when inserted words, I would like it to continue only when numbers are entered
from cs50 import get_int
numbers = []
while True:
number = get_int("number: ")
if not number: # here #
break # here #
if number not in numbers:
numbers.append(number)
print()
for number in numbers:
print(number)
need stopping if input not number

You can parse the input string to be a number or not in a while True loop, if it is not a number, break the loop, else keep asking.
numbers = []
while True:
#Ask for input
s = input("number: ")
number = 0
#Try to parse the string as a number, if you cannot, break the loop
try:
number = int(s)
except:
break
#If you can parse the string as a number, add it to the list
numbers.append(number)
print(numbers)
Sample outputs will be
number: 123
number: 456
number: 789
number: abc
[123, 456, 789]

In Python 3, you can use the following to ensure number is an integer (whole number):
isinstance(number, int)
If either an integer or a float (number with decimals) is allowed, you can use the following:
isinstance(number, (int, float))
I highly recommend reading more about this subject in this answer.

You don't need to define a new function to do that.
numbers = []
while True:
number = input("number: ")
try:
number = int(number)
if number not in numbers:
numbers.append(number)
except:
break
print (numbers)

try:
if number == int(number):
if number not in numbers:
numbers.append(number)
except:
#invalid input will throw you into this block
break

Related

i wrote this code to find the largest and smallest (int)number but it does not work

I wrote this code to get an input of several int numbers and write the smallest and largest of them but the code does not work.
numbers=[]
num=input('enter your number')
Int_num=int(num)
Int_num.append(numbers)
print('maximum number is:',max(numbers))
print('minimum number is:',min(numbers))
In order to get a sequence of numbers:
numbers = []
while True:
number = input('Enter a number or enter q to exit: ')
if number == 'q':
break
else:
numbers.append(int(number))
print(f'Max: {max(numbers)}, Min: {min(numbers)}')
Replace Int_num.append(numbers) with numbers.append(Int_num.append)
To get multiple numbers you can try:
numbers = []
last_number = input('Enter a number: ')
while last_number:
numbers.append(int(last_number))
print(f'Max: {max(numbers)}, Min: {min(numbers)}')
You are trying to append a list to a integer, it should be numbers.append(Int_num), so you will append the number Int_num to the list numbers.
The problem is line
Int_num.append(numbers)
it should be
numbers.append(Int_num)
Also if you put a while(True): around all but the first line you can add lots of numbers to the list (use ctrl+c to stop the program, if it's running in cmd or powershell)
Try this:
numbers=[]
num=input('enter your number')
while num != "":
Int_num=int(num)
numbers.append(Int_num)
num=input('enter your number')
print('maximum number is:',max(numbers))
print('minimum number is:',min(numbers))

In python, it shows ValueError: invalid literal for int() with base 10: ''? [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 1 year ago.
Improve this question
n = int(input("enter nos of items in List: "))
a = []
for i in range(0,n):
elements = int(input("Enter Elements : "))
a.append(elements)
avg = sum(a)/n
print("average of given numbers", round(avg,2))
I would suggest using validating the user input with a while loop, you can check if the answer contains only number, if it does not, then the loop repeats until the user enters a valid input.
n = input("enter nos of items in List: ")
while n.isdigit() != True:
n = input("Invalid Input!\nEnter nos of items in List: ")
a = []
for i in range(0, int(n)):
elements = input("Enter Elements : ")
while elements.isdigit() != True:
elements = input("Invalid Input!\nEnter Elements : ")
a.append(int(elements))
avg = sum(a)/int(n)
print("average of given numbers", round(avg,2))
ValueErros can be caused, as the result of the you trying to convert a string containing alphabetic characters into an integer.

How to limit input integer in single digit? [python] [duplicate]

This question already has answers here:
Python excepting input only if in range
(3 answers)
Closed 2 years ago.
what's the easiest way to limit this code integer input to a single digit?
num = ["First","Second","Third"]
num_list = []
for a in num:
x = int(input(f"Enter Your {a} number: "))
num_list.append(x)
for i in range(0,3):
for j in range(0,3):
for k in range(0,3):
if(i!=j&j!=k&k!=i):
print(num_list[i],num_list[j],num_list[k])
just a quick fix
def get_single_digit_input():
while True:
a = input('please enter number')
if not a.isnumeric():
print('please enter single digit Numeric only')
continue
a = int(a)
# your logic is here
if a<=9 and a>=0:
return a
else:
print('please enter single digit Numeric only')
a = get_single_digit_input()
You can check using a while statement. If the input is not a single digit, force it back to the input statement. Also you want to check if the input is a digit and not an alphabet or special character.
Here's a way to do it: I am using the walrus operator in python 3.9
while len(x:=input('Enter a single digit :')) > 1 or (not x.isnumeric()):
print ('Enter only a single digit')
print (x)
If you are using python < 3.9, then use this.
x = ''
while True:
x = input ('Enter a single digit :')
if (len(x) == 1) and (x.isnumeric()): break
print ('Enter only a single digit')
print (x)

While Loop Concatenation Exercise [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 5 years ago.
Improve this question
I'm just starting to learn Python and have a question regarding an exercise that came up in the textbook I'm reading.
I found a solution that does function, but I'm wondering if there is a simpler/recommended solution?
Problem:
numXs = int(input('How many times should I print the letter X? '))
toPrint = ' '
#concatenate X to print numXs times print(toPrint)
My solution:
numXs = int(input('How many times should I print the letter X? '))
toPrint = ''
while (toPrint == ''):
if numXs == 0:
numXs = int(input('Enter an integer != 0 '))
else:
toPrint = abs(numXs) * 'X'
print(toPrint)
I'd suggest you get all your data checking and correction handled up front, so your actual algorithm can be much simpler:
numXs = 0
while numXs <= 0:
numXs = int(input('How many times should I print the letter X? '))
if numXs <= 0:
print('Enter an integer > 0')
print('X' * numXs)
A simple solution would be
try:
print("x" * int(input("how many times?")))
except:
print("you entered an invalid number")
If you want a zero or negative check
try:
num = int(input("how many times?"))
if num > 0:
print("x" * num)
else:
print("need a positive integer")
except:
print("not a number")
If you want this to happen forever, just wrap it in a while loop
while True:
#code above
You are not handling wrong conversions (input of "Eight") - so you could shorten it to:
print(abs(int(input("How many?")))*"X") #loosing the ability to "requery" on 0
Same functionality:
numXs = abs(int(input('How many times should I print the letter X? ')))
while not numXs: # 0 is considered FALSE
numXs = abs(int(input('Enter an integer != 0 ')))
print(numXs * 'X')
Safer:
def getInt(msg, errorMsg):
'''Function asks with _msg_ for an input, if convertible to int returs
the number as int. Else keeps repeating to ask with _errorMsg_ until
an int can be returned'''
i = input(msg)
while not i.isdigit():
i = input(errorMsg)
return int(i)
I am using isdigit() to decide if the input is a number we can use. You could also do try: and except: around the int(yourInput) so you can catch inputs that are not conversible to integers:
def getIntWithTryExcept(msg, errorMsg):
'''Function asks with _msg_ for an input, if convertible to int returs
the number as int. Else keeps repeating to ask with _errorMsg_ until
an int can be returned'''
i = input(msg) # use 1st input message
num = 0
try:
num = int(i) # try convert, if not possible except: will happen
except:
while not num: # repeat with 2nd message till ok
i = input(errorMsg)
try:
num = int(i)
except: # do nothing, while is still True so it repeats
pass
return int(i) # return the number

A number from Multiple Numbers [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 9 years ago.
Improve this question
I have an assignment. It was suppose to do the following:
--> Take an integer input(say 100)
--> Add the digits till the sum is a single digit number(1)
My program till now is:
goodvalue1=False
goodvalue2=False
while (goodvalue1==False):
try:
num=input("Please enter a number: ")
except ValueError:
print ("Wrong input. Try again.")
else:
goodvalue1=True
if (goodvalue1==True):
ListOfDigits=list(map(int,str(num)))
sum=10
while(sum>9):
Sum=sum(ListOfDigits)
if (Sum>9):
ListOfDigits=list(map(int,str(Sum)))
Sum=sum(ListOfDigits)
Those booleans are not needed. You can factor the code down to:
while True:
try:
num = int(input("Please enter a number: ")) # Note how I've added int()
break # Breaks out of the loop. No need for a boolean.
except ValueError:
print("Wrong input. Try again.")
I don't see why you called list(map(int, str(num))); but I think you were intending to put int() around your input. So I added one in above. Now it can catch an error :).
Now, to get one digit, you can use another while loop here:
while num > 9:
num = sum(map(int, str(num)))
Pretty much this creates [1, 0, 0] which sum() then calls on. This repeats until it is no longer a two digit number (or three, four, etc)
So altogether:
while True:
try:
num = int(input("Please enter a number: ")) # Note how I've added int()
break # Breaks out of the loop. No need for a boolean.
except ValueError:
print("Wrong input. Try again.")
while num > 9: # While it is a two digit number
num = sum(map(int, str(num)))
Just note that for conditional statements, it's never pythonic to do a == True or b == False.
From the PEP:
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
My take on this:
inp = None
while inp is None:
try:
inp = int(input('Enter number here: '))
except ValueError:
print('Invalid Input, try again')
summed = sum(map(int, str(inp)))
while summed > 9:
summed = sum(map(int, str(summed)))
print('The result is {}'.format(summed))
For an explanation #Haidro did a good job: https://stackoverflow.com/a/17787707/969534
You're very close. Here's what you need to change:
Sum=sum(ListOfDigits)
while(Sum>9):
Sum=sum(ListOfDigits)
if (Sum>9):
ListOfDigits=list(map(int,str(Sum)))
Sum=sum(ListOfDigits)
In this code, you have a while loop that executes when sum is bigger than 9. So why use another variable Sum (also, it makes for really difficult-to-read code)? Do this instead:
while(sum>9):
sum=sum(ListOfDigits)
ListOfDigits=list(map(int,str(sum)))
This is only to show you what went wrong with your code. I wouldn't recommend using it (look below for what I would do). First, you mix variable-naming conventions, which is a very bad idea, especially when you work in a team (even otherwise, can you imagine looking at your code a month or six months from now?).
Second, you don't ever use goodvalue2; what's it there for?
Third, if goodvalue1 is only ever going to be a bool, then why check if (goodvalue1==True)? if goodvalue1 is clearer and more pythonic.
Please, for the love of all that is good, use some spaces in your code. Eyes get very strained after looking at expressions like ListOfDigits=list(map(int,str(num))) for a while. Try ListOfDigits = list(map(int, str(num))) instead.
Personally, I would do this:
num = None
while num is None:
try:
num = int(raw_input("Enter a number: "))
except ValueError:
num = None
num = sum(int(i) for i in str(num))
while num > 9:
num = sum(int(i) for i in str(num)) # this uses a list comprehension. Look it up, they're very useful and powerful!
RECURSION !
Calculate the sum of the digits. Check if the sum has one digit or multiple digit. If one digit, that is your answer, else, call the function on the sum again.
def oneDigitSum(n):
if n < 10:
return n
else:
return oneDigitSum(sum([int(i) for i in str(n)]))
# [f(elem) for elem in li] = [f(a), f(b), .... ] where li = [a, b, ... ]
# sum returns the total of the numbers in list
while True: # continue this loop for eternity, until it gets break
try:
num=int(input("Please enter a number: "))
print(oneDigitSum(num))
break # printed the sum, now I can break the loop peace fully
except ValueError:
print ("Wrong input. Try again.")
continue # oops, looks like wrong input, lets continue the loop

Categories