Automate the Boring Stuff with Python The Collatz Sequence assignment repet - python

I know there are a lot of posts on this assignment and they all have great information, however, I am trying to take my assignment to the next level. I have written the code for the sequence, I have written the try and except functions and have added the continues so the program will keep asking for a positive integer till it gets a number. now I would like the whole program to repeat indefinitely, and I will then write a (Q)uit option. I tried making the question ask into a global scope but that was wrong, can someone please give me a hint and I will keep working on it. here is my code;
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
return result
while True:
try:
n = int(input("Give me a positive number: "))
if n <= 0:
continue
break
except ValueError:
continue
while n != 1:
n = collatz(int(n))

An example of repeating indefinitely is as follows.
def collatz(number):
" No element of Collatz can be simplified to this one liner "
return 3 * number + 1 if number % 2 else number // 2
while True:
# Will loop indefinitely until q is entered
try:
n = input("Give me a positive number: ")
# String returned from input
if n.lower() == "q": # check for quit (i.e. q)
break
else:
n = int(n) # assume int, so convert (will jump to exception if not)
while n > 1: # loops and prints through collatz sequence
n = collatz(n)
print(n)
except ValueError:
continue

Pretty much all you need to do is move the second while loop into the first and add a "quit" option, though I've done some additional things here to simplify your code and give more feedback to the user.
def collatz(number):
if number % 2 == 0:
# Removed "print" here - should be done in the calling scope
return number // 2
else: # Removed "elif" - You already know "number" is not divisible by two
return 3 * number + 1
while True:
s = input("Give me a positive number, or 'q' to quit: ")
if s == 'q':
print('Quit')
break
try:
# Put as little code as possible in a "try" block
n = int(s)
except ValueError:
print("Invalid number, try again")
continue
if n <= 0:
print("Number must be greater than 0")
continue
print(n)
while n != 1:
n = collatz(n)
print(n)
Example run:
Give me a positive number, or 'q' to quit: a
Invalid number, try again
Give me a positive number, or 'q' to quit: 0
Number must be greater than 0
Give me a positive number, or 'q' to quit: 2
2
1
Give me a positive number, or 'q' to quit: 3
3
10
5
16
8
4
2
1
Give me a positive number, or 'q' to quit: q
Quit

Thank you the suggestions are great!! Here is my finished code;
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
else:
number = 3 * number + 1
print(number)
while True:
try:
n = input("Give me a positive number or (q)uit: ")
if n == "q":
print('Quit')
break
n = int(n)
except ValueError:
continue
collatz (n)

Related

Program to compute sum of even and odd numbers received in stream by user

In this particular code I have to find the sum of even and odd number given the by user in stream, as I can observe everything is ok in the code but still not able to run it and getting ValueError: invalid literal for int() with base 10:
sum_of_even_number=0
sum_of_odd_number=0
while True: # We have created a infinite loop
user_input=input()
if user_input=="\n\n":
break
num=int(user_input)
if num % 2==0:
sum_of_even_number+=num
else:
sum_of_odd_number+=num
print("sum_of_even_number : ",sum_of_even_number)
print("sum_of_odd_number : ",sum_of_odd_number)
You're getting a Value Error because you are trying to parse an empty string. If the user presses the enter key, then it gets formatted as a string with no text. So instead of checking to see if your text contains \n, check to see if its an empty string or not, like this:
sum_of_even_number=0
sum_of_odd_number=0
while True: # We have created a infinite loop
user_input=input()
if user_input == "":
break
num = int(user_input)
if num % 2 == 0:
sum_of_even_number += num
else:
sum_of_odd_number+=num
print("sum_of_even_number : ",sum_of_even_number)
print("sum_of_odd_number : ",sum_of_odd_number)
For more help: ValueError: invalid literal for int() with base 10: ''
the use of the "isdigit()" method is to prevent value error(if the user enters an alphanumeric value that can not be converted to an int or a float). Although this only works for positive whole numbers due to the "isdigit()" method. I also added a quit option to prevent the loop from being infinite.
sum_odd = 0
sum_even = 0
stat = True #looping condition
while stat:
num = input("Enter a number or enter q to quit: ")
if num.isdigit() == True: #to verify if the string is a positive int
if int(num)%2 ==0: #checking if the number is even
sum_even+=int(num)
print("sum of even number = "+str(sum_even))
elif int(num)%2 ==1: #checking if the number is odd
sum_odd+=int(num)
print("sum of odd number = "+str(sum_odd))
elif num.lower() == "q": #this breaks the loop
stat = False #change of looping condition
print("done") #indicating end of code
sample output:
Enter a number or enter q to quit: 10
sum of even number = 10
Enter a number or enter q to quit: 13
sum of odd number = 13
Enter a number or enter q to quit: 12
sum of even number = 22
Enter a number or enter q to quit: 15
sum of odd number = 28
Enter a number or enter q to quit: 16
sum of even number = 38
Enter a number or enter q to quit: 8
sum of even number = 46
Enter a number or enter q to quit: 9
sum of odd number = 37
Enter a number or enter q to quit: q
done
Edit: Fixing indentation.
Without Walrus operator:
Before: Using same code as your. I put print inside if/else condition block Use the f-string format as well.
sum_of_even_number=0
sum_of_odd_number=0
while True: # We have created a infinite loop
user_input=input('Enter number:')
if user_input=="\n\n":
break
num=int(user_input)
if num % 2==0:
sum_of_even_number+=num
print(f"sum_of_even_number : {sum_of_even_number}")
else:
sum_of_odd_number+=num
print(f"sum_of_odd_number : {sum_of_odd_number}")
With Python 3.8 Walrus Operator:
sum_of_even_number=0
sum_of_odd_number=0
while (user_input := input('Enter number:')): # We have created a infinite loop
num = int(user_input)
if num % 2 == 0:
sum_of_even_number = num
print(f"sum_of_even_number : {sum_of_even_number}")
else:
sum_of_odd_number = num
print(f"sum_of_odd_number : {sum_of_odd_number}")
Both output are same.
Enter number:6
sum_of_even_number : 6
Enter number:5
sum_of_odd_number : 5
Enter number:8
sum_of_even_number : 8
Enter number:100
sum_of_even_number : 100
Enter number:105
sum_of_odd_number : 105
Enter number:

Collatz sequence. Dealing with exception handling

I just started learning python 3 and have been having some issues when trying to understand exception handling. I am going through a tutorial book that has given me a small project called the 'The Collatz Sequence'
its essentially a program that evaluates any integer down to '1' by using a some simple math.
I have been able to successfully get the program to work UNTIL the user inputs anything but an integer. At first I was getting ValueError, which was corrected by using the except ValueError:.
Now I seem to be getting NameError: name 'number' is not defined
Any help is appreciated. Just trying to get an understanding of exception handling.
def collatz(number):
if number % 2 == 0:
even_number = number//2
print(even_number)
return even_number
elif number % 2 == 1:
odd_number = (number * 3 + 1)
print(odd_number)
return odd_number
try:
number = int(input('Enter Number: '))
except ValueError:
print('Please enter an integer')
while int(number) != 1:
number = collatz(number)
A possibility would be to keep track of whether an integer was given as input using a boolean value. Consider the (adapted) code below:
def collatz(number):
if number % 2 == 0:
even_number = number//2
print(even_number)
return even_number
elif number % 2 == 1:
odd_number = (number * 3 + 1)
print(odd_number)
return odd_number
# Keep asking for input until the user inputs an integer
got_integer = False
while not got_integer:
try:
number = int(input('Enter Number: '))
got_integer = True
except ValueError:
print('Please enter an integer')
while int(number) != 1:
number = collatz(number)
As you can see, I define a boolean variable got_integer. Initially, I set its value to False. After this variable definition is a while loop, which keeps executing the loop body until the value of got_integer is True. Now you simply set the value of got_integer to True upon a succesfull input (i.e. if the execution of the line number = int(input('Enter Number: ')) succeeds).
You have to have the logic inside try block if you are getting exceptions.
Then you can handle it when you face with an exception. In your case you can have the while block inside the try like below. According to the exceptions you can handle them below as you have done already.
def collatz(number):
if number % 2 == 0:
even_number = number//2
print(even_number)
return even_number
elif number % 2 == 1:
odd_number = (number * 3 + 1)
print(odd_number)
return odd_number
try:
number = int(input('Enter Number: '))
if number != 1:
number = collatz(number)
except ValueError:
print('Please enter an integer')

How to count how many times a number was printed using python?

So I made a nooby Collatz Sequence showing program. I am interested in knowing how many times number was printed by the computer so that I can see how many steps it took for a number to eventually become 1. If you don't know much about the Collatz sequence, run my code...
import sys
def collatz(number):
if number <= 0:
print("Next time, enter an integer greater than 1.")
sys.exit()
while number % 2 == 0:
number = number // 2
print(number)
if number == 1:
sys.exit()
while number % 2 != 0:
number = 3*number+1
print(number)
collatz(number)
print("""Enter a number.
Even number is halfed, odd number is multiplied by 3 and 1 is added to the product.
This is called as Collatz sequence.
Watch as your number slowly becomes 1.
Enter a positive integer:""")
try:
collatz(int(input()))
except ValueError:
print("Next time, Enter a positive integer, you dummy...")
One really quick and dirty way to do this, would be to just use an "iterations" argument. Something like this would get your desired result:
import sys
def collatz(number, iterations=0):
if number <= 0:
print("Next time, enter an integer greater than 1.")
sys.exit()
while number % 2 == 0:
number = number // 2
print(number)
iterations += 1
if number == 1:
print(f'This number took {iterations} steps to get to 1')
sys.exit()
while number % 2 != 0:
number = 3*number+1
print(number)
iterations += 1
collatz(number, iterations)
print("Enter a number.")
print("Even number is halfed, odd number is multiplied by 3 and 1 is added to the product.")
print("This is called as Collatz sequence.")
print("Watch as your number slowly becomes 1.\nEnter a positive integer:")
try:
collatz(int(input()))
except ValueError:
print("Next time, Enter a positive integer, you dummy...")
You can also use a global variable steps. But NewBoard's solution is also good.
import sys
steps = 0
def collatz(number):
global steps
if number <= 0:
print("Next time, enter an integer greater than 1.")
sys.exit()
while number % 2 == 0:
steps += 1
number = number // 2
print(number)
if number == 1:
print(f"Steps: {steps}")
sys.exit()
while number % 2 != 0:
steps += 1
number = 3*number+1
print(number)
collatz(number)
print("Enter a number.")
print("Even number is halfed, odd number is multiplied by 3 and 1 is added to the product.")
print("This is called as Collatz sequence.")
print("Watch as your number slowly becomes 1.\nEnter a positive integer:")
try:
collatz(int(input()))
except ValueError:
print("Next time, Enter a positive integer, you dummy...")

Automate The Boring Stuff With Python - Collatz Sequence

I'm very new to any sort of coding, currently using python 3.3. I've managed to run the Collatz Sequence accurately in python with the following:
while True: # The main game loop.
number = int(input('Enter number:\n'))
def collatz(number):
while number !=1:
if number % 2==0: #even numbers
number=number//2
print(number)
elif number % 2!=0: #odd numbers
number=number*3+1
print(number)
collatz(number)
However, I'm unsure of how and where to add a ValueError strong, for when the user enters a non-integer, something like the following:
except ValueError:
print('Only integers accepted.')
I'm very new to python, so if any answers could have a little explanation I'd be very appreciative. Thanks
Put it at the very very top. Parameter constraints should always happen as soon as possible, so that you don't waste time running code you're just going to error out of.
def progress(percentage):
if percentage < 0 or percentage > 100:
raise ValueError
# logic
I assumed that you're referring to Exception Handling, Validation part must be done in the beginning.
while True: # The main game loop.
try:
number = int(input('Enter number:\n'))
except ValueError:
print("Only integers accepted! Please try again ...")
else:
collatz(number)
#output:
#
#Enter number:
#abc
#Only integers accepted! Please try again ...
#Enter number:
#5
#16
#8
#4
#2
#1
#Enter number:
But program will continue looping, termination conditions needed.
number = None
while number != int():
try:
number = int(input("Enter number: "))
break
except:
print("Enter a valid Number")
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
else:
number = (3 * number + 1)
print(number)
collatz(number)
def collatz():
try:
number = int(input("Enter number: "))
while True:
if number == 1 or number == 0:
break
elif number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = 3 * number + 1
print(number)
except:
print("Enter in a valid number")
collatz()
Try this:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
else:
print(3 * number + 1)
return 3 * number + 1
while True:
try:
number = int(input("Enter a Number or type 0 to exit: "))
if number == 0:
break
while True:
if number != 1:
number = collatz(number)
else:
break
except ValueError:
print("Enter an integer number")

Collatz Sequence - Trying to fix a printed 'None' value

Complete beginner here, I'm currently reading through "Automate the Boring Stuff With Python" by Al Sweigert. I'm running into an issue where my program is returning a None value and I can't figure out how to change that.
I understand that at some point collatz(number) doesn't have a value, therefor None is returned- but I don't understand how to fix it. The book hasn't touched on yield yet. I've tried using return instead of print within the function, but I haven't been able to fix it.
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = 3 * number + 1
print(number)
print('Enter number:')
try:
number = int(input())
print(collatz(number))
except ValueError:
print ('Please enter an integer.')
As #chepner proposed you need to remove the print statement which is enclosing your collatz(number) call. The correct code would look like
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = 3 * number + 1
print(number)
print('Enter number:')
try:
number = int(input())
collatz(number)
except ValueError:
print ('Please enter an integer.')

Categories

Resources