Collatz - Automate the Boring Stuff with Python [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am completely new to python and I just completed the first python project in the book. However, I am trying to improve my code so that the program will continue running until the user enters a valid integer. Currently if a user provides an input that's not an integer, the program just says 'Please enter an integer' and exits. How do I achieve this? I have been trying for hours but is still unable to get to a conclusion.
#! python3
def collatz(number):
if (number % 2) == 0:
result = number // 2
print(result)
return(result)
else:
result = (3 * number) + 1
print(result)
return(result)
try:
givenNumber = int(input('Enter a number: '))
while givenNumber != 1:
givenNumber = collatz(givenNumber)
except ValueError:
print('Please enter an integer.')

You can wrap your logic inside a while loop:
while True:
try:
givenNumber = int(input('Enter a number: '))
# break here if condition True
except ValueError:
print('Please enter an integer.')

I'm not sure it related to python programming specific, but try to learn from the exampls as this one:
def collatz(number):
if (number % 2) == 0:
result = number // 2
print(result)
return(result)
else:
result = (3 * number) + 1
print(result)
return(result)
givenNumber = None
while not isinstance(givenNumber,int):
givenNumber = input('Enter a number: ')
try:
givenNumber = int(givenNumber)
except ValueError:
print("this is not an integer number")
givenNumber = collatz(givenNumber)
output for example:
Enter a number: 3.2
this is not an integer number
Enter a number: 2
1

Related

'Perfect factorial' python program [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I need to check whether what the user entered is positive. If it is not I need to print an error in the form of a msgbox.
number = input("Enter a number: ")
###################################
try:
val = int(number)
except ValueError:
print("That's not an int!")
The above code doesn't seem to be working.
Any ideas?
while True:
number = input("Enter a number: ")
try:
val = int(number)
if val < 0: # if not a positive int print message and ask for input again
print("Sorry, input must be a positive integer, try again")
continue
break
except ValueError:
print("That's not an int!")
# else all is good, val is >= 0 and an integer
print(val)
what you need is something like this:
goodinput = False
while not goodinput:
try:
number = int(input('Enter a number: '))
if number > 0:
goodinput = True
print("that's a good number. Well done!")
else:
print("that's not a positive number. Try again: ")
except ValueError:
print("that's not an integer. Try again: ")
a while loop so code continues repeating until valid answer is given, and tests for the right input inside it.

Is there a way to go to specific line or command in python?

I am going through book automate boring stuff with python and trying to solve the practical problems.
In this project I need to define collatz() function and print results as seen in code until it gets 1.
So basically i need to input only one number and program should return numbers until it returns 1.
Program works fine but i have one question if i can make it better :D .
My question is after using try: and except: is there a way to not end process when typing string in input function but to get message below 'You must enter number' and get back to inputing new number or string and executing while loop normally. Code works fine just wondering if this is possible and if so how?
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
else:
print(3 * number + 1)
return 3 * number + 1
try:
yourNumber = int(input('Enter number: '))
while True:
yourNumber = collatz(yourNumber)
if yourNumber == 1:
break
except ValueError:
print('You must enter a number')
Put the try/except inside a loop, such that on the except the loop will continue but on a success it will break:
while True:
try:
yourNumber = int(input('Enter number: '))
except ValueError:
print('You must enter a number')
else:
break
while yourNumber != 1:
yourNumber = collatz(yourNumber)

How do I check if a input is an integer type [duplicate]

This question already has answers here:
How do I determine if the user input is odd or even?
(4 answers)
Closed 4 years ago.
I tried to make a odd/even 'calculator' in python and it keeps popping up errors. Here's the code:
def odd_even():
print("Welcome to Odd/Even")
num = input("Pick a number: ")
num2 = num/2
if num2 == int:
print("This number is even")
else:
print("This number is odd")
Id like to know whats causing the errors and solutions to them
There is an error in the line: num = input("Pick a number: ")
Because input method always returns a String,so you should convert it into int to performs the integer operation
The currect code is:
num =int( input("Pick a number: "))
you can't do math with strings convert it to int
try:
num = int(input("Pick a number: "))
except ValueError:
print('This is not a number!')
return

Check if input is positive integer [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I need to check whether what the user entered is positive. If it is not I need to print an error in the form of a msgbox.
number = input("Enter a number: ")
###################################
try:
val = int(number)
except ValueError:
print("That's not an int!")
The above code doesn't seem to be working.
Any ideas?
while True:
number = input("Enter a number: ")
try:
val = int(number)
if val < 0: # if not a positive int print message and ask for input again
print("Sorry, input must be a positive integer, try again")
continue
break
except ValueError:
print("That's not an int!")
# else all is good, val is >= 0 and an integer
print(val)
what you need is something like this:
goodinput = False
while not goodinput:
try:
number = int(input('Enter a number: '))
if number > 0:
goodinput = True
print("that's a good number. Well done!")
else:
print("that's not a positive number. Try again: ")
except ValueError:
print("that's not an integer. Try again: ")
a while loop so code continues repeating until valid answer is given, and tests for the right input inside it.

Loop on if-statement to reject invalid input [duplicate]

This question already has answers here:
Integers as the only valid inputs
(3 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
In python is there a way to redo a raw input and if statement if the answer is invalid?
So for instance if you ask the user to guess 1 or 2, and they guess 3 you create the additional elif or else to tell the user that the answer is invalid and go through the raw input / if statement again?
I believe you want something like this:
# Loop until a break statement is encountered
while True:
# Start an error-handling block
try:
# Get the user input and make it an integer
inp = int(raw_input("Enter 1 or 2: "))
# If a ValueError is raised, it means that the input was not a number
except ValueError:
# So, jump to the top of the loop and start-over
continue
# If we get here, then the input was a number. So, see if it equals 1 or 2
if inp in (1, 2):
# If so, break the loop because we got valid input
break
See a demonstration below:
>>> while True:
... try:
... inp = int(raw_input("Enter 1 or 2: "))
... except ValueError:
... continue
... if inp in (1, 2):
... break
...
Enter 1 or 2: 3
Enter 1 or 2: a
Enter 1 or 2: 1
>>>
Use a while statement:
try:
x = int(raw_input('Enter your number: '))
except ValueError:
print 'That is not a number! Try again!'
while x != 1 and x != 2:
print 'Invalid!'
try:
x = int(raw_input('Enter your number: '))
except ValueError:
print 'That is not a number! Try again!'
This code starts off by taking the necessary input. Then, using a while loop, we check to see if x is 1 or 2. If not, we enter the while loop and ask for input again.
You could also do this:
while True:
try:
x = int(raw_input('Enter your number: '))
except ValueError:
print 'That is not a number! Try again!'
if x in [1, 2]:
break

Categories