Collatz sequence. Dealing with exception handling - python

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

Related

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

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

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)

can we make this script shorter ?even odd checking

hi there i'm learning python
i like to know if this script can be better or shorter
import sys
g = 1
def trying():
q = input('enter (y or yes) to retry')
if not q == 'y' or q == 'yes':
return 0
while g == True:
try:
t = int(input('please enter an integer:'))
r = t % 2
if r == 0:
print('your number is even')
if trying() == 0:
g = 0
else:
print('your number is odd')
if trying() == 0:
g = 0
except ValueError:
print('sorry you need to enter numbers only')
If you want in shorter, here is my version..
while True:
try:
print('Your number is %s' % ('even' if int(input('Please enter an integer: ')) % 2 == 0 else 'odd'))
if input('Enter (y or yes) to retry: ') not in ['y', 'yes']: break
except ValueError:
print('Sorry you need to enter numbers only')
What you want here is a do-while loop. You can easily implement it by adding a break statement to a infinite while-loop. More on this topic can be found here.
Next thing, you have to add a try-except statement as there is a string to integer conversion is happening.
print('Your number is %s' % ('even' if int(input('Please enter an integer: ')) % 2 == 0 else 'odd'))
This statement will return "Your number is even" if the input is even else it will return "Your number is odd". This method is called python ternary operator.
Then you can wrap it with a print-function to print the returned string. Look here.
input('Enter (y or yes) to retry: ') not in ['y', 'yes']
This check whether the user input is not there in the given list. So if user input is neither "y" or "yes", while-loop will break.
Here is an example of how the code can be made simpler. Remember that code should rarely be repeated. In most cases, if you have repeating lines of code it can be simplified.
while True:
try:
t = int(input('please enter an integer:'))
if t % 2 == 0: print('your number is even')
else: print('your number is odd')
q = input('enter (y or yes) to retry')
if not (q == 'y' or q == 'yes'): break
except ValueError:
print('sorry you need to enter numbers only')
def trying():
question = input('enter (y or yes) to retry')
if not (q == 'y' or q == 'yes'):
return 1
return 0
while True:
try:
num1 = int(input('please enter an integer:'))
num2 = t % 2
if not num2:
print('your number is even')
else:
print('your number is odd')
if trying():
break
except ValueError:
print('sorry you need to enter numbers only')
You don't have to import sys in your program as you didn't used it and you don't have to. You don't have to store anything in a variable for a while loop. Just assigning True and breaking out will do. If you're looking for anything that is True (this includes an unempty list, string, and dictionaries; and numbers not equal to 0). You should make if var:. If the variable evaluates to True. The conditional block will be executed. This is a clearer syntax so it is recommended. Name your variables with words, not with letters. This will not make your code longer and it will make your code better.
This is all I can do with your code. If there is more, please state them.

Categories

Resources