Question

I'm sure this is kind of silly but I'm having trouble understanding strings, and the raw_input object.

So, example

print "How much money do I have?",
checking balance = raw_input()
savings balance = raw_input()
print "I have %r and %r in my accounts." % (1000, 10000)

So, I have a very basic understanding of strings, but I don't really understand what's going on here. The raw input is just displaying a string of data that I define elsewhere in the program? and The "%r" just displays this? I don't understand how it's different from me using %s and defining my numbers there. I'm just very confused! Any explanation would help me.

Was it helpful?

Solution

Here is what each line in your program does:

  1. print out a message;
  2. SyntaxError (due to space in variable name);
  3. SyntaxError (ditto); and
  4. print two numbers unrelated to the raw_input you just tried to take.

Instead, you need something like:

print "How much money do I have?",
checking_balance = float(raw_input())
savings_balance = float(raw_input())
print "I have %.2f and %.2f in my accounts." % (checking_balance, savings_balance)

What this does:

  1. print again
  2. Take input, convert to float, and store as checking_balance;
  3. As above, with savings_balance; and
  4. print the numbers you just inputted, formatted to two decimal places.

(Note: more modern Python would make the last line:

print("I have {0:.2f} and {1:.2f} in my accounts.".format(checking_balance, savings_balance))

)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top