Nicholas
Nicholas

Reputation: 1

I am trying to use an if statement in python to display a dictionary but it skips straight to the else block

Database = {"name" : "Nicholas"}
Print ("welcome to database\n")
Print ("Enter 1 to display database\n")
Print ("Enter 2 to delete database\n")
X = input("make entry here:")

if x == 1:
    Print(database)
else:
    Print(" error")

Upvotes: 0

Views: 49

Answers (5)

kadina
kadina

Reputation: 5376

Couple of issues.

  1. input function always returns string. You need to convert into int like

    x = int(input("make entry here !!"))
    
  2. You are storing return value of input() in 'X' but if condition is checking 'x' value which is wrong. Python is case sensitive.

Upvotes: 0

Prashin Jeevaganth
Prashin Jeevaganth

Reputation: 1343

On top of the typo errors that are present in your code involving capitalization of print and variable names, even after you fix the syntax errors, the control flow of the code will still not go to the if branch. This is because input method in Python will store a string value into variable x, even if the user input is 1. Since 1 == “1” leads to false, you will always get to the else branch.

Here is a way to get the control flow of the code to pass through the if branch, after all the syntax errors are fixed.

Database = {"name" : "Nicholas"}
print ("welcome to database\n")
print ("Enter 1 to display database\n")
print ("Enter 2 to delete database\n")
x = input("make entry here:")

if x == "1":
    print(Database)
else:
    print(" error")

Upvotes: 2

marfer
marfer

Reputation: 1

You need to check against string, not int:

database = {"name" : "Nicholas"}
print ("welcome to database\n")
print ("Enter 1 to display database\n")
print ("Enter 2 to delete database\n")
x = input("make entry here:")

if x == "1":
    print(database)
else:
    print(" error")

Check it here: https://www.online-python.com/wbRd69MgYO

Upvotes: 0

Python is case sensitive, so here you defined capital X but you didn't x.

Upvotes: 0

Chris
Chris

Reputation: 23171

Your if statement is looking at x but your input is saved in a variable called X. Case matters.

Upvotes: 0

Related Questions