'I want to repeat a function indefinitely [duplicate]
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.
Solution 1:[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)
Solution 2:[2]
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)
Solution 3:[3]
You could use a while
loop with True
:
while True:
c = int(input())
numberCheck(c)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mkrieger1 |
Solution 2 | |
Solution 3 | Mureinik |