ValueError Exception Handling in a while loop: Repeat only wrong input - python

I would like the following code to ask the user -in a while loop- to input two integers, handle ValueError Exception, and if all well to print the sum.
My problem is that if the first number passes and the second doesn't, it asks to input the first one all over again.
How do I get it in this case to prompt the second input only?
while True:
try:
number_1 = int(input("enter the first number: "))
number_2 = int(input("enter the second number: "))
except ValueError:
print("please enter numbers only!")
else:
result = number_1 + number_2
print(f" {number_1} + {number_2} = {result}")
Many thanks in advance!

Probably writing a small function to request user for input and handle the ValueError would come handy in here and would be a good practice to use.
Example:
def get_input(show_text:str):
while True:
try:
number = int(input(show_text))
break
except ValueError:
print('Enter number only!')
return number
number_1 = get_input('enter the first number: ')
number_2 = get_input('enter the second number: ')
result = number_1 + number_2
print(f" {number_1} + {number_2} = {result}")
Example output
enter the first number: 1
enter the second number: a
Enter number only!
enter the second number: f
Enter number only!
enter the second number: 2
1 + 2 = 3

Related

How to use the same code but with different variables

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)

How to change the value within function, then apply it to while loop?

So I have this function:
def check_List(listname, input_num):
if input_num in listname:
print('Duplicated Number')
input_num=0
return input_num
the purpose was to change whatever I input for input_num to become 0 if it's a duplicate in a list and it worked. However, I have a while loop statement that states if the input is less than 1 or greater than 9, it will go into a loop. When I place this fuction into the loop, it does mention that it is a duplicate, but it will keep the original value that was input.
Here's my full code:
guess=[]
while guess != rnd:
count=0
strike=0
ball=0
guess1=int(input("Input First Number: "))
while guess1>9 or guess1<1:
print('Input a number between 1-9')
guess1=int(input("Input First Number: "))
guess.append(guess1)
guess2=int(input('Input Second number: '))
check_List(guess,guess2)
print(guess2)
while guess2>9 or guess2<1:
print('Input a number between 1-9')
guess2=int(input("Input Second Number: "))
guess.append(guess2)
guess3=int(input('Input Thrid number: '))
while guess3>9 or guess3<1:
print('Input a number between 1-9')
guess3=int(input("Input Thrid Number: "))
guess.append(guess3)
guess4=int(input('Input Fourth number: '))
while guess4>9 or guess4<1:
print('Input a number between 1-9')
guess4=int(input("Input Fourth Number: "))
guess.append(guess4)
print(guess, rnd)
I thinkt the behavior you observe might be liked to the fact, that you use check_List only on one input. I propose to clean up the code a little:
counting= ['first', 'second', 'third','fourth']
guess = []
while len(guess) < 4:
c_guess = int(input(f"Input {counting[len(guess)]} Number: "))
if c_guess in guess:
print('Duplicated Number')
continue
if 9 > c_guess >= 1:
guess.append(c_guess)
continue
print('Input a number between 1-9')
You can further improve it by cathing bad(non integer) inputs:
try:
c_guess = int(input(f"Input {counting[len(guess)]} Number: "))
except:
print('Not a valid integer number.')

Number validation in python?

Question was to help validate text with an automated number selector in Python
answer correctly below
from random import randrange
while True:
try:
userinput=int(input("Enter a number: "))
break
except:
print("Only numbers you loser")
print(randrange(int(input())))
just I have to press enter in the terminal before it registers that I have typed anything in
Enter a number: a
Only numbers you loser
Enter a number: 30
30
4
from random import randrange
s = input('Enter a Number: ')
try:
n = int(s)
print(randrange(n + 1))
except ValueError:
print('Enter a number instead of a letter')
You want to ask the input in an infinite loop, and break only once the value is valid (i.e. it does not throw a ValueError anymore).
from random import randrange
while True:
try:
n = int(input("Enter a number: "))
break
except ValueError:
print("Your input was not a number, try again.")
print(randrange(n + 1))

Python: Continue if variable is an 'int' and has length >= 5

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: "

How to count how many tries are used in a loop

For a python assignment I need to ask users to input numbers until they enter a negative number. So far I have:
print("Enter a negative number to end.")
number = input("Enter a number: ")
number = int(number)
import math
while number >= 0:
numberagain = input("Enter a number: ")
numberagain = int(numberagain)
while numberagain < 0:
break
how do I add up the number of times the user entered a value
i = 0
while True:
i += 1
n = input('Enter a number: ')
if n[1:].isdigit() and n[0] == '-':
break
print(i)
The str.isdigit() function is very useful for checking if an input is a number. This can prevent errors occurring from attempting to convert, say 'foo' into an int.
import itertools
print('Enter a negative number to end.')
for i in itertools.count():
text = input('Enter a number: ')
try:
n = int(text)
except ValueError:
continue
if n < 0:
print('Negative number {} entered after {} previous attempts'.format(n, i))
break
The solution above should be robust to weird inputs such as trailing whitespace and non-numeric stuff.
Here's a quick demo:
wim#wim-desktop:~$ python /tmp/spam.py
Enter a negative number to end.
Enter a number: 1
Enter a number: 2
Enter a number: foo123
Enter a number: i am a potato
Enter a number: -7
Negative number -7 entered after 4 previous attempts
wim#wim-desktop:~$

Categories

Resources