Python Forum
John Guttag Book - Finger Exercise 4 - need help to make the code better
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
John Guttag Book - Finger Exercise 4 - need help to make the code better
#11
Hi. I have also been practicing this question from John Guttag's Book. This was the code that I wrote

Counter = 1 #For the while loop
Odd_Number = 0 #Keeps track of the largest odd number
Even_Number = 0 #Keeps track of the largest even number 

while (Counter <= 10):
    New_Int = int(input ('Enter integer: ')) #Integer entered by the user
    if  (New_Int%2 != 0) and (New_Int > Odd_Number) and (New_Int > Even_Number): #For postive odd numbers
        Odd_Number = New_Int
        Counter = Counter + 1
    elif (New_Int%2 != 0) and (New_Int < Odd_Number) and (New_Int < abs(Even_Number)): #For negative odd numbers
        Odd_Number = New_Int
        Counter = Counter + 1
    elif (New_Int%2 == 0) and (New_Int > Even_Number):
        Even_Number = New_Int
        Counter = Counter + 1
    else:
        Even_Number = New_Int
        Counter = Counter + 1

if Odd_Number == 0:
    print ("No odd numbers")
else:
    print ('Largest odd number is ' + str(Odd_Number))
The code seems to work fine but I'd like to know whether I can trim it down. Also, I feel like I can cut down on some of the sections.
Reply
#12
why are you answering posts that are two years old?
Reply
#13
my solution to the problem
num = 0
# user enters the numbers and if its odd and greater than num variable, 
# it assigns value to num 
# 
for i in range (1, 11):
    num2 = int(input("enter the no.:"))
    if num2 % 2 == 1 and num2 > num:
        num = num2
# if no odd num ber was entered and value of num did  not change
if num == 0:
    print("no odd no. was entered")
else:
    print("the largest odd number entered is :", num)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  py4e book exercise not working when compiled adriand 11 8,919 Jul-01-2020, 08:42 AM
Last Post: tawhidbd1248
  [split] help me make this code better please (basic) Rustam 2 2,264 Jun-19-2020, 01:27 PM
Last Post: Rustam
  How to make this dictionary-generating code more efficient? Mark17 4 2,378 Oct-08-2019, 07:42 PM
Last Post: Mark17
  Book exercise in lists sonedap 17 7,057 Feb-03-2019, 08:37 PM
Last Post: ichabod801
  Creating code to make up to 4 turtle move simultaneously in a random heading J0k3r 3 5,488 Mar-05-2018, 03:48 PM
Last Post: mpd
  How to make faster this code Ace 1 2,966 Oct-23-2017, 12:11 PM
Last Post: Larz60+
  How can I make faster that code BlueEva00 1 2,695 Oct-18-2017, 03:51 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020