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

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.')

Related

Python program to read whole numbers and stop when 0 entered, then prints total positive numbers entered

I am trying to write a program where a user enters a bunch of numbers and when 0 is entered the program ends and prints how many positive numbers were entered. I am fairly close to solving this but can't get the positive sum to print.
Could you please explain where I have gone wrong?
Thanks in advance.
Please see attached my code.
userInput = None
oddNum = 0
evenNum = 0
while(userInput != 0):
userInput = int(input("Enter a number: "))
if(userInput > 0):
if(userInput % 2 == 0):
evenNum += 1
elif(userInput % 2 != 0):
oddNum += 1
print("positive numbers were entered".format(evenNum, userInput))
You are missing some of the required syntax for the string.format() command.
For each variable you want injected into the string to be printed, you must include a pair of curly braces {}. Otherwise, the arguments you pass to string.format() are just ignored.
userInput = None
oddNum = 0
evenNum = 0
while(userInput != 0):
userInput = int(input("Enter a number: "))
if(userInput > 0):
if(userInput % 2 == 0):
evenNum += 1
elif(userInput % 2 != 0):
oddNum += 1
print("positive numbers were entered; {} even numbers, and {} odd numbers".format(evenNum, userInput))

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')

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")

What's wrong with my use of if / then in this script?

I'm learning if and then statements. I'm trying to write code that takes any decimal number input (like 2, 3, or even 5.5) and prints whether the input was even or odd (depending on whether the input is actually an integer.)
I get an error in line 8
#input integer / test if any decimal number is even or odd
inp2 = input("Please enter a number: ")
the_number = str(inp2)
if "." in the_number:
if int(the_number) % 1 == 0
if int(the_number) % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
else:
print("You dum-dum, that's not an integer.")
else:
the_number = int(inp2)
if the_number % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
I'm just starting with python so I appreciate any feedback.
You have to include a colon at the end of second if statement, like you did in your other conditional statements.
if int(the_number) % 1 == 0:
Next time, give a closer look at the error message. It'll give you enough hints to fix it yourself, and that's the best way to learn a language.
EOL.
You forgot a :. Line 8 should read if int(the_number) % 1 == 0:.
Try putting the : at the end of the if statement
if int(the_number) % 1 == 0:
You can test your input as following code snippet
num = input('Enter a number: ')
if num.isnumeric():
print('You have entered {}'.format(num))
num = int(num)
if num%2:
print('{} is odd number'.format(num))
else:
print('{} is even number'.format(num))
else:
print('Input is not integer number')

Automate the Boring Stuff with Python The Collatz Sequence assignment repet

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)

Categories

Resources