Screen Link:
My Code:
capitals = {'France':'Paris','Spain':'Madrid','United Kingdom':'London',
'India':'New Delhi','United States':'Washington DC','Italy':'Rome',
'Denmark':'Copenhagen','Germany':'Berlin','Greece':'Athens',
'Bulgaria':'Sofia','Ireland':'Dublin','Mexico':'Mexico City'
}
user_input = input('Please enter a country:> ')
user_input = input('Please enter capital:> ')
if user_input == str('country') is str:
print('country name')
elif user_input == str('capital') is str:
print('capital name')
else:
print('please choose country or capital')
What I expected to happen:
The Else statement “Please choose country or capital” would happen if I didn’t put a country or a capital name in the browser
What actually happened:
'please choose country or capital' came after entering any of the capitals
There are several problems with your code.
-
user_input = input('Please enter a country:> ')
user_input = input('Please enter capital:> ')
The two inputs are assigned to variables with the same name. So the second input overwrites the first.
str('country')
Notice that country
is already a string because it is between ' '
. So you are transforming a string into a string. It does not raise an error but it makes no sense. Also, if you ran str(country)
(without the ' '
), you’d get an error since country
is not defined in your code.
str('country') is str
The above expression returns a boolean. If str('country')
is string it returns True
, if not it returns False
. In this case, it will always return True
. Therefore, if user_input == str('country') is str:
is the same as if user_input == True:
and so the if
statement will never return True
, which means print('country name')
will never be accessed.
But even if print('country name')
was accessed, it would just print the string country name
because it is between ' '
, which makes it a string. And if you use str(country name)
(without the ' '
), you’ll get an error since country name
is not defined in your code.
These exactly three errors also happen in the following part:
elif user_input == str('capital') is str:
print('capital name')
So, what you have is:
-
if user_input == True
-> this is false, so python will move on to the elif
clause;
-
elif user_input == True
-> this is false too, so python will move on to the else
clause;
-
The else
clause finally prints the string you see, 'please choose country or capital'
.
There is a lot to fix in your code. I hope this can help you do it.
1 Like