Error with if statement and multiple conditions - python

I'm having a problem with if statement that's checking if input is correct.
It when I input M or F it prints out "Wrong input" and I don't understand it very clearly.
def check(aw,iw):
if abs(aw-iw)<5 :
print "Your weight is normal."
elif abs(aw-iw)>5 and abs(aw-iw)<15 :
print "Your weight is about normal."
else:
print "Your weight is not normal."
return
print "Enter your gender (M/F)"
gender=raw_input()
if gender!='M' or gender!='F':
print "Wrong input."
else:
if gender=='M':
w=raw_input("Enter your weight (kg) :")
h=raw_input("Enter your height (cm) :")
idw=110-h
check(w,idw)
else:
w = raw_input("Enter your weight (kg) :")
h = raw_input("Enter your height (cm) :")
idw = 110 - h
check(w, idw)

Every input is either not equal to M or not equal to F (e.g., M is not equal to F). Instead you need to check if your input is not equal to M and not equal to F:
if gender != 'M' and gender != 'F':
# Here ------^
print "Wrong input."
Or, more elegantly, use the not in operator:
if gender not in ('M', 'F'):
print "Wrong input."

This line is incorrect:
if gender!='M' or gender!='F':
It will always resolve to False since gender can never be both M and F.
You can use in instead:
if gender in ('M', 'F'):
Alternatively:
if (gender != 'M') and (gender != 'F'):
Also, remove the line gender=int(gender): it should always fail.

I hope you have already got your answer in the previous answers to your question. i would just like to add the fact you appreciate some visualizations to the simple problem that you have faced but very delicate one for every beginner.
You have or doing this-
when you write
M
python checks if
M is !=(not equal to) M
but M is equal to M. so it results in false and then checks if
M != F
and sees its true. The or operation thus does the following-
true + true = true
true + false= true
false + true = true ....... this one
false + false = false
As your one resembles the 3rd one it returns true and python says "wrong input".
if you write and then it goes something like-
is
M!=M
returns false, and
M!=F
returns true.
In and its like-
true + true= true
true + false= false
false + true= false
false + false= false
So python returns false for the if statement and follows what you want it to do in the next lines of code. I hope it makes it very clear.
And remove gender=int(gender) its not necessary because python can recognize M and F as char and you need not turn it into integer value or ascii here.

Remove the line
gender=int(gender)
and make changes to
if gender!='M' or gender!='F':
as
if gender!='M' and gender!='F':

Also, you should use <= to include limits in your evaluation.
def check(aw,iw):
if abs(aw-iw)<=5 :
print "Your weight is normal."
You can shorten elif abs(aw-iw)>5 and abs(aw-iw)<15:, since if abs(aw-iw)<5 is not true, then it will always be higher than 5.
#Instead of elif abs(aw-iw)>5 and abs(aw-iw)<15:
elif abs(aw-iw)<=15:
print "Your weight is about normal."
else:
print "Your weight is not normal."
return
Instead of:
print "Enter your gender (M/F)"
gender=raw_input()
gender=int(gender)
You should use:
gender = raw_input('Enter yor gender (M/F)')
Where int(gender) would cause an error, since the input you want from gender=raw_input() gives a string in letters.
You should change that or for an and, since if using or, if your input is 'M', then gender != 'F' will give True and it will run the if condition.
#Instead of if gender!='M' or gender!='F':
if gender!='M' and gender!='F':
print "Wrong input."
Here you should use int(raw_input()) for your variables to be evaluated as integers and be able to add or subtract them. And since you are doing the same code wether it's M or F, there is no need to write another if: else: condition.
else:
w = int(raw_input("Enter your weight (kg) :"))
h = int(raw_input("Enter your height (cm) :"))
idw = 110 - h
check(w, idw)

Related

How can i search variables using input in this code? in python

i want to search variable using input .
found = False
number = [1,2,3,4,5,6,7,8,9,]
for value in number :
if value == 3 :
found = True
print(found)
If you want to get a value using input() and check if the value is in a list, you can do it like this:
value = int(input())
found = False
number = [1,2,3,4,5,6,7,8,9,]
result = value in number
print(result)
You can do something like:
value = int(input("Insert a value: "))
found = False
number = [1,2,3,4,5,6,7,8,9]
for i in number:
if i == value :
found = True
break
print(found)
The method used by #SangkeunPark is more efficient, but it can be done with your program with a simple change:
found = False
a = int(input())
number = [1,2,3,4,5,6,7,8,9,]
for value in number :
if value == a :
found = True
print(found)
n=int(input('Enter a value:'))
number = [1,2,3,4,5,6,7,8,9]
if n in number:
print(True)
else:
print(False)
Alright so first we are going to make the variables (just like you had in your code)
found = False
number = [1,2,3,4,5,6,7,8,9]
now we will add an input command and store the respective value in variable called 'value'
value = int(input("Enter your number: "))
Now to check if the user's value is in our list or not, we are going to iterate through the list and in every iteration we will check if the value user entered appears to be in the list, if it does we will just set the 'found' variable to True
for values in number:
if values == value :
found = True
break
if found:
print("number found")
else:
print("number not found")
Now here you can use both "in" and "=="
but since we are just checking the numbers in this particular piece of code, == is fine!
check out this
for more info about in and ==

Check input decimal number

I want to check if the input is a number(float with 0,one or two decimals) and greater than 0
def getnumber():
print ( "write a number: \n")
isValid = False
while not isValid:
try:
number = float(raw_input().replace(",","."))
if number >= 0:
isValid=True
else:
print ("Number not valid")
isValid = False
getnumber()
except:
print ("Number not valid")
return number
I have the following problems:
1- I don't know how to check if there are only two decimals
2- The code doesn't return the number if first I introduce a negative number
Does anyone know how to fix it?
Thanks a lot
The reason why your code isn't working with negative numbers is because the function calls itself recursively when the number is negative, but the value of isValid is always false after that call, so the loop repeats.
There isn't really any need for the Boolean variable.
That leaves you with the issue of detecting two decimal places. In order to be able to do that at string level you would have to retain the string that you converted to a floating-point number. Supposing you store it as s you could use some test like len(s) > 3 and s[-3] == '.'` to verify it.
This would give you a solution like:
def getnumber():
while True:
try:
s = raw_input("Write a number:").replace(",",".")
number = float(s)
if number >= 0 and len(s) > 3 and s[-3] ==".":
return number
else:
print("Negative or not two decimal places")
except Exception:
print("Invalid number")
print(getnumber())

Python3x Integer and String Input

I want the user to input a number
Give a number : he types "10" -but...
Give a number : he types "I want to type 10"
i want the program to just "count" the integer. Because if he types a string the program will stop
import random
goal = random.randrange(1,10)
n = 1
tries = 0
name = input("Dose to onoma sou ")
print("A game in Python")
while n != 0 :
value = int(input("madepse poio einai to noumero:"))
n = abs(value - goal)
print(value,n)
tries = tries + 1
if n >= 4 :
print("den eisai koda")
elif n > 0 and n <= 3 :
print("eisai koda")
else :
print("to vrikes")
print ("to score sou einai: ",tries)
skoros = str(tries)
score = open('score.txt', 'a')
score.write(name)
score.write(' ')
score.write(skoros)
score.write("\n")
score.close
This will take any input and pull the first number out of it. \d matches any digit 0-9, and + means "one or more".
import re
while True:
user = input('Enter a number: ')
match = re.search(r'\d+',user)
if match:
value = int(match.group(0))
break
else:
print("I didn't see a number in that response.")
print(value)
Well, you could just manually loop through the string and store the position of the number using isdigit().
The following approach expects the number to be the only one in the string (multi digit allowed):
start = None
stop = None
for i in range(len(input)):
c = input[i]
if c.isdigit():
if start == None:
start = i
stop = i
try:
number = int(input[start:stop])
catch:
print("invalid input")
EDIT:
I guess there would be some nice and easy Regex solution, but I'll leave my hands off of it, as I am not too experienced with it...

the if-else ladder gets terminated

I tried of making and Celcius to Faharanite converter and visa-versa.
I made extra if-else ladder to ensure that the user doesn't get stuck and when the user enters something wrong.
But i tried compiling this after the first statement gets terminated.
ch = raw_input("""What you want to convert :
1) Celcius to Faharanite.
2) Faharanite to Celcius.\n""")
if (type(ch)==int):
if (ch==1):
cel=raw_input("Enter to temperature in Celeius : ")
if (type(cel)!='float'):
cel = 1.8*(cel+32)
print "The Conversion is :" + cel
else :
print "YOu should enter values in numeric form"
elif (ch==2):
fara=raw_input("Enter to temperature in Faharanite : ")
if (type(fara)==float):
print "The Conversion is :" + 1.8*(fara-32)
else :
print "YOu should enter values in numeric form"
else :
print "Wrong choice"
Because the first if statement is never true. The result of raw_input is always a string.
devnull's comment suggesting adding ch = int(ch) will work as long as the user input is a number.
For more robust handling, I would do something like:
is_valid = False
while not is_valid:
ch = raw_input("""What you want to convert :
1) Celsius to Fahrenheit.
2) Fahrenheit to Celsius.\n""")
try:
ch = int(ch) # Throws exception if ch cannot be converted to int
if ch in [1, 2]: # ch is an int; is it one we want?
is_valid = True # Don't need to repeat the while-loop
except: # Could not convert ch to int
print "Invalid response."
# The rest of your program...
which will continue to to prompt the user until they enter a valid choice.
Note that you'll have to use a similar try/except construct to parse the temperature-to-convert into a float (with the float() method).

How to allow input only string value of "stop", "", then check and convert to float

Hi I am having trouble with the end of my loop. I need to accept the input as a string to get the "stop" or the "" but I don't need any other string inputs. Inputs are converted to float and then added to a list but if the user types "bob" I get the conversion error, and I cant set the input(float) because then I can't accept "stop".
Full current code is below.
My current thinking is as follows:
check for "stop, ""
check if the input is a float.
if its not 1 or 2, then ask for a valid input.
Any ideas please? If its something simple just point me in the direction and i'll try churn it out. Otherwise...
Thanks
# Write a progam that accepts an unlimited number of input as integers or floating point.
# The input ends either with a blank line or the word "stop".
mylist = []
g = 0
total = 0
avg = 0
def calc():
total = sum(mylist);
avg = total / len(mylist);
print("\n");
print ("Original list input: " + str(mylist))
print ("Ascending list: " + str(sorted(mylist)))
print ("Number of items in list: " + str(len(mylist)))
print ("Total: " + str(total))
print ("Average: " + str(avg))
while g != "stop":
g = input()
g = g.strip() # Strip extra spaces from input.
g = g.lower() # Change input to lowercase to handle string exceptions.
if g == ("stop") or g == (""):
print ("You typed stop or pressed enter") # note for testing
calc() # call calculations function here
break
# isolate any other inputs below here ????? ---------------------------------------------
while g != float(input()):
print ("not a valid input")
mylist.append(float(g))
I think the pythonic way would be something like:
def calc(mylist): # note the argument
total = sum(mylist)
avg = total / len(mylist) # no need for semicolons
print('\n', "Original list input:", mylist)
print("Ascending list:", sorted(mylist))
print ("Number of items in list:", len(mylist))
print ("Total:", total)
print ("Average:", avg)
mylist = []
while True:
inp = input()
try:
mylist.append(float(inp))
except ValueError:
if inp in {'', 'stop'}:
calc(mylist)
print('Quitting.')
break
else:
print('Invalid input.')

Categories

Resources