sorry - just a simple task, of asking for higher input unless its equal or less than previous input.
does it require a place holder for the input value or am I missing a break?
num=input("Enter a number: ")
while True:
num <= num
print("Something is wrong")
num=input("Try again: ")
if num >= num:
print("Keep going higher!")
code output
Something is wrong
Try again
import sys
num_tmp = -sys.maxsize - 1 # this expression returns lowest possible number
while True:
num = input("Enter a number: ") # input returns string value
if not num.isdecimal(): # checking if input contains only digits
print("Not a number, try again.")
continue # skips futher instructions and go to next iteration
elif int(num) < num_tmp: # int(num) converts string to integer
print("Entered number is lower that previous. That's all. Bye.")
break # breaks loop execution ignoring condition
num_tmp = int(num) # updating num_tmp for comparsion in next iteration
print("Keep going higher!")
Related
I don't understand why is not working on my code
def random_calculation(num):
return((num*77 + (90+2-9+3)))
while random_calculation:
num = int(input("Pleace enter number: "))
if num == "0":
break
else:
print(random_calculation(num))
Can you guide me what is wrong here, i really dont understand
You have several errors in your code:
You cannot do while random_calculation like this. You need to call the function, but since inside the loop you are already checking for a break condition, use while True instead.
Also, you are converting the input to int, but then comparing agains the string "0" instead of the int 0
Here's the corrected code:
def random_calculation(num):
# 90+2-9+3 is a bit strange, but not incorrect.
return((num*77 + (90+2-9+3)))
while True:
num = int(input("Please enter number: "))
if num == 0:
break
# you don't need an else, since the conditional would
# break if triggered, so you can save an indentation level
print(random_calculation(num))
so,when you start the loop it ask you what number you want to enter and then the code checks if the number is == to 0. IF the number is equal to 0: break the loop. IF the number is equal to any other number it prints the "random_calculation" function
I am new to coding. I would like to attend a course but there are assessments first in order to be chosen.
The question I am stuck on is:
Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1.
num = 0
inputs = []
while True:
num = int(input("Please enter a number between -1 and 5: "))
if num > -1:
break
else:
inputs.append(int(num))
print (sum(inputs) / len(inputs))
so lets break this down together.
This is fine.
num = 0
inputs = []
You will want to modify this while true statement to be while True (if using python) like below
while True:
Next, it doesn't explicitly say integers, and technically there are different number types, but for simplicity sake we check to see if the number entered is an integer to avoid trying convert a letter to an integer. (This will cause a ValueError). We make a decision to ignore this type of bad input and continue.
input_value = input("Please enter a number between -1 and 5: ")
try:
num = int(input_value)
except ValueError:
continue
The condition for stopping the loop is entering -1 (if I understood the question properly). So, first check to see if the number entered matches the condition to stop: if num == -1: break.
if num == -1:
break
otherwise, you will want to check to be sure the number is in range before it is added to your inputs array, otherwise ignore it and wait for the next input. The question asks for any number, but since you're prompting for specific input, we're making a decision here not to accept numbers out of bounds of what was prompted for.
elif num < -1 or num > 5:
continue
Finally, if input is not -1, and the input is a number between 0-5 inclusive, add it to the array and await the next input.
else:
inputs.append(num)
Finally at the end of the return after -1 was received, it is possible the first number entered was -1, or all values entered were invalid. Both of these scenarios would result in division by 0, and an error being thrown. So you would want to set the minimum number that can be set as the divisor to 1 to ensure you don't crash trying to calculate your answer:
print(sum(inputs) / max(len(inputs), 1))
And now putting it all together:
num = 0
inputs = []
while True:
input_value = input("Please enter a number between -1 and 5: ")
try:
num = int(input_value)
except ValueError:
continue
if num == -1:
break
elif num < -1 or num > 5:
continue
else:
inputs.append(num)
return sum(inputs) / max(len(inputs), 1)
Maybe this is the code you are looking for just changing if num > -1 to if num == -1 to agree with the question you posted:
num = 0
inputs = []
while True:
num = int(input("Please enter a number between -1 and 5: "))
if num == -1:
break
else:
inputs.append(num)
print(sum(inputs) / len(inputs))
and it works just fine having as a result:
Please enter a number between -1 and 5: 5
Please enter a number between -1 and 5: 4
Please enter a number between -1 and 5: 3
Please enter a number between -1 and 5: 2
Please enter a number between -1 and 5: 1
Please enter a number between -1 and 5: -1
3.0
I am writing code that will take an integer input from a user. If the integer is greater than 0 then the program will ask the user for a second integer input. If the second integer input is greater than 1 then the program will compute the first number raised to the power of the second number. I am unsure how to correctly implement a while true loop such that when a user enters a wrong input it will reprompt the user for that respective integer i.e. int 1 or 2. Really appreciate some help :)!
while True:
first_num= int(input("Enter the first integer:"))
if(first_num>0):
while True:
sec_num= int(input("Enter the second integer:"))
if(sec_num>1):
print(first_num**sec_num)
break
You have the break in the wrong place. Move it under the last if and it will continue prompting for the second number without going back to the first.
while True:
first_num= int(input("Enter the first integer:"))
if(first_num>0):
while True:
sec_num= int(input("Enter the second integer:"))
if(sec_num>1):
print(first_num**sec_num)
break
If you want to end the program after one success, then don't nest the whiles
while True:
first_num= int(input("Enter the first integer:"))
if(first_num>0):
break
while True:
sec_num= int(input("Enter the second integer:"))
if(sec_num>1):
print(first_num**sec_num)
break
Handle each number one at a time. Don't start trying to get the second number until you have a valid first number.
while True:
first_num = int(input(...))
if first_num > 0:
break
while True:
second_num = int(input(...))
if second_num > 1:
break
print(first_num ** second_num)
If you want to repeat the ** operation for multiple numbers, put everything inside a third loop.
while True:
while True:
first_num = int(input(...))
if first_num > 0:
break
while True:
second_num = int(input(...))
if second_num > 1:
break
resp = input("Try again?")
if not resp.lower().startswith("y"):
break
I'm trying to create a while loop function with digits. Basically, my function is to keep adding up numbers until a non-digit is entered, and then I can break the loop. However, when I enter a non-digit input, the non-digit also get added to the equation and result in an error.
How can I exclude the non digit from the equation?
sum_num = 0
while True:
num = input("Please input a number: ")
sum_num = int(sum_num) + int(num)
if num.isdigit() != True:
print(sum_num)
break
I would be using a try except to catch the error. This makes it clear that you are avoiding such.
The reason your code doesn't work is because you are trying to add the "nondigit" (string) to a "digit" (integer) before you even check if this is possible, which you do after you've already caused the error. If you move the if statement above, your code will work:
sum_num = 0
while True:
num = input("Please input a number: ")
if num.isdigit() != True:
print(sum_num)
break
sum_num = int(sum_num) + int(num)
If you wrap it in a try/except it should do what you want.
while True:
num = input("Please input a number: ")
try:
sum_num = int(sum_num) + int(num)
except ValueError as ex:
print(sum_num)
break
I'm doing a certain online course and I've completed the assignment with this code, but I can still induce a bug with certain inputs, and I can't understand why. I've asked the course mentors (using pseudo code) and they say there's a problem with my try/except statement.
The program should prompt a user for a number, over and over again, returning an error if something non-numeric is entered, with the exception of the string 'done,' in which case it will return the maximum and minimum of all the numbers entered.
Here's the program:
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done': break
try:
float(num)
except:
print("Invalid input")
continue
if largest is None:
largest = num
elif largest < num:
largest = num
if smallest is None:
smallest = num
elif smallest > num:
smallest = num
print("Maximum is", largest)
print("Minimum is", smallest)
If you enter the following values as input 1 2 3 pk 27 -37 done, the output is Max: 3, Min -37.
It's driving me crazy. I have do idea why this is happening.
You are casting the input to a float, but not retaining that for later checks.
So later on after the except block, Python is doing string comparisons and is comparing the string "3" to the string "27" and since '3' is 'larger' than '2' it considers "3" larger than "27", much like "b" is larger than "aaabbbbzzz".
To fix it change this:
float(num)
to this:
num = float(num)