1

I'm learning about functions in Python 2.7.x and one of the suggestions in the book I am using is to solicit input from a user to get values for the script. The advice on how to use raw_input in a function is as follows:

You need to use int() to convert what you get from raw_input()

I'm not sure how to use int() yet. This is what I have tried so far:

def cheeses_and_crackers(cheeses, crackers):
    print "You have %d types of cheeses." % cheeses
    print "You have %d types of crackers." % crackers
    print "That is a lot of cheese and crackers!\n"

print "How many cheeses do you have?"
cheeses1 = raw_input("> ")
int(cheeses1)

print "How many types of crackers do you have?"
crackers1 = raw_input("> ")
int(crackers1)

cheeses_and_crackers(cheeses1, crackers1)

The error I get when I try run this is as follows:

TypeError: %d format: a number is required, not str

I'm guessing how to use int() so I'd appreciate some help with basic syntax too.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Paul Jacobson
  • 85
  • 1
  • 10
  • 1
    `cheeses1 = int(raw_input("> "))` – Yevhen Kuzmovych May 05 '17 at 12:13
  • You have to store after you call `int()`. Like `cheeses1 = int(cheeses1)` – kuro May 05 '17 at 12:13
  • You can use `int(raw_input("> "))` that way your imput is converted to a int immediatly. You must also think about user not giving a correct fromat, ie a string instead of an int so use a try /catch – Ludisposed May 05 '17 at 12:13
  • *"Some of the answers do address my question"* - then it's a duplicate as far as SO is concerned; it's all about finding people the right *answers*. You're simply not assigning the return value of `int`. – jonrsharpe May 05 '17 at 12:40
  • It was flagged as a duplicate question. My question is not the same as the referenced question. It is not a duplicate. I searched a couple times for similar questions before I asked and referencing the other question is certainly helpful but simply flagging my question as a duplicate isn't helpful. – Paul Jacobson May 05 '17 at 12:43

1 Answers1

0

int does not mutate the user input (a string, which is in fact immutable), but constructs an integer and then returns it.

Since you don't assign any name to the return value, it is lost.

Demo:

>>> user_input = raw_input('input integer > ')
input integer > 5
>>> type(user_input)
<type 'str'>
>>> input_as_int = int(user_input)
>>> input_as_int
5
>>> type(input_as_int)
<type 'int'>
>>> type(user_input) # no change here
<type 'str'>
timgeb
  • 76,762
  • 20
  • 123
  • 145