I have a piece of code that does some calculations with a user input number. I need a way to check if user entry is an integer and that entered number length is equal or more than 5 digits. If either one of conditions are False, return to entry. Here is what i got so far and its not working:
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "
If anyone has a solution, I'd appreciate it.
Thanks
This would be my solution
while True:
stringset = raw_input("Enter a number: ")
try:
number = int(stringset)
except ValueError:
print("Not a number")
else:
if len(stringset) >= 5:
break
else:
print("Re-enter number")
something like this would work
while True:
number = input('enter your number: ')
if len(number) >= 5 and number.isdigit():
break
else:
print('re-enter number')
Use this instead of your code
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5:
try:
val = int(userInput)
break
except ValueError:
print "Re-enter number:
else:
print "Re-enter number:
Do not use isdigit function if you want negative numbers too.
By default raw_input take string input and input take integer input.In order to get length of input number you can convert the number into string and then get length of it.
while True:
stringset = input("Enter number: ")
if len(str(stringset))>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "
Related
I want to make a code that allows me to check if the number I have entered is really a number and not a different character. Also, if it is a number, add its string to the list.
Something like this:
numbers = []
num1 = input("Enter the first number: ")
try:
check = int(num1)
numbers.append(num1)
print("The number {} has been added.".format(num1))
except ValueError:
print("Please, enter a number")
I have to do the same for several numbers, but the variables are different, like here:
num2 = input("Enter the next number: ")
try:
check = int(num2)
numbers.append(num2)
print("The number {} has been added.".format(num2))
except ValueError:
print("Please, enter a number")
Is there any way to create a code that does always the same process, but only changing the variable?
If you are trying to continue adding numbers without copying your code block over and over, try this:
#!/usr/bin/env python3
while len(numbers) < 5: #The five can be changed to any value for however many numbers you want in your list.
num2 = input("Enter the next number: ")
try:
check = int(num2)
numbers.append(num2)
print("The number {} has been added.".format(num2))
except ValueError:
print("Please, enter a number")
Hopefully this is helpful!
Create the list in a function (returning the list). Call the function with the number of integers required.
def get_ints(n):
result = []
while len(result) < n:
try:
v = int(input('Enter a number: '))
result.append(v)
print(f'Number {v} added')
except ValueError:
print('Integers only please')
return result
Thus, if you want a list of 5 numbers then:
list_of_numbers = get_ints(5)
Python noob here. I am trying to create a list with numbers a user inputs and then do some simple calculations with the numbers in the list at the end, in a while loop. The While loop is not breaking when 'done' is inputted. It just prints 'Invalid input.'
list = []
while True:
try:
n = int(input('Enter a number: '))
list.append(n)
except:
print('Invalid input')
if n == 'done':
break
print(sum.list())
print(len.list())
print(mean.list())
You will have to separate receiving user input with checking against "done" from conversion to a number and appending to the list. And you will have to check for "done" before converting the input to an integer.
Try something like this:
list_of_numbers = []
while True:
user_input = input("Enter a number or 'done' to end: ")
if user_input == "done":
break
try:
number = int(user_input)
except ValueError:
print("invalid number")
continue
list_of_numbers.append(number)
print(list_of_numbers)
# further processing of the list here
This is because the int() function is trying to convert your input into an integer, but it is raising an error because the string 'done' can not be converted to an integer. Another point is that sum(), mean() and len() are functions, not attributes of lists. Also mean() is not a built in function in python, it must be import with numpy. Try it like this:
from numpy import mean
list = []
while True:
try:
n = input('Enter a number: ')
list.append(int(n))
except:
if n!='done':
print('Invalid input')
if n == 'done':
break
print(sum(list))
print(len(list))
print(mean(list))
You must check if you can turn the input into a integer before appending to your list. You can use use the try/except to catch if the input variable is convertible to a integer. If it's not then you can check for done and exit.
list = []
while True:
n = input('Enter a number: ')
try:
n = int(n)
list.append(n)
except ValueError:
if n == 'done':
break
print('Invalid input')
total = sum(list)
length = len(list)
mean = total/length
print('sum:', total)
print('length:', length)
print('mean:', mean)
Example interaction
Enter a number: 12
Enter a number: 3
Enter a number: 4
Enter a number:
Invalid input
Enter a number: 5
Enter a number:
Invalid input
Enter a number: done
sum: 24
length: 4
mean: 6.0
If the user enters done, you will attempt to convert into an int, which will raise an exception that you then catch.
Instead, perform your check before attempting to convert it to an integer.
I am trying to write a game that generates a random integer and the user has to guess it.
The problem is that if the user input is not a digit it crashes. So I tried to use isdigit, and it works at the beginning, but if the user decides to input not a number after the first input was a digit, it still crashes. I don't know how to make it check isdigit for every input.
import random
x =(random.randint(0,100))
print("The program draws a number from 0 to 100. Try to guess it!")
a = input("enter a number:")
while a.isdigit() == False :
print("It is not a digit")
a = input("enter a number:")
if a.isdigit() == True :
a = int(a)
while a != x :
if a <= x :
print("too less")
a = input("enter a number:")
elif a >= x :
print("too much")
a = input("enter a number")
if a == x :
print("good")
I would suggest doing the following:
completed = False
while not completed:
a = input("enter a number: ")
if a.isdigit():
a = int(a)
if a < x:
print("too little")
elif a > x:
print("too much")
else:
print("good")
completed = True
else:
print("It is not a digit")
If your code crashed because the user entered not a number, then either make sure the user enters a number, or handle an error while trying to compare it with a number.
You could go over all chars in the input and ensure that they are all digits.
Or you could use a try/except mechanism. That is, try to convert to the numerical type you wish the user to enter and handle any error throwen. Check this post:
How can I check if a string represents an int, without using try/except?
And also:
https://docs.python.org/3/tutorial/errors.html
The typical pythonic way to tackle that would be to "ask for forgiveness instead of looking before you leap". In concrete terms, try to parse the input as int, and catch any errors:
try:
a = int(input('Enter a number: '))
except ValueError:
print('Not a number')
Beyond that, the problem is obviously that you're doing the careful checking once at the start of the program, but not later on when asking for input again. Try to reduce the places where you ask for input and check it to one place, and write a loop to repeat it as often as necessary:
while True:
try:
a = int(input('Enter a number: '))
except ValueError: # goes here if int() raises an error
print('Not a number')
continue # try again by restarting the loop
if a == x:
break # end the loop
elif a < x:
print('Too low')
else:
print('Too high')
print('Congratulations')
# user vs randint
import random
computer = random.randint(0,100)
while True:
try:
user = int(input(" Enter a number : "))
except (ValueError,NameError):
print(" Please enter a valid number ")
else:
if user == computer:
print(" Wow .. You win the game ")
break
elif user > computer:
print(" Too High ")
else:
print(" Too low ")
I think this can solve the issues.
In your code you want to check whether the user has input no or string since your not using int() in your input it will take input as string and furthur in your code it wont be able to check for <= condition
for checking input no is string or no
code:-
a = input ("Enter no")
try:
val = int(a)
print("Yes input string is an Integer.")
print("Input number value is: ", a)
except ValueError:
print("It is not integer!")
print(" It's a string")
You probably will have to learn how to do functions and write your own input function.
def my_input(prompt):
val = input(prompt)
if val.isdigit():
return val
else:
print('not a number')
# return my_input(prompt)
I have been trying to solve this problem by using the following function. What should I do to store all the digits input value and print them only at the end of the program when the program finishes to loop.
def compare(a):
a=0
while True:
b=input("Enter an integer : ")
if b.isdigit():
k=n+1
a=a+int(b)
elif b.isalpha():
if b.upper()=="Q":
print("Digits\n",a,"\nTotal\n",a)
break
else:
print("Invalid Value. Enter again")
elif b.isalnum():
print("Value not recognized. Enter a valid value.")
else:
print("Unrecognized value is submitted. Enter again")
I assumed you want the Total to print the number of digits, and not the sum of the digits. A working version with comments about the changes compared to your code:
def compare(): # input value is not used
a=[] # changed a to a list instead of integer
n=0 # hold the number of digits that were entered
while True:
b=input("Enter an integer : ")
if b.isdigit():
n+=1 # add 1 to the number of digits that were entered, variable k is not used
a.append(int(b)) #append the entered digit to list a
elif b.isalpha():
if b.upper()=="Q":
print("Digits\n",*a,"\nTotal\n",n) # use print(*a) to print the list of numbers
break
else:
print("Invalid Value. Enter again")
elif b.isalnum():
print("Value not recognized. Enter a valid value.")
else:
print("Unrecognized value is submitted. Enter again")
Updating you code as per question
def compare(a):
a=0
all_digits = [] # Empty list
while True:
b=input("Enter an integer : ")
if b.isdigit():
all_inputs.append(b) # Append digit to list
k=n+1
a=a+int(b)
elif b.isalpha():
if b.upper()=="Q":
print("Digits\n",a,"\nTotal\n",a)
print("all digits: {}".format(all_digits))
break
else:
print("Invalid Value. Enter again")
elif b.isalnum():
print("Value not recognized. Enter a valid value.")
else:
print("Unrecognized value is submitted. Enter again")
But this would be better code:
def compare(): # no need to pass any argument
a = 0
all_digits = [] # Empty list
while True:
b = raw_input("Enter an integer: ")
if b.isdigit():
all_digits.append(b) # Append digit to list
a = a + int(b) # do not see 'k' being used anywhere
elif b.isalpha():
if b.upper() == "Q":
print("Digits: {}\nTotal: {}\nSum: {}".format(", ".join(all_digits), len(all_digits), a))
break
else:
print("Invalid Value. Enter again")
else: # no need of b.isalnum(). this will take care of both
print("Unrecognized value is submitted. Enter again")
Output
Enter an integer: 1
Enter an integer: 2
Enter an integer: 3
Enter an integer: 4
Enter an integer: 5
Enter an integer: Q
Digits: 1, 2, 3, 4, 5
Total: 5
Sum: 15
Ok so I'm really new to programming. My program asks the user to enter a '3 digit number'... and I need to determine the length of the number (make sure it is no less and no more than 3 digits) at the same time I test to make sure it is an integer. This is what I have:
while True:
try:
number = int(input("Please enter a (3 digit) number: "))
except:
print('try again')
else:
break
any help is appreciated! :)
You could try something like this in your try/except clause. Modify as necessary.
number_string = input("Please enter a (3 digit) number: ")
number_int = int(number_string)
number_length = len(number_string)
if number_length == 3:
break
You could also use an assert to raise an exception if the length of the number is not 3.
try:
assert number_length == 3
except AssertionError:
print("Number Length not exactly 3")
input() returns you a string. So you can first check the length of that number, and length is not 3 then you can ask the user again. If the length is 3 then you can use that string as a number by int(). len() gives you the length of the string.
while True:
num = input('Enter a 3 digit number.')
if len(num) != 3:
print('Try again')
else:
num = int(num)
break
Keep the input in a variable before casting it into an int to check its length:
my_input = input("Please enter a (3 digit) number: ")
if len(my_input) != 3:
raise ValueError()
number = int(my_input)
Note that except: alone is a bad practice. You should target your exceptions.
while True:
inp = raw_input("Enter : ")
length = len(inp)
if(length!=3):
raise ValueError
num = int(inp)
In case you are using Python 2.x refrain from using input. Always use raw_input.
If you are using Python 3.x it is fine.
Read Here
This should do it:
while True:
try:
string = input("Please enter a (3 digit) number: ")
number = int(string)
if len(string) != 3 or any(not c.isdigit() for c in string):
raise ValueError()
except ValueError:
print('try again')
else:
break