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...")
Related
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")
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'm trying to solve this problem below. I can get it to print whether it's odd or even but I can't get it to print out the correct message if number is a multiple of 4.
Here is the problem: Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. If the number is a multiple of 4, print out a different message.
Here is my code:
number = input("Pick a number and I'll tell you if it's odd or even. ")
def odd_or_even():
if int(number) % 2 == 0:
return("Your number is even.")
elif int(number) % 4 == 0:
return("Your number is a multiple of 4.")
else:
return("Your number is odd.")
print(odd_or_even())
If a number is a multiple of 4, it is also an even number and that's why it always triggers your first condition and doesn't even check the second one. Change the order of the conditions, i.e.:
...
if int(number) % 4 == 0:
return("Your number is a multiple of 4.")
elif int(number) % 2 == 0:
return("Your number is even.")
...
Problem statement: Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number.
Sample output (ignore bullets, didn't know how to format text into console output):
Enter an integer, the input ends if it is 0: 1
Enter an integer, the input ends if it is 0: 2
Enter an integer, the input ends if it is 0: -1
Enter an integer, the input ends if it is 0: 3
Enter an integer, the input ends if it is 0: 0
You didn't enter any number
The number of positives is 3
The number of negatives is 1
The total is 5
The average is 1.25
Attempted solution:
def main():
i = int( input ("Enter an interger, the input ends if it is 0: "))
count_pos = 0
count_neg = 0
total = 0
if (i != 0):
while (i != 0):
if (i > 0):
count_pos += 1
elif (i < 0):
count_neg += 1
total += i
i = int( input ("Enter an interger, the input ends if it is 0: "))
count = count_pos + count_neg
average = total / count
print ("The number of positives is", count_pos)
print ("The number of negatives is", count_neg)
print ("The total is", total)
print ("The average is", float(average))
else:
print ("You didn't enter any number.")
main()
You do not need this line (which is why your error is happening):
main(i)
To continuously get user input, use an infinite loop, and test for the condition to break the loop.
while (true):
i = input("Enter an integer (0 to stop): ")
if(i == 0)
break
sum1 += i
if (i > 0):
count_pos += 1
elif (i < 0):
count_neg += 1
Then calculate and return average.
You are calling the main function with the parameter 'i', which does not exist. You can't use variables declared in a function outside of that function
Check out: Python Scopes