Home > Enterprise >  I have a problrm with if statement and while loop and dictionary in python
I have a problrm with if statement and while loop and dictionary in python

Time:02-08

men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}


def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif r not in men:
        print('Sorry, the number is not found')
    elif r >= 11:
        while r >= 11:
            r = r   1 == 1
            print('This is invalid number')
mo()

I have problem in the elif. What I want is if I write more than 10 characters in the console, then the code will print 'This is invalid number'. But instead the code prints 'Sorry, the number is not found'.

Output:

Please Enter The Number: 111111111111111
Sorry, the number is not found

Process finished with exit code 0

enter image description here

CodePudding user response:

The answer posted by ksohan is correct, but there's a catch. What you want is if the number entered is greater than 10 characters, then console will print 'This is invalid number'. If you want to compare the length of characters then you should first typecast r variable to string and then compare its length with 10.

Try this:

men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}


def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif len(str(r)) > 10:
        print('This is invalid number')
    elif r not in men:
        print('Sorry, the number is not found')
mo()

CodePudding user response:

if / elif / else

runs until the first condition is met. in your case, the first condition met is r not in men

if(condition):
  do something
elif(condition):
  do something else
elif(condition):
  do something else
else:
  do something

You could re-order them, so that the length check happens before checking if it's in the dict.

CodePudding user response:

I am not sure why are you using while loop and r = r 1 == 1 in your code. But I guess you want something like this:

men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}


def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif len(str(r)) >= 11:
        print('This is invalid number')
    elif r not in men:
        print('Sorry, the number is not found')
mo()

  •  Tags:  
  • Related