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)
Related
I am trying to control the user's input using exception handling. I need them to only input a positive number, and then I have to return and print out that number.
I have to send a message if the user puts in non-number and I have to send a message if the user puts in a number less than 1. Here is what I have:
def input_validation(prompt):
boolChoice = True
while boolChoice == True:
try:
l = input(prompt)
x = int(l)
boolChoice = False
except ValueError:
print("Not a valid input")
if l.isalpha() == True:
print("Your input is not a number")
elif l.isalnum() == True:
print ("Your input is not completely a positive number")
elif l < 0:
print("Your number is not positive")
print("Try again")
return x
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
My program works fine until a negative integer gets inputted. It doesn't print the message and then goes through the loop again, it just returns and prints back the negative number, which I don't want. How can I fix this? Thank you.
You can use try...except to check if its an integer or letters
def input_validation(prompt):
while True:
try:
l = int(input(prompt))
if l<0: #=== If value of l is < 0 like -1,-2
print("Not a positive number.")
else:
break
except ValueError:
print("Your input is invalid.")
print("Try again")
return l
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
try
def input_validation(prompt):
boolChoice = True
while boolChoice == True:
try:
l = input(prompt)
x = int(l)
if x < 0:
print ("Your input is a negative number\n Please enter a postive number")
elif x == 0:
print("Your input is zero\n Please enter a postive number ")
else:
boolChoice = False
except Exception as e:
print("Not a valid input")
if l.isalpha() == True:
print("Your input is not a number")
elif l.isalnum() == True:
print ("Your input is not completely a positive number")
else:
print(f"Failed to accept input due to {e}")
print("Try again")
continue
return x
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
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()
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")
This is a simple program to check if a number is odd or even.I want to check if the user wants to continue or not and when I run it I get an Invalid Syntax Error on the break line, what have I got wrong?
while True:
if cont != "no":
num = (int(input("Type a number. ")))
num_remainder = num % 2
if num_remainder == 0:
print ()
print (num, " is an even number.")
else:
print ()
print (num, " is an odd number.")
cont= (input("Would you like to continue?")
continue
else:
break
Thanks
I think this is simpler,
while True:
num = int(input("Type a number. "))
print () # blank line before assert whether is or not a even number
if num % 2 == 0:
print (num, " is an even number.")
else:
print (num, " is an odd number.")
if input("Would you like to continue?") == 'no': # Ohh, you want to break now.
break
When running this code, I keep having an error. I would like to know what is wrong. The code has to be able to read words and integers and repeat the prompt(Please enter an integer >= 2: ') until it is greater or equal to 2. Thanks in advance.
def prime_number():
prime_num = input('Please enter an integer >= 2: ')
while not(prime_num.isdigit() and int(prime_num)<1):
prime_num = input('Please enter an integer >= 2: ')
for i in range(2,int(prime_num)+1):
for x in range(2,i):
if i%x == 0:
break
else:
print (i)
You need to enter the function. This is typically done in python with:
def prime_number():
prime_num = input('Please enter an integer >= 2: ')
while not(prime_num.isdigit() and int(prime_num)<1):
prime_num = input('Please enter an integer >= 2: ')
for i in range(2,int(prime_num)+1):
for x in range(2,i):
if i%x == 0:
break
else:
print (i)
if __name__ == "__main__":
prime_number()
Just some advice in general. I would separate the input logic from the prime number calculation logic.
As mentioned by #rpattiso, you are not invoking the method and
You while condition is buggy
This should work:
def prime_number():
prime_num = input('Please enter an integer >= 2: ')
while not (prime_num.isdigit() and not int(prime_num)<1):
prime_num = input('Please enter an integer >= 2: ')
for i in range(2,int(prime_num)+1):
for x in range(2,i):
if i%x == 0:
break
else:
print (i)
prime_number()