Checking if input meets the requirements before printing anything - python

input_list = raw_input("Enter numbers separated by spaces: ")
number = input_list.split()
if len(number) == 5:
for n in number:
a = int(n)
if 0< a <=5:
print 'x'* a
elif a == 0:
print '.'
else:
print "Number does not lie in the range 0 to 5."
else:
print "Invalid Input."
I want my program to check if the 5 inputted numbers meets all the conditions and if even one them fails to print INVALID INPUT and stop the program. Also I don't quite understand how my program checks each inputted number on its own as my teacher helped me but didn't explain it .
The program should ask for the number five times before printing anything
The program must check that the input are numbers are between 0 and 5. It will also fail if a number of digits is entered other than 5. Failed input can terminate the program with an appropriate error message.
Inputted numbers may be duplicates. (ex. 3, 3, 3, 0, 0 is acceptable input.)

This is what Python's assert statement does:
>>> x = 5
>>> try:
... assert(x==4)
... except(AssertionError):
... print("Error!")
...
>>> Error!
In the assert clause, you are stating a boolean condition which you are forcing to be true. If it is not true, you can catch the error using the except statement and handle it there.
In your case you could have:
assert(((x <= 5) and (x >= 0)))

number = raw_input("Enter numbers separated by spaces: ")
2 num_list = number.split()
3 for n in num_list:
4 a = 'True'
5 if int(n) <0 or int(n) >5:
6 a = 'False'
7 break
8 if (len(num_list) == 5) and a == 'True':
9 for n in num_list:
10 b = int(n)
11 if 0< b <=5:
12 print ('x'* b)
13 elif b == 0:
14 print ('.')
15 else:
16 print 'Invalid Input!'

Related

hailstone program in python

i have to write a hailstone program in python
you pick a number, if it's even then half it, and if it's odd then multiply it by 3 and add 1 to it. it says to continue this pattern until the number becomes 1.
the program will need methods for the following:
accepting user input
when printing the sequence, the program should loop until the number 1.
print a count for the number of times the loop had to run to make the sequence.
here's a sample run:
prompt (input)
Enter a positive integer (1-1000). To quit, enter -1: 20
20 10 5 16 8 4 2 1
The loop executed 8 times.
Enter a positive integer (1-1000). To quit, enter -1: 30
30 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
The loop executed 19 times.
Enter a positive integer (1-1000). To quit, enter -1: -1
Thank you for playing Hailstone.
right now i have this:
count = 0
def hailstone(n):
if n > 0
print(n)
if n > 1:
if n % 2 == 0:
hailstone(n / 2)
else:
hailstone((n * 3) + 1)
count = count + 1
i don't know what to do after this
Try to think in a modular way, make two functions: check_number() and user_call(). Check_number will verify if the current number in the loop is odd or even and the user_call() just wraps it to count how many times the loop did iterate.
I found the exercise in a great book called Automate Boring Stuff with Python, you have to check it out, if you don't know it already.
Here's my code. Try to use what serves you the best.
from sys import exit
def check_number(number):
if number % 2 ==0:
print(number // 2)
return(number // 2)
else:
print(number*3+1)
return number*3+1
def user_call(number):
count = 0
while number != 1:
count += 1
number = check_number(number)
return count
if __name__ == "__main__":
try:
number = int(input('Give a number \n'))
count = user_call(number)
print('count ',count)
except Exception as e:
exit()
you can use global
visit https://www.programiz.com/python-programming/global-keyword to learn more
import sys
res = []
def hailstone(number):
global res
if number > 1:
if number % 2 == 0:
res.append( number // 2 )
hailstone(res[len(res)-1])
else:
res.append(number * 3 + 1)
hailstone(res[len(res)-1])
return res
number = int(input('Enter a positive integer. To quit, enter -1: '))
if number <= 0 or number == 0:
print('Thank you for playing Hailstone.')
sys.exit()
else:
answers = hailstone(number)
for answer in answers:
print(answer)
print('The loop executed {} times.'.format(len(answers) + 1))
I used recursion to solve the problem.
Heres my code:
Edit: All criteria met
count = 0
list_num = []
def input_check():
number = int(input("Enter a positive integer (1-1000). To quit, enter -1: "))
if number >= 1 and number <= 1000:
hailstone_game(number)
elif number == -1:
return
else:
print("Please type in a number between 1-1000")
input_check()
def hailstone_game(number):
global count
while number != 1:
count += 1
list_num.append(number)
if number % 2 == 0:
return hailstone_game(int(number/2))
else:
return hailstone_game(int(number*3+1))
list_num.append(1) # cheap uncreative way to add the one
print(*list_num, sep=" ")
print(f"The loop executed {count} times.")
return
input_check()
Additional stuff that could be done:
- Catching non-integer inputs using try / except
Keep in mind when programming it is a good habit to keep different functions of your code separate, by defining functions for each set of 'commands'. This leads to more readable and easier to maintain code. Of course in this situation it doesn't matter as the code is short.
Your recursive function is missing a base/terminating condition so it goes into an infinite loop.
resultArray = [] #list
def hailstone(n):
if n <= 0: # Base Condition
return
if n > 0:
resultArray.append(n)
if n > 1:
if n % 2 == 0:
hailstone(int(n/2))
else:
hailstone((n * 3) + 1)
# function call
hailstone(20)
print(len(resultArray), resultArray)
Output
8 [20, 10, 5, 16, 8, 4, 2, 1]
Here's a recursive approach for the problem.
count=0
def hailstone(n):
global count
count+=1
if n==1:
print(n)
else:
if n%2==0:
print(n)
hailstone(int(n/2))
else:
print(n)
hailstone(3*n+1)
hailstone(21)
print(f"Loop executed {count} times")

Python validation from if neither inputs equal a number

I am having an issue with Python validation. I was wondering if there was a simple way to put validation on two input numbers to check a few things:
If the inputs are ints
if neither of the inputs equals a certain number, they are not valid. (For example, this would mean one of them would have to be 5. So a = 1 b = 4, a = 3 b = 2, a = 1 b = 1 wouldn't work)
If the two numbers are the same number that is required it will not work (E.G. if a = 5 b = 5 will not work as 5 is the required number, however a = 1 b = 5 would work as 5 is only being inputted once).
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
val = int(a)
val1 = int(a)
if val1 != 5 or val != 5:
print("I'm sorry but it must be a pos int and equal 5")
continue
break
except ValueError:
print("That's not an int")
This is what I was trying to do, but I think I may be dreadfully wrong?
Any help appreciated!
Thanks.
Logical xor
You should continue the loop if exactly one a and b is equal to 5. It means you need a logical xor. Parens are needed to avoid comparing a to 5 ^ b:
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a)
b = int(b)
if (a != 5) ^ (b != 5):
print("I'm sorry but it must be a pos int and equal 5")
continue
break
except ValueError:
print("That's not an int")
It might not be very readable though.
Count 5's
You could count the number of ints equal to 5:
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a)
b = int(b)
count5 = [a, b].count(5)
if count5 == 1:
break
else:
print("Exactly one input should be equal to 5.")
except ValueError:
print("That's not an int")
If you want to differentiate between errors:
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a)
b = int(b)
count5 = [a, b].count(5)
if count5 == 2:
print("Inputs cannot both be equal to 5.")
elif count5 == 0:
print("At least one input should be equal to 5.")
else:
break
except ValueError:
print("That's not an int")
Here's an example:
Enter first input: 3
Enter second input: 1
At least one input should be equal to 5.
Enter first input: 5
Enter second input: 5
Inputs cannot both be equal to 5.
Enter first input: 3
Enter second input: 5
Logic... if True then break, False then print error message...
Two things... you want logical exclusive or so that True ^ True = False
You aren't storing b. The text you're printing doesn't explain what's happening.
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a) # like the readable code using a not val1...
b = int(b)
if (a != 5) ^ (b != 5): # added parens as suggested
break
else:
print("I'm sorry but it must be a pos int and equal 5")
continue
except ValueError:
print("That's not an int")
Output
Enter first input: 5
Enter second input: 5
I'm sorry but it must be a pos int and equal 5
Enter first input: 1
Enter second input: 5
runfile('...')
Enter first input: 5
Enter second input: 5
I'm sorry but it must be a pos int and equal 5
You could use:
(a == 5 and b != 5) or (a != 5 and b == 5)
Or this:
(a == 5) != (b == 5)
(!= is the boolean equivalent of bitwise xor)

Automate the boring tasks - exercise - collatz function

Beginner question here.
I have just attempted an exercise from Automate the boring stuff. I've completed the question in the format suggested by first defining a function as below:
"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."
and then using that same function, meeting those minimal constraints, to write a programme that meets the following requirements:
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.
I've managed to generate a sequence of numbers ending with one, following the above rules, but my program prints each number in the sequence three times. Is anyone able to explain why this might be?
Thanks so much for your help
def collatz(number):
if int(number) % 2 == 0:
print(int(number)//2)
return int(number)//2
else:
print(3 * int(number) + 1)
return 3 * int(number) + 1
collatz(5)
print('Enter a number')
entry = input()
while collatz(entry) != 1:
collatz(entry)
entry = collatz(entry)
Your loop should look like this:
entry = input()
while entry != 1:
entry = collatz(entry)
You are calling the function 3 times and you have a print call in the function.
Only call the function once and I would remove the print statements from the collatz method and just print in the calling loop, e.g.:
In []:
def collatz(number):
if number % 2 == 0:
return number//2
return 3*number + 1
entry = int(input("Enter a number: "))
print(entry)
while entry != 1:
entry = collatz(entry)
print(entry)
Out[]:
Enter a number: 10
10
5
16
8
4
2
1
You can try:
def collatz(number):
if number == 0:
return 'Try again with an integer other than 0'
elif number == 1:
return 1
elif number % 2 == 0:
n = number // 2
print(n)
elif number % 2 == 1:
n = 3 * number + 1
print(n)
while n != 1:
n = collatz(n)
return n
return n
The last statement return n in line 15 is optional.

How can I log the highest and lowest number entered in Python?

I don't realize what is my mistake, this is how far I got now:
x = 1
e = 0
while x <= 50:
print "Please enter a number (from 1 to 9):"
b = float(raw_input())
asd = 0
if asd == 0:
h = b
l = b
asd = 1
if b < l:
l = b
elif b > h:
h = b
if 1 <= b or b <= 9:
x = x * b
print x
else:
print "Number is too large or too small."
e = e + 1
print "You have reached a value over 50."
print "Highest number entered:", h
print "Lowest number entered:", l
print "Entered numbers:", e
This is the program's output:
Please enter a number (from 1 to 9):
5
5.0
Please enter a number (from 1 to 9):
4
20.0
Please enter a number (from 1 to 9):
5
100.0
You have reached a value over 50.
Highest number entered: 5.0
Lowest number entered: 5.0
Entered numbers: 3
Why is the program giving me 5 instead of 4 as lowest number entered and how can I correct that?
You keep resetting asd each iteration, you need to set the variables outside the loop, I would use a list and that will enable you to get the min/max and number of valid inputs :
nums = [] # hold all nums outside the loop
limit = 1
while 50 >= limit:
num = float(raw_input("Please enter a number (from 1 to 9)")
if 1 <= num <= 9:
limit *= num
nums.append(num) # add all to list
else:
print "Number is too large or too small."
print "You have reached a value over 50."
print "Highest number entered:", max(nums)
print "Lowest number entered:", min(nums)
print "Entered numbers:", len(nums)
Everytime you go through the loop, you are setting asd to 0, causing the if statement below it to execute every single time, so you are always blindly updating l with the value the user just entered, which you have named as b
just for fun :)
def get_float_input(msg="Enter a Number:"):
while True:
try:
return float(raw_input(msg))
except ValueError:
print "Invalid Input Please Enter A Float!"
from itertools import takewhile
my_list = sorted(takewhile(lambda val:val < 50,iter(get_float_input,"Y")))
print "You Have Entered A # Greater than 50"
print "Min:",my_list[0]
print "Max:",my_list[-1]
print "Entered %d Numbers"%len(my_list)

Separating an inputted integer into a list to check if each element of the list meets the requirements

input_list = input("Enter numbers separated by spaces: ")
number = input_list.split()
for n in number:
a = int(n)
if len(number)!=5 or number>5 or number<0 :
print ('invalid input')
if 0< a <=5:
print ('x'* a)
elif a == 0:
print ('.')
My program is checking the 5 digits which are inputted as if they are one number but I want my program to first make sure that 5 digits are inputed and then check if they are between 0 and 5 but the program combines all 5 digits into one number, I want the program to check each element of the list on it's own and before printing anything I want the program to check if the inputted number meets all the conditions and if does not to print (Invalid Input) and stop their
input_list = input("Enter numbers separated by spaces: ")
numbers = input_list.split()
if len(numbers) == 5 and all(0 <= int(n) <= 5 for n in numbers):
print("ok")
print("".join(numbers))
else:
print("invalid")
I use raw_input in python 2. input is fine for python 3.
input_list = raw_input("Enter numbers separated by spaces: ").split()
numbers = [int(n) for n in input_list if 0 <= int(n) <= 5]
if len(numbers) != 5:
print ('invalid input')
for a in numbers:
if a == 0:
print ('.')
else:
print ('x'* a)
input_list = input("Enter numbers separated by spaces: ")
number = input_list.split()
if len(number) == 5:
for n in number:
a = int(n)
if 0< a <=5:
print ('x'* a)
elif a == 0:
print ('.')
else:
print ("Number does not lie in the range 0 to 5.")
else:
print ("Invalid Input.")
Yes, the above works but is should check input first to make sure it is valid
number = raw_input("Enter numbers separated by spaces: ")
2 num_list = number.split()
3 for n in num_list:
4 a = 'True'
5 if int(n) <0 or int(n) >5:
6 a = 'False'
7 break
8 if (len(num_list) == 5) and a == 'True':
9 for n in num_list:
10 b = int(n)
11 if 0< b <=5:
12 print ('x'* b)
13 elif b == 0:
14 print ('.')
15 else:
16 print 'Invalid Input!'

Categories