0

Here is my code:

spam = input()


if spam == 1:
 print("Hello Word")
if spam == 2:
 print("Howdy")
else:
 print("Greetings")
    

#Task if spam == 1 then print Hello World if spam == 2 print Howdy and if
#anything else print greeetings

However my code is printing greetings on any input.

jaabh
  • 815
  • 6
  • 22

6 Answers6

1

Since input() accepts string, you could cast the variable into an int to compare:

spam = input()

if int(spam) == 1:
    print("Hello World")
elif int(spam) == 2:
    print("Howdy")
else:
    print("Greetings")
jaabh
  • 815
  • 6
  • 22
0

try using elif (else if)

spam = input()


if spam == '1':
 print("Hello Word")
elif spam == '2':
 print("Howdy")
else:
 print("Greetings")
Barzuka
  • 41
  • 1
  • 6
0

Your input is formatted as a string, you have to convert it to an int with int().

bests

QLR
  • 1
  • 3
0

Change the second if to elif. The then sequence should operate as expected.

acrobat
  • 812
  • 4
  • 7
0

you are checking if it's equal to a number not a string; input returns a string not a number.

you can fix this in two ways:

  1. change the statement to be spam == "1"

  2. change spam = int(input())

Ruli
  • 2,592
  • 12
  • 30
  • 40
Proodle
  • 51
  • 5
0

The input you are asking the user is of type integer, but the default input type is string this can be checked by

type(spam)

what you want to do is

spam = int(input())
if spam == 1:
    print("Hello Word")
elif spam == 2:
    print("Howdy")
else:
    print("Greetings")
Kapil
  • 165
  • 1
  • 9