How to prevent infinite loop in Boolean while loop? - while-loop

I have code that goes like:
maybeYes = raw_input("Please enter Yes to continue.")
if maybeYes != "Yes":
print "Try again."
# ask for input again
else:
pass
What do I fill in where I want to make it ask for input again?

you should just do the raw_input directly in a loop.
while True:
result = raw_input("...")
if result != "Yes":
print "Try again."
continue
else:
break

This will loop printing wrong until the user types yes, Yes, YEs, YES, yEs or yeS as the input is converted to all uppercase before checking against YES, then your code can continue on...
while raw_input("Please enter Yes to start: ").upper() != 'YES':
print 'Wrong'
print 'Correct'
#Carry on here
Output:
Please enter Yes to start: nowg
Wrong
Please enter Yes to start: wggwe
Wrong
Please enter Yes to start: Yes
Correct

It looks to me like you WANT an infinite loop here.
maybeYes = raw_input("Please enter Yes to continue.")
while maybeYes != "Yes":
maybeYes = raw_input("Please try again.")
However, you can always add a counter/escape.
maybeYes = raw_input("Please enter Yes to continue.")
attempts = 0
while maybeYes != "Yes" and attempts < 10:
maybeYes = raw_input("Please try again.")
attempts += 1

Related

How do I make this so that way whenever the user says no it will stop or terminate the program? Currently, it's not doing that

def Main():
global more
InitializeReport()
TeamCode()
more = input("Do you have more to enter?")
while (more != "N" or "No" or "n" or "no"):
ProcPlyr()
more = input("Do you have more to enter?")
CalcAvg()
DisplaySummary()
while (more == "N" or more == "No" or more == "n" or more =="no"):
exit()

Processing.org user input code error?

Could you help me find the error in my code.
import javax.swing.JOptionPane;
String mortgagetype;
mortgagetype = JOptionPane.showInputDialog("What type of mortgage do you desire? (open or closed, only)");
if (mortgagetype == "open" || mortgagetype == "closed") {
print("hello");
}
I want the program to print hello if the user inputs open or closed. However it doesn't and I don't know what the problem is.
Instead of using mortgagetype == "something" in the if statement, use mortgagetype.equals("something").

Lua script - Coding a scenario

Situation :
There are two sensors and I want to save the data of values of each sensor in the certain file..But it's not working. I am working on linux system and the file is still empty.
What's wrong with my code? any suggestion please?
my code is:
--Header file
require("TIMER")
require("TIMESTAMP")
require("ANALOG_IN")
function OnExit()
print("Exit code...do something")
end
function main()
timer = "TIMER"
local analogsensor_1 = "AIR_1"
local analogsensor_2 = "AIR_2"
local timestr = os.data("%Y-%m-%d %H:%M:%S")
-- open the file for writing binary data
local filehandle = io.open("collection_of_data.txt", "a")
while true do
valueOfSensor_1 = ANALOG_IN.readAnalogIn(analogsensor_1);
valueOfSensor_2 = ANALOG_IN.readAnalogIn(analogsensor_2);
if (valueOfSensor_1 > 0 and valueOfSensor_2 > 0) then
-- save values of sensors
filehandle:write(timestr, " -The Value of the Sensors: ", tostring(valueOfSensor_1), tostring(valueOfSensor_2)"\n");
end
TIMER.sleep(timer,500)
end
-- close the file
filehandle:close()
end
print("start main")
main()
I do not know what this libs realy do.
But this code is incorrect;
1) you do not close while statement.
if in real code you close it before filehandle:close() then try call filehandle:flush()
2) you forgot comma:
filehandle:write(timestr, " -The Value of the Sensors: ", tostring(valueOfSensor_1), tostring(valueOfSensor_2)"\n")
(it should seay something like attemt call a number value).
3) try print out valueOfSensor_1 and valueOfSensor_2 values. May be there no data.
Beside the typos pointed out by #moteus, shouldn't this:
if (valueOfSensor_1 and valueOfSensor_2 > 0) then
be like this?
if (valueOfSensor_1 > 0 and valueOfSensor_2 > 0) then
Edit, in response to your comment to another answer:
still error..it says "attempt to call field 'data' (a nil value)
I can't be sure without the stack trace, but, most likely, something bad happens in the ANALOG_IN library code. You may not be using it properly.
try to turn this:
valueOfSensor_1 = ANALOG_IN.readAnalogIn(analogsensor_1);
valueOfSensor_2 = ANALOG_IN.readAnalogIn(analogsensor_2);
into this:
success, valueOfSensor_1 = pcall(ANALOG_IN.readAnalogIn, analogsensor_1);
if not success then
print("Warning: error reading the value of sensor 1:\n"..valueOfSensor_1)
valueOfSensor_1 = 0
end
success, valueOfSensor_2 = pcall(ANALOG_IN.readAnalogIn, analogsensor_2);
if not success then
print("Warning: error reading the value of sensor 2:\n"..valueOfSensor_2)
valueOfSensor_2 = 0
end
If the failure in ANALOG_IN is not systematic, it will work around it. If the call fails systematically, you'll get a huge warning log, and an empty collection_of_data.txt.
Please note that ANALOG_IN is not a standard Lua library. You should check its documentation , and pay attention to the details of its usage.

User input after print

I'm trying to make a simple lua program that converts Fahrenheit to Celsius and kelvin and I don't know how to put an input command on the same line as a print line. Here's what I mean.
I want the program to display:
Fahrenheit = "Here's the user input"
I know how to make it say
Fahrenheit =
"User input"
I'm still a novice.
This is my code so far:
print("Fahrenheit = ") f = io.read() c = (5/9)*(f-32)
print("Celsius = "..c) k = c + 273 print("Kelvin = "..k)
Look into io.write() and io.read(). For instance, you could say:
io.write("Fahrenheit = ")
The write command writes output to the screen buffer, but doesn't add a newline. Similarly, read checks the latest input, and returns it.
For reference, I suggest this link from the tutorial.

python3 - data type of input()

I need to assign a user-provided integer value to an object. My format is as follows:
object = input("Please enter an integer")
The following print tests...
print(type(object))
print(object)
...return <class 'str'> and '1'. Is there a way to set the data type of 'object' to the data type of the user's input value? IOW, such that if object=1, type(object)=int? I know I can set the data type of an input to int using the following:
object = int(input("Please enter an integer"))
In this case, if the user does not provide an int, the console throws a traceback error and the program crashes. I would prefer to test whether the object is in fact an int; if not, use my program to print an error statement and recursively throw the previous prompt.
while True:
try:
object = int(input("Please enter an integer"))
break
except ValueError:
print("Invalid input. Please try again")
print(type(object))
print(object)
You can always catch a "traceback error" and substitute your own error handling.
user_input = input("Please enter an integer")
try:
user_number = int(user_input)
except ValueError:
print("You didn't enter an integer!")