How to use do/while? [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Python: How to keep repeating a program until a specific input is obtained? [duplicate]
(4 answers)
Closed 3 years ago.
I want to get a user input which is bigger than zero. If user enters anything else than a positive integer prompt him the message again until he does.
x = input("Enter a number:")
y= int(x)
while y<0:
input("Enter a number:")
if not y<0:
break
If I add a bad value first then a good one it just keeps asking for a new one. Like Try -2 it asks again but then I give 2 and its still asking. Why?

The first time you assign the result of input to x, and convert x to a number (int(x)) but after the second call to input you don't. That is your bug.
That you have a chance to get this bug is because your code has to repeat the same thing twice (call input and convert the result to a number). This is caused by the fact that Python unfortunately does not have the do/while construct, as you mentioned (because there was no good way to use define it using indentation and Python's simple parser, and now it's too late).
The usual way is to use while True with break:
while True:
x = input("Enter a number:")
y = int(x)
if not y<0:
break

You assign a value to y before the while loop, then you enter the loop without assigning a value to y from the input.
Just change your code:
x = input("Enter a number:")
y= int(x)
while y<0:
y = int(input("Enter a number:"))
print('out?')

Related

I need python to to check if variable is an integer using the input() command [duplicate]

This question already has answers here:
Python check for integer input
(3 answers)
Closed 1 year ago.
I need python to check if a variable is an integer or not, then act accordingly.
Here is the pertinent code:
def data_grab():
global fl_count #forklift count
print("How many Heavy-lift forklifts can you replace?\n\n"
"Please note: Only forklifts that have greater than 8,000 lbs. of lift capacity will qualify for this incentive.\n"
"**Forklifts do NOT need to be located at a port or airport to be eligible.**")
forklift_count = input("Enter in # of forklifts:")
if type(forklift_count) is int:
fl_count = forklift_count
else:
print("Invalid number. Please try again.")
data_grab()
Currently, when the user actually types in an integer, it will automatically jump to ELSE instead of executing the code under IF.
Any thoughts?
Try the str.isdigit() method:
forklift_count = input("Enter in # of forklifts:")
if forklift_count.isdigit():
# Use int(forklift_count) to convert type to integer as pointed out by #MattDMo
fl_count = forklift_count
else:
print("Invalid number. Please try again.")
From the documentation:
str.isdigit()
Return True if all characters in the string are digits and there is at least one character, False otherwise.
A beginner/possibly incomplete answer here, but you could wrap the input() with int().
forklift_count = int(input("Enter in # of forklifts:"))
input() returns a string so even if you enter an int it will treat as string unless you convert it.

isinstance() not working the way I think it should [duplicate]

This question already has answers here:
Read an integer list from single line input along with a range using list comprehension in Python 3
(2 answers)
Closed 3 years ago.
My program requires a user input of a list of two elements, so to check if those conditions are satisfied I used the following code:
start = input('Enter you start location.\nE.g. Enter "[2,5]" for x-coordinate 2 and y-coordinate
5.')
while isinstance(start, list) == False or len(start) != 2:
start = input('Try again.')
This will never exit the while loop no matter what I input. Why?
Because your start variable turns out to be a string:start = "[2,5]", which is not a list. You can ask the user to input e.g 2,3,
then you get "2,3". You then can split it to a list using start.split(',')
Absolutely not recommanded for obvious security risk, but you can use eval.
start = eval(input('Enter you start location.\nE.g. Enter "[2,5]" for x-coordinate 2 and y-coordinate 5.'))
A prefered way is by using split, but in this case ask the user to enter coordinate separated by a coma.
start = input('Enter you start location.\nE.g. Enter "2,5" for x-coordinate 2 and y-coordinate 5.')
start = start.split(",")
Edit as recommanded by #soyapencil comments
inp_str = input('Enter you start location.\nE.g. Enter "[2,5]" for x-coordinate 2 and y-coordinate 5.')
start = [int(i) for i in iter(eval(inp_str,{}))]

Python not give the proper return value [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 3 years ago.
I'm writing a program that ask for users input and check if it is an integer. If yes than it converts it into an integer and return with the value. If the user typed something which isn't a number than the program ask the user again to input a number. If the user press only an enter and keep the input empty than it will return with a default value.
def inputNumber(message):
number = input(message)
if number !='':
if number.isdigit():
number = int(number)
return number
else:
print("This is not a whole number! Try again.")
inputNumber(message)
else:
number = int(1000)
return number
The program works well until I write a letter. If I write for example 'x' than it will say try again:
Max cooldown(secs): x
This is not a whole number! Try again.
Max cooldown(secs):
But if I press an enter with empty input it will not return with the default value but with None. It is only happens when I make an error with writing a letter.
You recursively call inputNumber in the case of an input that is not a digit ... and in that condition you should be using:
return inputNumber(message)

Everything appears to be defined as a string? Python [duplicate]

This question already has answers here:
Specify input() type in Python?
(2 answers)
Closed 4 years ago.
I am completely new to programming. However, I just wanna write a simple bit of code on Python, that allows me to input any data and the type of the data is relayed or 'printed' back at me.
The current script I have is:
x = input()
print(x)
print(type(x))
However, regardless of i input a string, integer or float it will always print string? Any suggestions?
In Python input always returns a string.
If you want to consider it as an int you have to convert it.
num = int(input('Choose a number: '))
print(num, type(num))
If you aren't sure of the type you can do:
num = input('Choose a number: ')
try:
num = int(num)
except:
pass
print(num, type(num))
1111 or 1.10 are valid strings
If the user presses the "1" key four times and then Enter, there's no magic way to tell if they wanted to enter the number 1111 or the string "1111". The input function gives your program the arbitrary textual data entered by user as a string, and it's up to you to interpret it however you wish.
If you want different treatment for data in particular format (e.g. if they enter "1111" do something with it as a number 1111, and if they enter "111x" show a message "please enter a valid number") then your program needs to implement that logic.

Python 3.6 validating an integer input [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I am using Python 3.6 currently and my code currently is asking a user to input 2 integers and convert them into binary form, this is not a problem, the issue that I have is when it asks the user to input a number, if they put anything other than an integer, it will break the code and come up with an error, is there a specific few lines of code that will ensure that errors will not display if letters or floats are inputted?
def add():
Num1 = int(input("Input the first number between 0 and 255, the calculated answer must not be above 255: "))
Num2 = int(input("Input the second number between 0 and 255, the calculated answer must not be above 255: "))
I have tried one method which was:
if type(Num1) != int:
print("Please input a number")
add()
However I still get errors when testing the code.
I would like the code to detect that a string or float has been inputted, then reload the "def" function without giving a syntax error.
This is the print result:
This is the gist of how to get an integer from the command line. It works using a while loop and try/except statements. You can add the checks for the integer range. You can use this code to create a function, which can be called twice for your particular problem.
n = None
while True:
n = input('enter an integer')
try:
n = int(n)
break
except:
continue

Categories