This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
am trying to take input from user forcefully and execute it in Fibonacci elements program, having problem near input i want to make sure that he doesn't enter character nor -ve number, when i take my input as int(input()) my while loop wont execute i want it to keep executing until user provides input.
in below program when i entered 5 as input it taking it as string object
n=input("enter no of fibonnaci elements: ")
while not n:
n=input("enter no of fibonnac elements: ")
print(type(n))
if(n!=int()):
print("enter integer only")
else:
t1=0
t2=1
print("series is:",end=" ")
for i in range(n):
print(t1,end=" ")
t1,t2=t2,(t1+t2)
print()
You can use isinstance(n,int)to check if it is an int. But if you use int(input("enter no of fibonnaci elements:"))then it will throw a ValueError before it.
n=int(input("enter no of fibonnaci elements: ")) #convert to int here
while not n: #will not enter this loop - why is it even here?
n=input("enter no of fibonnac elements: ")
if(not isinstance(n,int)): #Note: won't Reach this line - Will throw an error before this
print("enter integer only")
else:
t1=0
t2=1
print("series is:",end=" ")
for i in range(n):
print(t1,end=" ")
t1,t2=t2,(t1+t2)
print()
A better way to do this
while True:
try:
n=int(input("enter no of fibonnaci elements: "))#convert to int here
break
except ValueError:
print("enter integer only")
t1=0
t2=1
print("series is:",end=" ")
for i in range(n):
print(t1,end=" ")
t1,t2=t2,(t1+t2)
print()
Output
enter no of fibonnaci elements: str
enter integer only
enter no of fibonnaci elements: 6
series is: 0 1 1 2 3 5
Related
This is my assigned task :
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and having as output:
Invalid input
Maximum is 10
Minimum is 2
This is what I have so far but is not showing me the maximum neither the minimum of the inputs , as is not showing the Invalid input whenever the user try to put any word in it .
list = []
for i in range(2,10):
list.append(int(input('Ingrese un nĂºmero\n')))
# Ordenar lista
list.sort()
# Numero menor
print(list[0])
# Numero mayor
print(list[-1])
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
print(num)
print("Maximum", largest)
Code:-
lis = []
while True:
try:
num=int(input("Enter a number: "))
lis.append(num)
except ValueError:
print("It is not a number.. please verify!! Invalid input\n")
check=input("If you want to continue to write number please enter. if you are done please write done:\n")
if check.lower() == "done":
break
print("Maximum", max(lis))
print("Minimum",min(lis))
Output:-
Enter a number: 7
If you want to continue to write number please enter. if you are done please write done:
Enter a number: 2
If you want to continue to write number please enter. if you are done please write done:
Enter a number: bob
It is not a number.. please verify!! Invalid input
If you want to continue to write number please enter. if you are done please write done:
Enter a number: 10
If you want to continue to write number please enter. if you are done please write done:
done
Maximum 10
Minimum 2
You can use walrus operator (:=) to prompt and check if num equals 'done' or not. Catch invalid num using try except and add num to numlist if it can be casted to int. Print out the largest and the smallest num of numlist using max() and min().
numlist = []
while (num := input('Enter a number: ')) != 'done':
try: numlist += [int(num)]
except ValueError: print('Invalid input')
print('Maximum is', max(numlist))
print('Minimum is', min(numlist))
Output:
Enter a number: 7
Enter a number: 2
Enter a number: bob
Invalid input
Enter a number: 10
Enter a number: 4
Enter a number: done
Maximum is 10
Minimum is 2
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)
This question already has answers here:
How do I determine if the user input is odd or even?
(4 answers)
Closed 4 years ago.
I tried to make a odd/even 'calculator' in python and it keeps popping up errors. Here's the code:
def odd_even():
print("Welcome to Odd/Even")
num = input("Pick a number: ")
num2 = num/2
if num2 == int:
print("This number is even")
else:
print("This number is odd")
Id like to know whats causing the errors and solutions to them
There is an error in the line: num = input("Pick a number: ")
Because input method always returns a String,so you should convert it into int to performs the integer operation
The currect code is:
num =int( input("Pick a number: "))
you can't do math with strings convert it to int
try:
num = int(input("Pick a number: "))
except ValueError:
print('This is not a number!')
return
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I am trying to get a user to input a number into a calculator program. The goal right now is to keep giving the user an error message and asking to reenter a number until they enter a real number.
here is some code that I've done:
number_1 = input("Enter your first number here! ")
while number_1 == int():
print("Well done for entering a number!")
you need to use isdigit()
number_1 = input("Enter your first number here! ")
if str(number_1).isdigit():
print("Well done for entering a number!")
How about try: except:?
def my_input(number_1):
while 1:
try:
int(number_1)
return number_1
except:
print("It is not an integer.")
number_1 = input("Give an integer: ")
int1 = input("Enter your first number here! ")
my_input(int1)
print("Well done for entering a number!")
You may have to change int(number_1) to float(number_1) (and input text(s)) depending on your implementation.
got a error while compiling the code.
I tried to find smallest and largest value from user's input by storing the input in lists. After 'int' object not iterate problem, couldn't proceed further
largest=0
smallest=0
num=[]
while True:
num = int(input("Please enter a number: "))
for i in num:
if i>largest:
largest=i
for j in num:
if j<smallest:
smallest=j
if num==12:
break
print(largest)
print(smallest)
The moment you issue below code line num is no longer a list, instead its an int type of data.
num = int(input("Please enter a number: "))
As you can understand, there is nothing to iterate over in case of a single integer value.
The right solution is to read your input to a separate variable and append to your list.
input_num = int(input("Please enter a number: "))
num.append(input_num)
Further you will have to change value of your exit clause
if num==12:
break
If you desire to stop the loop after 12 inputs, then use len(num) == 12 in the if condition. In case you want to break loop if input number is 12 then change if condition to if input_num == 12
Note: Your algorithm has logical errors as well. You are assigning smallest to 0 . In case user enters all positive integers as input, your result will incorrect.
You are trying to iterate through a number which is wrong, you have overwritten your num list to an integer. Instead of the following:
num = int(input("Please enter a number: "))
You should save the number in some other variable and add to num list like:
x = int(input("Please enter a number: "))
num.append(x)