Discussion:
[Tutor] (no subject)
Job Hernandez
2015-07-25 01:49:26 UTC
Permalink
I have been reading a book on Python. I am currently stuck with one of
the exercises and so wanted to ask you if you can help me.
Of course, if you have the time.

Exercise : Ask the user to input 3 integers and prints out the largest odd
number. if no odd number was entered it should print a message o that
effect.


These lines of code don't work :

a = raw_input('enter number: ')
b = raw_input('enter number: ')
c = raw_input('enter number: ')


list = [ a, b, c]
list2 =[ ]

for x in list:
if x%2 == 1: # responsible for the type error: not all arguments
converted during string #
#formatting
list2.append(x)
print list2

w = max(list2)

print ' %d is the largest odd number.' % w
# i don't know but maybe I have to return the list for this to work?
Because if I assign a
#variable to to 3 integers, like the code below it works.
But these do:

a = 3
b = 7
c = 9


list = [ a, b, c]
list2 =[]

for x in list:
if x%2 == 1:
list2.append(x)
print list2

w = max(list2)

print ' %d is the largest odd number.' % w

#Thank you for your time.

Sincerely ,

Job
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Alan Gauld
2015-07-25 08:43:45 UTC
Permalink
Post by Job Hernandez
a = raw_input('enter number: ')
b = raw_input('enter number: ')
c = raw_input('enter number: ')
raw_input() returns a string. So if you enter 6,
say, it is stored as the character '6' not the
number 6. You need to use the int() function to
convert it to an integer or float() to convert
it to a floating point number. eg.

c = int(raw_input('enter number: '))
Post by Job Hernandez
list = [ a, b, c]
A small point: its not a good idea to use the
type name as your variable because that then
hides the function used to convert things to lists.
ie you can no longer do
Post by Job Hernandez
list('abc')
['a','b','c']

Its better to use names that describe the content
of the data, so in your case something like inputs
or numbers.

Just a small point which makes no difference in
this example but might trip you up in future.
Post by Job Hernandez
list2 =[ ]
if x%2 == 1: # responsible for the type error: not all arguments
You get the error because you are trying to divide
a character by a number. If you convert to int()
up above then it will go away.
Post by Job Hernandez
list2.append(x)
print list2
w = max(list2)
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Loading...