1

I am working through some exercises on python and my task is to create a program that can take a number, divide it by 2 if it is an even number. Or it will take the number, multiply it by 3, then add 1. It should ask for an input and afterwards it should wait for another input.

My code looks like this, mind you I am new to all this.

print('Please enter a number:')

def numberCheck(c):
    if c % 2 == 0:
        print(c // 2)
    elif c % 2 == 1:
        print(3 * c + 1)

c = int(input())
numberCheck(c)

I want it to print "Please enter a number" only once. but after running I want it to wait for another number. How would I do this?

I tried a for loop but that uses a range and I don't want to set a range unless there is a way to do it to infinity.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    So, I am thinking about your current predicament, but I am also curious. Is there a reason you are using floor division? – MatthewS Jan 17 '21 at 18:19
  • 1
    `while True` is your friend. Also since you seem to be a Python beginner, may I suggest to use PEP8 naming style? ie no `camelCase` names but rather `snake_case` – ThiefMaster Jan 17 '21 at 18:20
  • I don't know, it is only chapter 3 of the book and I am doing as told lol – B3y0ndD34th Jan 17 '21 at 18:31
  • If you are using Python 3.9 or above, use `while (c:= int(input()): numberCheck(c)` to get an infinite loop – Joe Ferndz Jan 18 '21 at 09:11
  • The linked question is not really a duplicate, it asks specifically for a possibility of an infinite loop using a `for` statement, while this one is about infinite loops in general. A better duplicate target would be https://stackoverflow.com/questions/24335680/how-can-i-make-this-repeat-forever. – mkrieger1 Apr 19 '22 at 23:01

3 Answers3

1

So my understanding is you want the function to run indefinitely. this is my approach, through the use of a while loop

print("Enter a number")

while True:
  c = int(input(""))
  numberCheck(c)
Cryton Andrew
  • 89
  • 1
  • 2
1

If you want to run an infinite loop, that can be done with a while loop.

print('Please enter a number:')

def numberCheck(c):
        if c % 2 == 0:
            print(c // 2)
        elif c % 2 == 1:
            print(3 * c + 1)
            
while True:
    c = int(input())
    numberCheck(c)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
0

You could use a while loop with True:

while True:
    c = int(input())
    numberCheck(c)
Mureinik
  • 297,002
  • 52
  • 306
  • 350