Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Booleans in Python
#1
Hi all,

I am trying to understand how to code the exercise shown below but I am afraid I am stuck.
I guess I am still a newbie in Python.
Can someone please explain to me this exercise?
I cannot provide any code since I don't even know how to start it.

Write a python program that will return a Boolean value that will allow the program to continue The program then requests a number upon which the program responds whether it is odd or even. Essentially we wish to continue entering until we (i.e. the user) is finished. See sample run below:

Run

Please enter a number: ? 5
The number you entered is odd
Another number: ? y
Please enter a number: ? 90
The number you entered is even
Another number: ? Y
Please enter a number: ? 43
The number you entered is odd

Kind regards,

Azure
Reply
#2
Use input()
Reply
#3
(Apr-22-2020, 08:10 AM)anbu23 Wrote: Use input()

Hi Ambu23,

This is the code I used, however, I am not sure if this is the right answer though.

number = int(input("Please introduce a string: "))

while number%2 != 0:

print("The number you entered is odd")

number = str(input("Another number? "))

if number == "y":

number = int(input("Please enter a number: "))

number%2 == 0

print("The number you entered is even")

endif

break:

Is this method correct?
Reply
#4
Output of input() is of string type. So no need to use str(). This code will exit loop when you enter other than Y for input('Another number? ')

while True:
  num = int(input('Please enter a number: '))
  print('Number you entered is ' + ('even' if num%2 == 0 else 'odd'))
  proceed = input('Another number? ')
  if proceed.upper() != 'Y':
      break
Reply
#5
(Apr-22-2020, 09:25 AM)anbu23 Wrote: Output of input() is of string type. So no need to use str(). This code will exit loop when you enter other than Y for input('Another number? ')

while True:
  num = int(input('Please enter a number: '))
  print('Number you entered is ' + ('even' if num%2 == 0 else 'odd'))
  proceed = input('Another number? ')
  if proceed.upper() != 'Y':
      break

Thank you so much Anbu23!
Reply
#6
Just for fun:

>>> for num in range(5):
...     print(f"{num} is {['odd', 'even'][num % 2 == 0]}")
... 
0 is even
1 is odd
2 is even
3 is odd
4 is even
>>> 
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
(Apr-22-2020, 02:16 PM)perfringo Wrote: Just for fun:

>>> for num in range(5):
...     print(f"{num} is {['odd', 'even'][num % 2 == 0]}")
... 
0 is even
1 is odd
2 is even
3 is odd
4 is even
>>> 

Thank you so much!
Reply


Forum Jump:

User Panel Messages

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