I know there are multiple posts on this question. But I could not post my code in any other way except by asking a question. Can someone please help me understand how I can stop n from being input into the collatz function each time the global scope executes.
Write a function named collatz() that has one parameter named number.
If number is even, then collatz() should print number // 2 and return this value.
If 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.
(Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence,
you’ll arrive at 1! Even mathematicians aren’t sure why.
Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”)#
Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value.
desired output
3
10
5
16
8
4
2
1
Input Validation
Add try and except statements to the previous project to detect whether the user types in a noninteger string.
Normally, the int() function will raise a ValueError error if it is passed a noninteger string, as in int('puppy').
In the except clause, print a message to the user saying they must enter an integer.
def collatz(number):
if number%2==0:
number=number//2
print(number)
elif number%2==1:
number=3*number+1
print(number)
print('Enter number: ')
n=int(input())
while n!=1:
collatz(n)
You‘ve created an infinite loop, since your „n“ doesn‘t change within the loop and „n!=1“ is never met as long as the user doesn’t input “1” in the beginning.
Try this:
def collatz(number):
if number % 2 == 0:
number = number // 2
else:
number = 3 * number + 1
print(number)
return number
n = int(input("Enter number: "))
while n != 1:
n = collatz(n)
Related
I am working on a program that requires the user to enter a number and will continue to loop until a positive number is given. When a positive number is given, it will alert the user and present them with the sum of the digits of their number. However, I thought I had written my code correctly, but it is giving me an incorrect answer. What have I done wrong and how can I fix this?
user_input = float(int(input("Please Enter Your Number:")))
s = 0
while user_input < 0:
float(int(input("Please Enter Another Number: ")))
if user_input > 0:
s += user_input%10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
Four things:
Not sure why you storing the input as float, int should suffice.
If you give a negative input, it will enter the while loop. However, in the while loop, you are not actually assigning the new input to user_input. Fix this by adding user_input =
The while loop guarantees user_input is >= 0, so if user_input > 0: is unnecessary.
Probably the most important, to calculate the sum of digits, you need to repeatedly divide and sum, not just do it once. So, add a while loop.
Final code:
user_input = int(input("Please Enter Your Number: "))
s = 0
while user_input < 0:
user_input = int(input("Please Enter Another Number: "))
while user_input:
s += user_input % 10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
The if statement is generally used to decide if something should be done once.
If you want to keep going until user_input becomes zero, you'll need a while.
Also, I'm not entirely certain why you're storing the number as a float, especially when you make that from an int anyway. It may as well just be an int.
Additionally, you're loop to re-enter the value if it was negative doesn't actually assign the new value to the variable.
And you probably also want to outdent the print statement lest it be done on every iteration of the loop you're about to add.
Of course, some may suggest a more Pythonic way of summing the digits of a positive number is a simple:
sum([int(ch) for ch in str(x)])
That works just as well, without having to worry about explicit loops.
Another way to solve this is using assert and a function:
def sum_num():
# try get user input
try:
user_in = input('Enter Number: ')
assert int(user_in) > 0
except AssertionError:
# we got invalid input
sum_num()
else:
s_d = sum([int(i) for i in user_in])
print('You\'ve entered a positive number! The sum of the digits is: ', s_d)
#run the function
sum_num()
So this will asked user input, if it is not greater than zero it will throw assertion error, which we catch and return the user to inputting the number by calling the function again. If all is well, we split the input into character and add them up. as list('12') gives ['1','2']. We convert to int and add them. :)
The awesome thing about this is you can add more too the asset to capture other issue as floats, character as invalid inputs. E.g.
Assuming literal_eval is important( from ast import literal_eval)
assert isinstance(literal_eval(user_in),int) and int(user_in)>0
Check if user_in is integer and it is greater than 0. So you won’t get issues when user inputs floats or characters.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Stuck on this problem and I couldn't find an answer and my code keeps failing.
Write a function called specialPrime which takes in an integer as an argument and returns True if the integer is a prime number and length of the integer squared is less than six digits, False if it is not a prime number or the integer squared is greater than six digits. Write a program which prompts the user to type in an integer and uses you specialPrime function to determine whether or not the integer is special.
Example Interaction
Enter a number: 140
140 is not a special prime number.
Enter a number: 89
89 is a special prime number.
My code
def specialPrime(isPrime,G6):
isPrime= int(input('Enter a number:')
if isPrime < 2 return False
elif isPrime == 2
return True
for n in range(2, x)
if x % n ==0:
return False
return True
G6 = len(isPrime**2)
if G6 > 6: return False
else
return True
while True
print( isPrime + 'is a special number')
else
print( isPrime + 'is not a special prime')
`
First:
Write a function called specialPrime which takes in an integer as an argument and returns True [or] False
Your function doesn't take an integer as an argument, it takes two arguments that… I'm not sure what they're intended to be, because you ignore them anyway. So, start with that. Also, give it a meaningful name. isPrime sounds like a flag that tells you whether a number is prime, or a function that figures out whether a number is prime, not a candidate number that may or may not be prime. So:
def specialPrime(number):
The next part of your code is close, but it's got problems too:
You're supposed to be testing the value you got as an argument, not some completely different value you got from input.
if, elif, for, and all other "compound statements" in Python need colons.
if, etc., statements with multi-line bodies need those bodies indented.
What is x? You were testing isPrime, and suddenly you're testing another variable that you haven't even defined anywhere.
You return True if the number is == 2, and also if it's > 2 but has no divisors between 2 and the number. That means you aren't testing the other condition; you're just assuming it's always true.
So:
if number < 2: return False
elif isPrime == 2:
pass
for n in range(2, number):
if number % n ==0:
return False
This can all be improved in multiple ways, but those are the minimal changes to make it make sense as Python code.
Next, you're trying to take the length of a number. Numbers don't have lengths. You can take the length of a string representation of a number:
digits = len(str(number**2))
if digits > 6:
… or you can do arithmetic to test the number of digits:
square = number**2
if square > 999999:
Also, notice the names digits and square, which tell you that it's a count of digits, or a square of a number, instead of G6, which tells you that it's a group of the 6 major EU countries.
Either way, you then have some of the same problems from the first block with colons and indents again, which you need to fix the same way.
Finally:
Write a program which prompts the user to type in an integer and uses you specialPrime function to determine whether or not the integer is special.
There's nothing about a while True-type loop here—it's a reasonable extension to the program, but get the basics working first.
So you need to prompt the user to type in an integer. Here is where you use input:
number = input('Enter a number:')
But the result of input is a string. If the user types 23, what you get is the string '23'. So, you need to call int to convert it:
number = int(input('Enter a number:'))
Now you have to call your function:
if specialPrime(number):
And again, you have some of the same errors with colons and indents that you need to fix.
After all of those fixes, the code will run. If there are no logic errors in your tests, it will give the right answer. If there are… well, you can debug it from there.
You could modify your code to use a couple of helper functions for each of the two requirements of special_prime(x):
def squared_less_than_six_digits(x):
return len(str(x**2)) < 6
def is_prime(x):
if x < 2:
return False
else:
for n in range(2, x):
if x % n == 0:
return False
return True
def special_prime(x):
return is_prime(x) and squared_less_than_six_digits(x)
def main():
user_input = 0
while True:
try:
user_input = int(input("Please enter an integer:"))
except ValueError:
print("Error: You did not enter a integer. Please try again.")
continue
else:
print("You entered the integer {}. Its square is {}.".format(user_input, user_input**2))
break
if special_prime(user_input):
print("It is a special prime.")
else:
print("It is not a special prime.")
if __name__ == "__main__":
main()
Try the above code out here!
Testing:
Prime number whose square is less than six digits:
Please enter an integer: 2
You entered the integer 2. Its square is 4.
It is a special prime.
Prime number whose square is greater than or equal to six digits:
Please enter an integer: 317
You entered the integer 317. Its square is 100489.
It is not a special prime.
Nonprime number whose square is less than six digits:
Please enter an integer: 1
You entered the integer 1. Its square is 1.
It is not a special prime.
Nonprime number whose square is greater than or equal to six digits:
Please enter an integer: 318
You entered the integer 318. Its square is 101124.
It is not a special prime.
I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0
I'm trying to write a collatz program from the 'Automate the Boring Stuff with Python book', but have ran into some problems. I'm using python 3.5.2. Here's the project outline:
Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If 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.
My code:
def collatz(number):
if number % 2 == 0: #its even
print(number // 2)
return number // 2
elif number % 2 == 1: #its odd
print(3*number+1)
return 3*number+1
print('Type an integer: ')
num=int(input())
while(True):
if collatz(num) == 1:
break
# Or even simpler:
# while(collatz(num) != 1):
# pass
The output gives me an infinite loop:
Type an integer:
10
5
5
5
5
5
5
5
5
...
But when I break it down and use a variable to store the return value, it works:
while(True):
num=collatz(num)
if num == 1:
break
Output:
Type an integer:
5
16
8
4
2
1
Why is it? I don't understand why the first program doesn't work. Both are similar but I just chose to test the return value directly in my original program instead of using variables.
I'd appreciate any help, Thanks.
Your code:
while(True):
if collatz(num) == 1:
break
didn't work because everytime collatz gets called it gets called with the same value of num and as a result returns the same number again and again. That number is not 1, so you have an infinite loop.
When you do num = collatz(num), the value of num is changed the first time the function is called. The new value is then passed to the second time the function is called, and so on. So eventually you reach a point when the value of num becomes 1 and exit the loop.
import random
print "Welcome to the number guesser program. We will pick a number between 1 and 100 and then ask you to pick a number between 1 and 100. If your number is 10 integers away from the number, you win!"
rand_num = random.randint(1, 100)
user_input = raw_input('Put in your guess:').isdigit()
number = int(user_input)
print number
if abs(rand_num - number) <= 10:
print "Winner"
else:
print "Loser"
Whenever I try to run this code, the computer always generates the number 1. And if I put in a number that is 10 (or less) integers away from one it will still display the else statement. I will have my gratitude to whoever can solve my predicament. I am new to python try to keep your answers simple please.
raw_input returns a string you entered as input. isdigit() checks whether a string is a digit or not and returns True or False.
In your code you're assigning the return value of isdigit to user_input So, you get either True or False. Then you convert it to a number, thus getting either one or zero. This is not what you want.
Let user_input be just a result of raw_input. Then check whether it is a valid number with user_input.isdigit(). If it's not a number, print an error message and exit (or re-ask for input), else convert user_input to an integer and go on.
The problem is product by this sentenc:
user_input = raw_input('Put in your guess:').isdigit().
The return value of isdigit() is True or False. When you enter 1 or any digit number, it will return True(True=1,False=0), so you will always get 1, if you enter digit. You can change like this:
import random
print "Welcome to the number guesser program.
We will pick a number between
1 and 100 and then ask you to pick a number
between 1 and 100. If your number is 10 integers
away from the number, you win!"
rand_num = random.randint(1, 100)
user_input= raw_input('Put in your guess:')
is_digit = user_input.isdigit()
if is_digit==True:
number = int(user_input)
print number
if abs(rand_num - number) <= 10:
print "Winner"
else:
print "Loser"
else:
print 'Your input is not a digit.'
Look at this line:
user_input = raw_input('Put in your guess:').isdigit()
The function raw_input gives you user input, but then you call isdigit and as consequence in your variable user_input you get result of isdigit. So, it has boolean value.
Then in
number = int(user_input) you cast it to integer type. In python true is 1 and false is 0. That's why you always get 1.