Python 3 Count and While Loop - python-3.x

I am trying to figure out an error in the code below. I need the following conditions to be met:
1) If equal to zero or lower, I need python to state "Invalid Input"
2) If greater than zero, ask whether there is another input
3) As long as there is another input, I need the program to keep asking
4) If "done", then I need Python to compute the lowest of inputs. I have not gotten to this part yet, as I am getting an error in the "done" portion.
print ("Lowest Score for the Racer.")
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
while True:
number = float(input('Do you have another input? If "Yes" type another score, if "No" type "Done": '))
if number < 0 or number == 0:
print ("Input should be greater than zero. Please enter score: ")
if number == "Done":
print ("NEED TO COUNT")
break

I tried to modify your code according to your desired output. I think this should give you an idea. However there is still small things to deal in code. I suppose you can manage rest of it.
empthy_list = []
print ("Lowest Score for the Racer.")
while True:
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
if number > 0:
empthy_list.append(number)
reply = input('Do you have another input? If "Yes" type another score, if "No" type "Done": ')
if reply == "Yes" :
number = float(input("Please enter score: "))
empthy_list.append(number)
if reply == "Done":
print("NEED TO COUNT")
print("Lowest input is: ",min(empthy_list))
break

I wrote an alternative solution which is more robust regarding input errors. It might include some ideas for improving your code but probably isn't the best solution, either.
print ("Lowest score for the racer.")
valid_input = False
num_arr = []
while not valid_input:
foo = input('Please enter score: ')
try:
number = float(foo)
if number > 0:
num_arr.append(number)
valid_input = True
else:
raise ValueError
while foo != 'Done' and valid_input:
try:
number = float(foo)
if number > 0:
num_arr.append(number)
else:
raise ValueError
except ValueError:
print('Invalid input! Input should be number greater than zero or
"Done".')
finally:
foo = input('Do you have another input? If yes type another score,
if no type "Done": ')
except ValueError:
print('Invalid input! Input should be number greater than zero.')
print("Input done! Calculating lowest score...")
print("Lowest score is ", min(num_arr))

Related

Is there a possibility to add "less than" exception to this piece of code in Python?

I'm quite new to coding and I'm doing this task that requires the user to input an integer to the code. The function should keep on asking the user to input an integer and stop asking when the user inputs an integer bigger than 1. Now the code works, but it accepts all the integers.
while True:
try:
number = int(input(number_rnd))
except ValueError:
print(not_a_number)
else:
return number
You can do something like this:
def getPositiveInteger():
while True:
try:
number = int(input("enter an integer bigger than 1: "))
assert number > 1
return number
except ValueError:
print("not an integer")
except AssertionError:
print("not an integer bigger than 1")
number = getPositiveInteger()
print("you have entered", number)
while True:
# the input return value is a string
number = input("Enter a number")
# check that the string is a valid number
if not number.isnumeric():
print(ERROR_STATEMENT)
else:
if int(number) > 1:
print(SUCCESS_STATEMENT)
break
else:
print(NOT_BIGGER_THAN_ONE_STATEMENT)
Pretty simple way to do it, of course you must define ERROR_STATEMENT, SUCCESS_STATEMENT and NOT_BIGGER_THAN_ONE_STATEMENT to run this code as it is, I am using them as place-holder.

Odd/even range in python3.x

Given an input range (lowest/highest) and choice(odd/even) how can I print the desired output in python? In the below code it doesn't seem to be executing the else condition
low = int(input("Lowest number: "))
high = int(input("Highest number: "))
oddeven = input("Do you want to see odd or even numbers: ")
print(oddeven)
for num in range(low, high):
if (num % 2 == 0):
print(num)
else :
if (num % 2 == 1):
print(num)
I think the easiest solution to implement, would be for you to create two for loops, one for the even case and one for the odd case, so you only have to check once rather than for each iteration of the for loop:
def get_int_input(prompt: str) -> int:
while True:
try:
return int(input(prompt))
except ValueError:
print("Error: Enter an integer, try again...")
low = get_int_input("Enter the lowest number in the range (inclusive): ")
high = get_int_input("Enter the highest number in the range (inclusive): ")
valid_odd_even_responses = {"odd", "even"}
odd_even_response = ""
while odd_even_response not in valid_odd_even_responses:
odd_even_response = input(
"Do you want to see odd or even numbers: ").lower()
if odd_even_response == "odd":
for num in range(low, high + 1):
if num % 2 == 1:
print(num)
else:
for num in range(low, high + 1):
if num % 2 == 0:
print(num)
Example Usage:
Enter the lowest number in the range (inclusive): -1
Enter the highest number in the range (inclusive): 13
Do you want to see odd or even numbers: even
0
2
4
6
8
10
12
Some thoughts:
Check your indentation (look that "else")
"oddeven" is useless
You don't need num % 2 == 0, just num % 2, because, in python, 0 is 'false' already
You don't need the second 'if', because the 'else' is already doing the job bifurcating the flow in your program
If you're learning, try to draw your algorithm with paper and pencil before implementing it
Happy coding!
The first two lines are OK:
low = int(input("Lowest number: "))
high = int(input("Highest number: "))
Here, I add a clarification that tells the user how to answer the question. Your code does not use this variable, that is why you get the wrong output.
even = int(input("Do you want to see odd (0) or even (1) numbers: "))
If the user wants even numbers but low is not even, or the other way around, adjust it:
if (even and low % 2 == 1) or (not even and low % 2 == 0):
low += 1
Step though all odd or even numbers:
print("\n".join(str(x) for x in range(low, high + 1, 2)))

How to show invalid input

My task is:
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
I want to ignore any invalid integer and print 'Invalid Output' message after calculating the maximum and minimum number.But it always prints the invalid message right after user input. How am i supposed to solve this?
Thanks in advance.
Code:
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
n = int(num)
except:
print('Invalid input')
if largest is None:
largest=n
elif n>largest:
largest=n
elif smallest is None:
smallest=n
elif n<smallest:
smallest=n
print("Maximum", largest)
print('Minimum', smallest)
You could store that invalid output as a boolean variable
largest = None
smallest = None
is_invalid=False
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
n = int(num)
except:
is_invalid=True
if largest is None:
largest=n
elif n>largest:
largest=n
elif smallest is None:
smallest=n
elif n<smallest:
smallest=n
print("Maximum", largest)
print('Minimum', smallest)
if is_invalid:
print('Invalid Input')
This can be one solution
largest = None
smallest = None
errors = False
while True:
num = input('Please type a number : ')
if num == 'done':
break
try:
number = int(num)
#your logical operations and assignments here
except ValueError:
errors = True
continue
if errors:
print('Invalid input')
else:
print('Your Results')
Hope this helps :)
If you are familiar with lists,you can use list to solve your problem effectively,
here is a modified version of your code which uses list,
num1=[]
while True:
num = input("Enter a number: ")
num1.append(num)
if num == "done":
break
for i in num1:
try:
i = int(i)
except:
print('Invalid input:',i)
num1.remove(i)
print("Maximum", max(num1))
print('Minimum', min(num1))
output:
Enter a number: 34
Enter a number: 57
Enter a number: 89
Enter a number: ds
Enter a number: 34
Enter a number: do
Enter a number: done
Invalid input: ds
Invalid input: do
Maximum 89
Minimum 34
hope this helps,let me know if anything is incorrect.
Try removing the (int) in try block. Because you want only integer input in try block so if does not satisfy the condition of integer input it will execute the except block.
Your code should look like this in try block:
try:
n = num

How to fix issue where python won't call a function from within a loop

At the yes/no loop, the program won't call the function to re-perform a calculation. Instead, it asks to compute another gcd repeatedly instead of calling the specified function.
I've tried re-inputting the whole function into the question loop if the user inputs yes, but that did not work either.
def gcd(n,m):
if(m==0):
return n
else:
return gcd(m,n%m)
n = int(input("Enter a positive whole number:"))
while True:
if n <= 0:
print ("The number entered is not a positive number!, please try again")
n = int(input("Enter a positive whole number : "))
if n > 0: break
m = int(input("Enter a second positive whole number:"))
while True:
if m <= 0:
print ("The number entered is not a positive number!, please try again")
m = int(input("Enter a positive whole number : "))
if m > 0: break
GCD = gcd(n,m)
print("The GCD of the two numbers you entered is:" ,GCD)
while True:
a = input("Compute another GCD? Enter y/n:").lower()
if a=="y":
gcd(n,m)
elif a=="n":
break
else:
print("Invalid entry. Please enter either y/n:")
print("Goodbye!")
Expected results is that it calls the function gcd(n,m) and re-performs a calculation. Actual results is that it asks to perform another calculation without having actually completed a second calculation.
The function is called. The problem is that you don't do anything with its return value.
You will also need to ask the user for new input. In order to not repeat the same code again you can have a function that does that.
Then the whole code becomes:
def get_2_numbers():
n = int(input("Enter a positive whole number:"))
while True:
if n <= 0:
print ("The number entered is not a positive number!, please try again")
n = int(input("Enter a positive whole number : "))
if n > 0: break
m = int(input("Enter a second positive whole number:"))
while True:
if m <= 0:
print ("The number entered is not a positive number!, please try again")
m = int(input("Enter a positive whole number : "))
if m > 0: break
return n, m
def gcd(n,m):
if(m==0):
return n
else:
return gcd(m,n%m)
a, b = get_2_numbers()
while True:
answer = input("Compute another GCD? Enter y/n:").lower()
if answer == "y":
print(gcd(a, b))
a, b = get_2_numbers()
elif answer == "n":
break
else:
print("Invalid entry. Please enter either y/n:")
print("Goodbye!")
A small downside is that the user will have to answer y even before the first calculation, but I'll leave that as an exercise to the reader.

I cant make the program continue to loop if its invalid input is entered

I have this program:
number = int(input('Contact Number:'))
def validatePhoneNumber(number):
count = 0
while True:
while number > 0:
number = number//10
count = count+1
if (count == 10) :
break
elif (count > 10) :
print('Invalid phone number')
return -1
elif (count < 10):
print('Invalid phone number')
return -1
validatePhoneNumber(number)
it will appear like this:
Contact Number:1234
Invalid phone number
>>>
I want it to continue to loop until a 10 digit number is entered then it will stop.
Contact Number:1234567890
>>>
The condition is that If the number is missing or invalid, return ‐1.
Am I missing something inside the program?
Thanks
What about this:
number = input('Contact Number:') # it's a str now, so we can use len(number)
def validatePhoneNumber(number):
while len(number) != 10:
number = input("Please enter a 10-digit contact number: ")
return number
number = validatePhoneNumber(number)
It's a more pythonic approach and therefore easier to understand and debug. Also as other comments pointed out, leading 0s aren't stripped away now.

Resources