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")
Related
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')
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...")
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.')
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)
I am writing a piece of code that needs to multiply numbers by different values, all the code for the entering and validation of the 7 digit number works however the multiplication doesn't work. This is my code.
while True:
try:
num = int(input("enter a 7 digit number: "))
check = len(str(num))
if check == 7:
print("This code is valid")
break
else:
num = int(input("enter a number that is only 7 digits: "))
except ValueError:
print("you must enter an integer")
num = int(num)
def multiplication():
num[0]*3
num[1]*1
num[2]*3
num[3]*1
num[4]*3
num[5]*1
num[6]*3
return total
multiplication()
When I run it, I get the following error:
Traceback (most recent call last):
File "\\hpdl3802\stuhomefolders$\12waj066\Year 10\Computing\A453\Code\Test v2.py", line 29, in <module>
multiplication()
File "\\hpdl3802\stuhomefolders$\12waj066\Year 10\Computing\A453\Code\Test v2.py", line 20, in multiplication
num[0]*3
TypeError: 'int' object is not subscriptable
Any feedback is welcome
Of course, your code might be written in a number of ways, optimized (check #Kasravand answer, it's awesome) or not, but with a minimal effort this is what I get:
while True:
try:
num = input("enter a 7 digit number: ")
check = len(num)
int(num) # will trigger ValueError if not a number
if check == 7:
print("This code is valid")
break
else:
print("bad length, try again")
except ValueError:
print("you must enter an integer")
def multiplication(num):
total = int(num[0])*3
total += int(num[1])*1
total += int(num[2])*3
total += int(num[3])*1
total += int(num[4])*3
total += int(num[5])*1
total += int(num[6])*3
return total
print("Answer: ", multiplication(num))
If you're bound to use an integer instead of a list for the input, you can do one of the following:
You could access the individual digits using a combination of integer division and modulo, for example:
first_digit = num // 1000000 * 3
second_digit = num // 100000 % 10 * 1
# and so on
Or you could get the input as a string and access and convert the individual digits:
# [...]
num = input("enter a number that is only 7 digits: ")
# [...]
first_digit = int(num[0]) * 3
second_digit = int(num[1]) * 3
When you convert the input number to an integer you can not use indexing on that object since integers don't support indexing. If you want to multiply your digits by a specific number you better do this before converting to integer.
So first off replace the following part:
num = int(input("enter a number that is only 7 digits: "))
with:
num = input("enter a number that is only 7 digits: ")
The you can use repeat and chain functions from itertools module in order to create your repeated numbers, then use a list comprehension to calculate the multiplication:
>>> from itertools import repeat, chain
>>> N = 7
>>> li = list(chain.from_iterable(repeat([3, 1], N/2 + 1)))
>>> num = '1290286'
>>> [i * j for i, j in zip(map(int, num), li)]
[3, 2, 27, 0, 6, 8, 18]
This code will works:
while True:
try:
num = int(input("enter a 7 digit number: "))
except ValueError:
print("you must enter an integer")
else:
if len(str(num)) != 7:
print("enter a number that is only 7 digits")
else:
break
num = str(num)
def multiplication():
total = 0
for i,m in enumerate([3,1,3,1,3,1,3]):
total += int(num[i])*m # transform the index of text into a integer
return total
print(multiplication())
This should help
num = ''
check = 0
while True:
try:
num = raw_input("enter a 7 digit number: ")
check = len(num)
if check == 7:
print("This code is valid")
break
else:
print "enter a number that is only 7 digits"
except ValueError:
print("you must enter an integer")
def multiplication():
total = 0
for i in range(check):
if i % 2 == 0:
total += int(num[i]) * 3
else:
total += int(num[i]) * 1
print total
multiplication()