Python Forum
Simple Python program not working
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple Python program not working
#1
Greetings,

Learning Python for the first time. Initial assignment: write a program that has a variable with a known numerical value, ask a user to guess that number, and tell the user if their guess matched the known value.

Here is what I coded:
def magic_number_guess():
	magic_number = 7
	user_guess = input("Please enter your Magic Number guess. ")
	print(magic_number)
	print(user_guess)
	if user_guess == magic_number:
	      print("Your guess is correct!")
	else:
	      print("Your guess was not correct. Please try again.")
Typical results:

>>> magic_number_guess()

Please enter your Magic Number guess. 8
7
8
Your guess was not correct. Please try again.
>>> magic_number_guess()

Please enter your Magic Number guess. 7
7
7
Your guess was not correct. Please try again.

No matter the value of user_guess, it seems that the if statement is never true: Your guess is correct! is never the result even when inputting 7.

I can go back and create simple if/elif/else or if/else statements that work as expected. But in the case of the code above, not so much.

What am I doing incorrectly/not accounting for?

Thanks.
Reply
#2
You need to convert user_guess to an int:
user_guess = int(input("Please enter your Magic Number guess. "))
Reply
#3
Thanks!. Your help and answer inspired me to investigate what was happening. Correct me if I am wrong, but the original line

user_guess = (input("Please enter your Magic Number guess. ")
resulted in user_guess holding a string. And comparing a numeric value with a string value will always(?) return false, right? Now with comparing an int to an int, the if statement is allowed to return what I needed.

Again, thanks for your help.
Reply
#4
Correct
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Using If Statements Instead of While Loop in Simple Game Program new_coder_231013 5 3,073 Dec-14-2021, 12:23 AM
Last Post: supuflounder
  Enigma Program not working properly npd29 3 2,037 May-01-2020, 10:37 AM
Last Post: pyzyx3qwerty
  Simple IF statement not working as intended gortexxx 2 2,743 May-17-2018, 07:54 PM
Last Post: gortexxx
  Simple Eight-Puzzle not working! BenjaminDJ 2 3,131 May-04-2018, 12:17 PM
Last Post: BenjaminDJ
  Supposedly simple program not working! Please help! BenjaminDJ 5 3,990 Feb-20-2018, 08:43 PM
Last Post: BenjaminDJ
  GTIN code validation program not working! AnonDxZ 1 2,757 Nov-29-2017, 11:25 PM
Last Post: Prrz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020