-4

I am learning Python and it is my first programming language. So I tried making a number guessing game where the goal is to guess a number that is within 1 and 100. Every time the player inputs a guess, the program will update the range of possibility. Example: the answer is 50, the player guess 40, then the program would prompt the player to guess a number between 40 and 100... until the player gets the number. Here is my working code:

ans=input('Please enter a number between 1 and 100: ')
guess=input('Please enter your guess: ')
low=1
upp=100
while guess!=ans:
 if ans>guess:
  low=int(guess)
 elif ans<guess:
  upp=int(guess)
 guess=input('The answer is between %d and ' %low + '%d' %upp)
else:
 print('You have guessed correctly!')

This code works as intended, however within the While loop for the assignments of variable 'low' and 'upp', the program would not work if I put 'upp=guess' instead. A TypeError would occur, and it seems like 'upp' (or 'low') has become a string instead of a number.

My question is how did the variable 'upp' become a string while the variable 'guess' is a number?

lizardfireman
  • 329
  • 3
  • 17
  • If you're running Python 3, `guess` is not a number. If you're running Py2, you should be using `raw_input` wrapped in `int` to avoid arbitrary code execution. Also, use string formatting properly, the whole point is to avoid tons of individual concatenations: `guess = input('The answer is between %d and %d' % (low, upp)) – ShadowRanger Jan 19 '17 at 08:01

2 Answers2

0

You can convert string to int and vice versa any time by :

string = "55"
integer = int(string)
print(integer)

Output: 55

integer = 55
string = str(integer)
print (string)

Output: "55"

Erik Šťastný
  • 1,487
  • 1
  • 15
  • 41
0

All data using the input function in python is by default interpreted as a string. In order to change it to an int, simply use int(guess), which is what you already are doing. It's just a little technicality in Python

Read this for more info:

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

https://docs.python.org/3/library/functions.html#input

Levi Muniz
  • 389
  • 3
  • 16