Q) Write a function named collatz() that has one parameter named number. If a number is even, then collatz() should print number // 2 and return this value. If a 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.
This is the code I wrote for the above problem but I need a small help on how to use the while loop so when I get a ValueError rather than breaking out of the program I want the program to re-execute the program rather than just displaying the print statement in except.
try:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
x = int(input("Enter a number: "))
while x != 1:
x = collatz(x)
except ValueError:
print("Please enter a numerical value")
You could modify the code from the HandlingExceptions - Python Wiki:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
has_input_int_number = False
while has_input_int_number == False:
try: # try to convert user input into a int number
x = int(input("Enter a number: "))
has_input_int_number = True # will only reach this line if the user inputted a int
while x != 1:
x = collatz(x)
except ValueError: # if it gives a ValueError
print("Error: Please enter a numerical int value.")
Example Usage:
Enter a number: a
Error: Please enter a numerical int value.
Enter a number: 1.5
Error: Please enter a numerical int value.
Enter a number: 5
16
8
4
2
1
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
x = int(input("Enter a number: "))
while x != 1:
try:
x = collatz(x)
except ValueError:
print("Please enter a numerical value")
Use while True and break if not statified.
def collatz(x):
x= x//2 if x%2==0 else x*3+1
print(x)
return x
def func(x):
while True:
x = collatz(x)
if x==1:
break
def run():
while True:
try:
x = int(input("Input a positive number: "))
assert x>0
func(x)
break
except Exception as exc:
#print("Exception: {}".format(exc))
pass
if __name__ == "__main__":
run()
Related
def is_even(number):
return number % 2 == 0
def check_number(number):
if is_even(number):
number = number // 2
else:
number = 3 * number + 1
def collatz(number):
while number != 1:
print(number)
check_number(number)
print("Final number is: " + str(number))
if __name__ == "__main__":
number = int(input("Enter a number:"))
collatz(number)
Question: how can my code could be written more succinctly?
Background:
Working on Automate the boring stuff challenges in Python. The program below is meant to:
get the user to enter an integer
check that what was entered was an integer (with try and except)
perform the collatz() function on that sequence
CODE:
def accept_int():
while True:
try:
i = int(input())
break
except ValueError:
print('Please enter an integer value: ')
continue
return i
def collatz(i):
while num > 1:
if i % 2 == 1:
return 3* i + 1
else:
return i // 2
print('Hello, please enter an integer: ')
num = accept_int()
while num > 1:
num = collatz(num)
print(num)
I am trying to display the largest number in a user inputed array. I am not allowed to use a built in sort function. Here is the code I have crafted. As it runs it always returns the first integer in my list instead of the largest.
integers = []
print("Please enter a list of integers.")
print("To finish entering the integers, enter a 0 for the value.")
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
integerIn = input("Please enter an integer < 0 to finish >: ")
if integerIn == int("0"):
done = True
else:
integers.append(integerIn)
return integers
floatInput()
def largestNumber(array):
maxNum = -1
for i in array:
if i > maxNum:
maxNum = i
return maxNum
def displayArray():
print("The Maximum value is: " + str(largestNumber(integers)))
displayArray()
Right code for this task:
def float_input():
integers = list()
while True:
value = int(input('Enter value (or 0 to exit): '))
if value != 0:
integers.append(value)
elif value == 0:
break
return integers
print(max(float_input()))
Or, if you want to create your own largestNumber function use this:
def largest_number(lst):
max_elem = lst[0]
for j in lst[1:]:
if j > max_elem:
max_elem = j
return max_elem
print(largest_number([1, 2, 5, 3, 4])) # print 5
This is my working code:
number = int(input())
while number > 1:
if number % 2 == 0:
number = int(number) // 2
print (number)
elif number % 2 == 1:
number = 3 * int(number) + 1
print (number)
Now I'm trying to add the exception that if user input has non-integer value, it should print 'Enter a number'
while True:
try:
number = int(raw_input())
break
except ValueError:
print("Enter a number!")
while number > 1:
....
EDIT: As noted in a comment by Anton, use raw_input in Python 2, and input in Python 3.
I'm a complete beginner so I would appreciate all kinds of tips. Here is how I managed to solve the problem, and for now it seems to work fine:
def collatz(number):
if number%2 == 0:
return number // 2
else:
return 3*number+1
print ('Enter a number:')
try:
number = int(input())
while True:
if collatz(number) != 1:
number= collatz(number)
print(number)
else:
print('Success!')
break
except ValueError:
print('Type an integer, please.')
You could check for ValueError for the except. From docs:
exception ValueError
Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
try:
number = int(input())
while number > 1:
if number % 2 == 0:
number = int(number) // 2
print (number)
elif number % 2 == 1:
number = 3 * int(number) + 1
print (number)
except ValueError:
print('Enter a number')
You could do this-
while number != 1:
try:
if number % 2 == 0:
number = int(number) // 2
print (number)
elif number % 2 == 1:
number = 3 * int(number) + 1
print (number)
except ValueError:
print('Enter a number')
break
def collatz(number):
if number % 2 == 0:
return number // 2
else:
return 3 * number + 1
while True:
try:
value = int(input("Eneter a number: "))
break
except ValueError:
print("enter a valid integer!")
while value != 1:
print(collatz(value))
value = collatz(value)
def coll(number):
while number !=1:
if number%2==0:
number= number//2
print(number)
else:
number= 3*number+1
print(number)
while True:
try:
number = int(input("Enter the no:"))
break
except ValueError:
print("Enter a number")
print(coll(number))
I did it like this:
# My fuction (MINI-Program)
def collatz(number):
if number % 2 == 0:
return number // 2
else:
return 3 * number + 1
# try & except clause for errors for non integers from the users input
try:
userInput = int(input("Enter a number: "))
# Main loops till we get to the number 1
while True:
number = collatz(userInput)
if number !=1:
userInput = number
print(userInput)
else:
print(1)
break
except ValueError:
print("Numbers only! Restart program")
My code is creating an infinite loop when I enter a letter at the command prompt. I think that len(sys.argv) > 1 is causing the problem, since if I enter a letter at the command prompt this will always be true and the loop will not end. Not sure how I could work around this though... any advice for this newbie would be helpful. Thanks!
"""
Have a hard-coded upper line, n.
Print "Fizz buzz counting up to n", substituting in the number we'll be counting up to.
Print out each number from 1 to n, replacing with Fizzes and Buzzes as appropriate.
Print the digits rather than the text representation of the number (i.e. print 13 rather than thirteen).
Each number should be printed on a new line.
"""
# entering number at command line: working
# entering letter at command line: infinite loop
# entering number at raw_input: works, runs process
# entering letter at raw_input: working
import sys
n = ''
while type(n)!=int:
try:
if len(sys.argv) > 1:
n = int(sys.argv[1])
else:
n = int(raw_input("Please enter a number: "))
except ValueError:
print("Please enter a number...")
continue
print("Fizz buzz counting up to {}".format(n))
for y in range(1,n+1):
if y % 5 == 0 and y % 3 == 0:
print('fizzbuzz')
elif y % 3 == 0:
print('fizz')
elif y % 5 == 0:
print('buzz')
else:
print(y)`enter code here`
Try casting first catching a value and index error:
import sys
try:
n = int(sys.argv[1])
except (IndexError,ValueError):
while True:
try:
n = int(raw_input("Please enter a number: "))
break
except ValueError:
print("Please enter a number...")
print("Fizz buzz counting up to {}".format(n))
for y in range(1,n+1):
if y % 5 == 0 and y % 3 == 0:
print('fizzbuzz')
elif y % 3 == 0:
print('fizz')
elif y % 5 == 0:
print('buzz')
else:
print(y)
If you are not actually trying to take command line inputs just use the while True:
while True:
try:
n = int(raw_input("Please enter a number: "))
break # input was valid so break the loop
except ValueError:
print("Please enter a number...")
print("Fizz buzz counting up to {}".format(n))
for y in range(1,n+1):
if y % 5 == 0 and y % 3 == 0:
print('fizzbuzz')
elif y % 3 == 0:
print('fizz')
elif y % 5 == 0:
print('buzz')
else:
print(y)