Multiple IF and ELIF conditionals [Python] - python

name="admin"
passw="aaa"
itemone="01"
itemtwo="02"
a=input("Enter your username:")
b=input("Enter your password:")
if(a==name)and(b==passw):
print("Welcome.")
c=int(input("Enter Item Code:"))
if(c==itemone):
print("Name: ID")
elif(c==itemtwo):
print("Name: Mirror")
else:
print("Item not found. Try again.")
else:
print("Username/Password is incorrect.")
exit()
when "01" or "02" is entered, the program ignores all the other codes and directs to "item not found. try again."
I finally got it to work! Thank you!!!

You are taking the input and casting it to an integer, then checking if it is equal to a string. This will return false. Example:
01=="01"
=> False
"01"=="01"
=> True
You don't need to cast the input to an integer.

As robert_x44 said, you are comparing an integer with a string.
Try:
itemone=01
itemtwo=02
Also, in your post the if blocks are not indented. It is probably just a formatting error, but python if statements must be indented.

Either change itemone and itemtwo to ints, or don't convert your input to an int. Right now you're comparing ints to strs, which won't work.
Pick one of the following two changes - don't make both or you'll just reverse the situation you're in now (comparing strs to ints instead of ints to strs.)
How to use just ints
Change:
itemone="01"
itemtwo="02"
to:
itemone=1
itemtwo=2
How to use just strs
Change:
c=int(input("Enter Item Code:"))
to:
c = input("Enter Item Code:")

Related

How to give user input in python3

n=input("enter the no:")
check(test_list,n)
def check(test_list,n):
for i in test_list:
if(i==n):
print("yes in a list")
continue
else:
continue
I had written the simple code to check if a no. exists in a list or not, but while taking user input I"m not getting any results after providing input value n.
Why is so?
In your code the first line should be corrected as n=int(input("enter the no:")).
In python it takes the inputs as strings. Think if you are giving the input as 3. Then the variable n stores the value "3"( not the value 3 ). You should need to know 3 == "3" is False.
Therefore, when you are taking the input you should convert that string input to the int. To do that we use int() method. The int() method converts the specified value into an integer number
n=int(input("enter the no:"))
check(test_list,n)
def check(test_list,n):
for i in test_list:
if(i==n):
print("yes in a list")
continue
else:
continue
You were not getting any results because the input() function always returns a string. For this reason, we need to convert it to an Integer before passing it on into the function, and I did with n=int(input()).
n=int(input("enter the no:"))
def check(test_list,n):
for i in test_list:
if(i==n):
print("yes in a list")
continue
else:
continue
check((1,2,3),n)

To check whether an entered value exists in a List

This is my simple code. When a User enters a value, it has to be compared with the list I have used and should return the output as required. But when I execute the code and enter a value that is a part of the list, it returns the print statement under the else construct. Please help me with your suggestions
mylist=[1,2,3]
print('Enter the Rank:')
x=input()
if x in mylist:
print('You have passed')
else:
print('Sorry you have failed')
The items in mylist are ints. Input returns a string, so to compare them you need to convert one of them.
Either
x = int(input())
or
if int(x) in mylist

Issue with trying to limit datatype inputs

Hello I have this issue with a function that I created in python:
def intcheck(num)
if isinstance(num, int):
return num
else:
intcheck(input("Invalid datatype: Input integer only: "))
It's supposed to check if the input is an integer, and if it isn't, ask the user for another input, then check that one, ect. ect.
However the code appears to get stuck on the else: statement such that even a correct input will not return, and it will just ask for another input indefinitely.
A simpler way is:
def is_int(foo):
try:
return int(foo)
except ValueError:
print('{} is not a number'.format(foo))
return is_int(input('Please enter a number: '))
If you are on Python 2, make sure you use raw_input instead of input.
If you're using Python 3.x, input() returns a string, so you have to convert it to an int. If you're using Python 2.x, you really should be using raw_input() instead (Python 2.x input() is very unsafe), and since raw_input() is the same as Python 3.x input(), you also have to convert the string to an int.
In both case, you need to return the result of the recursive call in the else clause as shown in other answers.
Now using recursion this way, while possibly "elegant", is not the simplest solution - a good old while loop works as fine and avoids stacking frames (Python don't do tail-recursion optimisation):
def checkint():
while True:
num = input("your prompt here")
try:
return int(num)
except ValueError:
print "'{}' is not a valid integer".format(num)
You've forgotten that the input function returns a str object! So, you loop forever in the else of the intcheck function. Instead, you could do that:
def intcheck(num):
if isinstance(num, int):
return num
else:
input_string = input("Invalid datatype: Input integer only: ")
try:
input_int = int(input_string)
except ValueError:
input_int = input_string
finally:
intcheck(input_int)
Input in Python is always loaded as a string, so firstly, you need to convert the input into one. Elegant way is to check it with exceptions: if it is int, return it, and if not, ask for another input.
def intcheck(num):
try:
return int(num)
except ValueError:
return intcheck(input("That is not a integer, please enter integer: "))

Else is being displayed even if correct

I've been having a problem in my multiplication game where else would be displayed even if the answer was correct.
Here is a sample of the code:
for num in range(0,1):
number1 = random.randint(2,5)
number2 = random.randint(2,5)
answer = number1*number2
guess = input("What is %d x %d? " % (number1, number2))
if guess == answer:
print('Correct')
else:
print('Incorrect')
In Python 3.x, Input returns a str, vs. in Python 2.x where it attempted to evaluate the input as python code. And str == int always returns False, and doesn't throw an exception. You'd need to change your code to:
if guess == str(answer):
if you'd like to avoid throwing exceptions if the input isn't actually a number, or
gess = int(input(...))
if you intend to actually use guess as a number later on, but will then have to handle what happens if the user enters not a number.

How to add up a variable?

I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)

Categories