as part of the Chapter 3 exercise for Automate the Boring Stuff, I need to write a short program that mimics the Collatz sequence, where:
If number inputted is even number, divide it by 2, repeat until it equals 1;
If number inputted is odd number, multiply it by 3 then plus 1, repeat until it equals 1;
Create a clean exit for Ctrl+C.
Detect whether the user typed in a noninteger string.
Below is my code so far, which seems to work but I would appreciate any advice/best practice for improving it.
My main question is, after the program prints 'Enter integers only', is there any short and simple way to loop back to the 'Enter any number: ' line? I can't think of anything atm besides complicated if loops. Thanks.
def collatz(number):
if number % 2 == 0 :
results = number // 2
print(results)
if results != 1:
collatz(results)
elif number % 2 == 1 :
results = 3 * number + 1
print(results)
if results != 1:
collatz(results)
try:
entry = input('Enter any number : ')
number = int(entry)
print(number)
collatz(number)
except ValueError:
print('Enter integers only.')
except KeyboardInterrupt:
sys.end()
You can try using a while loop. The below code will be helpful for you.
def collatz(number):
if number % 2 == 0 :
results = number // 2
print(results)
if results != 1:
collatz(results)
elif number % 2 == 1 :
results = 3 * number + 1
print(results)
if results != 1:
collatz(results)
while True:
try:
entry = input('Enter any number : ')
number = int(entry)
print(number)
collatz(number)
except ValueError:
print('Enter integers only.')
except KeyboardInterrupt:
break # Stop the while loop.
sys.end()
As you want to keep prompting the same, until the program exits. I'd suggest just encapsulating the program code in a while(true) loop:
while True:
try:
entry = input('Enter any number : ')
number = int(entry)
print(number)
collatz(number)
except ValueError:
print('Enter integers only.')
except KeyboardInterrupt:
sys.end()
You can define an iteration to make sure the input is integer type.
while True: # executes the loop body indefinitely
try:
entry = input('Enter any number : ')
number = int(entry)
print(number)
collatz(number)
break # immediately terminates the loop entirely
except ValueError:
print('Enter integers only.')
except KeyboardInterrupt:
sys.end()
Put it in a "while" loop.
while True:
try:
...
except:
...
Related
import sys
ok = True
count = 0
while ok == True:
try:
a = int(input("What is a? Put number pls "))
ok = False
count = count + 1
except ValueError:
print("no u")
if (count >= 3):
sys.exit()
What I'm trying to do here is get the user to input an integer. If the user inputted an integer or the loop has ran 3 times, the program stops. I have tried putting the if statement both in the try and except statements, it still keeps on looping.
I have also tried this:
ok = True
count = 0
while ok == True:
try:
a = int(input("What is a? Put number pls "))
ok = False
count = count + 1
except ValueError:
print("no u")
if (count >= 3):
break
It still doesn't break out of the loop.
I have inputted numbers, breaks out of the loop as what I expected. I then tried to input random letters and hoped that the loop stops after 3 times, it still continues to loop until I have inputted a number. Happens to both versions.
Here's an approach which you might not have thought of:
count = 0
while count < 3:
try:
a = int(input("What is a? Put number pls "))
break
except ValueError:
print("no u")
count = count + 1
There is no need for ok because you can just use a break statement if you want to end the loop. What you really want to be testing for is if count is less than three, and incrementing count every time the user gets it wrong.
There is no reason to increment count if the loop is about to end, so you want to increment count whenever there is a ValueError (in the except-block) and the loop is about to start again.
I would recommend a slightly expanded version of michaels solution, that takes advantage of the while/else mechanism to determine when no good input was provided
count = 0
while count < 3:
try:
a = int(input("What is a? Put number pls "))
break
except ValueError:
print("no u")
count = count + 1
else: # is triggered if the loop completes without a break
print("No Break... used up all tries with bad inputs")
sys.exit(-1)
print(f"You entered a number {a}")
I'm new to python and I'm looking to code a small calculator for divisions, that includes while loops and if conditionals
My code looks like this:
a = input('first number')
while type(a)!=int:
try:
a=int(a)
print('imput number is correct ',a)
except:
print('Imput data is not correct ')
a=input('first number')
b = input('second number')
while type(b)!=int and b!=0:
try:
b=int(b)
print('Imput data is correct',b)
except:
print(' imput data is not a number, please only imput numbers ')
b=input('second number')
while b==0:
try:
c=1/b
print('imput number is correct ',b)
except ZeroDivisionError:
print('Cant divide by 0')
b=input('second number again')
if type(a)==int and type(b)==int and b!=0:
c=a/b
print('the result is: ',c)
The program suddenly ends after you imput 0 a second time in the second number space, but the proccess should keep asking for a value that is a number and different from 0
After b=input('second number again') is executed, b is a string, so b == 0 is False(a string is never equal to an integer).
You'll find this easier if you write a common function to get the user input. Something like this:
def get_input(prompt, nonZero=False):
while True:
try:
if (n := int(input(prompt))) == 0 and nonZero:
raise ValueError('Value must be non-zero')
return n
except ValueError as e:
print(e)
a = get_input('Input first number: ')
b = get_input('Input second number: ', True)
print(a/b)
I am a starter in learning Python, and I am doing the practice project of the book called Automate the Boring Stuff with Python, chapter 3. That is a collatz sequence. My code is below:
def collatz(number):
if number % 2 == 0:
return (int(number)//2)
else:
if number % 2 ==1:
return(3*int(number)+1)
print('Enter number:')
try:
number = int(input())
while True:
if number != 1:
number = collatz(number)
print(number)
else:
break
except ValueError:
print('You must input an interger!')
This code is running well, and until the result reached 1, it stopped.like
3
10
5
16
8
4
2
1
But when I put the Try-exception block into the While loop, then everything changed. like this:
while True:
number = int(input())
try:
if number != 1:
number = collatz(number)
print(number)
else:
break
except ValueError:
print('You must input an interger!')
Then the program couldn't finish the while loop till the final result 1. It stopped after just one try, like
3
10
I can't figure it out. Could anybody here explain why? Thanks a lot!
I am going through book automate boring stuff with python and trying to solve the practical problems.
In this project I need to define collatz() function and print results as seen in code until it gets 1.
So basically i need to input only one number and program should return numbers until it returns 1.
Program works fine but i have one question if i can make it better :D .
My question is after using try: and except: is there a way to not end process when typing string in input function but to get message below 'You must enter number' and get back to inputing new number or string and executing while loop normally. Code works fine just wondering if this is possible and if so how?
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
else:
print(3 * number + 1)
return 3 * number + 1
try:
yourNumber = int(input('Enter number: '))
while True:
yourNumber = collatz(yourNumber)
if yourNumber == 1:
break
except ValueError:
print('You must enter a number')
Put the try/except inside a loop, such that on the except the loop will continue but on a success it will break:
while True:
try:
yourNumber = int(input('Enter number: '))
except ValueError:
print('You must enter a number')
else:
break
while yourNumber != 1:
yourNumber = collatz(yourNumber)
I am writing a Collatz sequence program using the practice projects from chapter 3 of Automate the boring stuff with python.
The program outline is:
Write a function named collatz() that has one parameter named number.
If number is even, then collatz() should print number // 2 and return
this value. If number is odd, then collatz() should print and return
3 * number + 1.
Then write a program that lets the user type in an integer and that
keeps calling collatz() on that number until the function returns the
value 1.
My code runs however it stops on 4 rather than 1. For every number I have tried so far the output goes past 1 back to 4.
example output:
6,3,10,5,16,8,4,2,1,4
I am using python 3.4.2
def collatz(number):
if number % 2 == 0:
number = number //2
print(number)
return number
elif number % 2 == 1:
number = 3 * number + 1
print(number)
return number
print ("pick a number:")
while True:
try:
number = int(input())
while number != 1:
number = collatz(number)
collatz(number)
break
except ValueError:
print("Error: Please enter a valid integer")
print("Magic! You are down to 1.")
The problem is that you call collatz() once more after the loop finishes with 1. Just remove that line, and it works fine.
Also if you move the "pick a number" to the input function, you can avoid the new line after the question and are asked again every time, if you input an invalid value.
Additionally you should also check if the number is greater than or equal to 1, to avoid endless loops. The code to do all that would look like that:
while True:
try:
number = int(input("pick a number: "))
if number < 1:
print("Error: Please enter a integer greater than or equal to 1 ")
continue
while number != 1:
number = collatz(number)
# removed the additional call to collatz
break
except ValueError:
print("Error: Please enter a valid integer")
print("Magic! You are down to 1.")
def collatz(number):
number = number // 2 if number % 2 == 0 else 3 * number + 1
print(number)
return number
number = int(input("Pick a Number\n"))
while number != 1:
number = collatz(number)
print("Magic! You are down to 1.")