The following program uses {0} in a string, and I'm not sure how it works, it came up in an online tutorial about iteration for Python, and I can't seem to find anywhere explaining it.
import random
number = random.randint(1, 1000)
guesses = 0
print("I'm thinking of a number between 1 and 1000.")
while True:
guess = int(input("\nWhat do you think it is? "))
guesses += 1
if guess > number:
print("{0} is too high.".format(guess))
elif guess < number:
print("{0} is too low.".format(guess))
else:
break
print("\nCongratulations, you got it in {0} guesses!\n".format(guesses))
Thank you!
That is the new python formatting style. Read up on it here.
It's an indicator to the format method that you want it to be replaced by the first (index zero) parameter of format. (eg
"2 + 2 = {0}".format(4)
)It's a boon for placing same arg multiple times
Isn't this nice!!!
here I can place the
year
argument in multiple lines using.foramt(year)
output : Enter the year: 1996 1996 Year is Leap Year
AND Another ex:
output: my name is sagar. I am from hyd. Hope everyone doing Good OR
Output: my name is sagar. I am from hyd. Hope everyone doing Good
http://docs.python.org/release/3.1.3/library/stdtypes.html#str.format
It's a placeholder which will be replaced with the first argument to
format
in the result.{1}
would be the second argument and so on.See Format String Syntax for details.