//I started learning python 2 weeks ago and right now stack with this problem for a few days. I need somobody to give me a hint or something close to solution. Thank you.Here is my code.
from math import sqrt
# Write your solution here
number = int(input("Please type in a number:"))
while True:
if number > 0:
print(sqrt(number))
break
if number == 0:
print("Invalid number")
break
if number < 0:
print("Exiting...")
break
//Expected output example
Please type in a number: 16
4.0
Please type in a number: 4
2.0
Please type in a number: -3
Invalid number
Please type in a number: 1
1.0
Please type in a number: 0
Exiting..
the first break statement always breaks out of the loop, so you never reach the second (and third if). you may want to indent it to be part of the if statements' bodies:
from math import sqrt
# Write your solution here
number = int(input("Please type in a number:"))
while True:
if number > 0:
print(sqrt(number))
break
if number == 0:
print("Invalid number")
break
if number < 0:
print("Exiting...")
break
Also, if you want to continue the loop until 0 is read, you may want to remove the first two break statements and move the input reading into the function:
from math import sqrt
# Write your solution here
while True:
number = int(input("Please type in a number:"))
if number > 0:
print(sqrt(number))
if number == 0:
print("Invalid number")
if number < 0:
print("Exiting...")
break
The conditions of the if's are mutually exclusive, so only one statement can be entered at a time.
In more complex scenarios, if you only want to enter one if statement, you may want to use elif or continue:
from math import sqrt
# Write your solution here
while True:
number = int(input("Please type in a number:"))
if number > 0:
print(sqrt(number))
continue # continue with next loop iteration, skip anything below
elif number == 0: # only check condition, if first loop condition was false
print("Invalid number")
elif number < 0:
print("Exiting...")
break
EDIT: John Gordon rightfully pointed out, that your cases for exit and invalid number are swapped. To make sure this is a complete solution, I will also incorporate this change:
from math import sqrt
# Write your solution here
while True:
number = int(input("Please type in a number:"))
if number > 0:
print(sqrt(number))
elif number < 0:
print("Invalid number")
elif number == 0:
print("Exiting...")
break
Related
We want to create a program that prompts the user to enter a number between 1 and 10. As long as the number is out of range the program reprompts the user for a valid number. Complete the following steps to write this code.
a.Write a line of code the prompts the user for number between 1 and 10.
number = float(input("Enter a number between 1 and 10: "))
b. Write a Boolean expression that tests the number the user entered by the code in step "a." to determine if it is not in range.
x = (number > 10 or number < 1)
c.Use the Boolean expression created in step b to write a while loopthat executes when the user input is out of range. The body of the loop should tell the user that they enteredan invalid number and prompt them for a valid number again.
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
d.Write the code that prints a message telling the user that they entered a valid number.
if x == False:
print("wow, you printed a number between 1 and 10!")
I answered the stuff for the question, but my problem is that whenever the user enters a wrong number on their first try and a correct number on their second try, the program still considers it as an invalid input. How do I fix this???
Rewrite this line in the while loop:
x = (number > 10 or number < 1)
so it becomes
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
x = (number > 10 or number < 1)
This changes the value of x so it doesn't stay at True
If you use a while True construct, you won't need to repeat any code. Something like this:
LO, HI = 1, 10
while True:
input_ = input(f'Enter a number between {LO} and {HI}: ')
try:
x = float(input_)
if LO <= x <= HI:
print(f'Wow! You entered a number between {LO} and {HI}')
break
print(f'{input_} is not in range. Try again')
except ValueError:
print(f'{input_} is not a valid number. Try again')
Note:
When asking for numeric input from the user, don't assume that their input can always be converted properly. Always check
The following code snippet should do all you need:
number = float(input("Please input a number: "))
while (number > 10 or number < 0):
number = float(input("Error. Please input a new number: "))
Use an infinite loop, so that you can prompt for the input only once.
Use break to terminate the loop after the number in the correct range is entered.
Use f-strings or formatted string literals to print the message.
while True:
num = float(input('Enter a number between 1 and 10: '))
if 1 <= num <= 10:
print('Wow, you printed a number between 1 and 10!')
break
else:
print(f'You printed an invalid number: {num}!')
question:
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 it.
Input:
7 ,2 , bob, 10, 4, done.
Desired output:
Invalid input
Maximum is 10
Minimum is 2
Actual output:
Invalid input
Invalid input
Maximum is 10
Minimum is 2
Code:
largest=-1
smallest=None
while True:
num =input("Enter a number: ")
try:
if num == "done" :
break
elif smallest is None:
smallest=int(num)
elif int(num)<smallest:
smallest=int(num)
elif int(num)>largest:
largest=int(num)
else:
raise ValueError()
except ValueError:
print("Invalid input")
print("Maximum is",largest)
print("Minimum is",smallest)
I think there's a more Pythonic way of doing this. Try this:
inputList = []
while True:
num = input("Enter a number:")
try:
num = int(num)
inputList.append(num)
except:
if num == "done":
break
else:
print ("Invalid input. Ignoring...")
print ("Maximum is:",max(inputList))
print ("Minimum is:",min(inputList))
Edit: This code works with Python3. For Python2, you might want to use raw_input() instead of input()
You are already capturing the ValueError in Exception,
So inside, try, you are raising ValueError there you leave the scope for this error.
When you accept input, and it accepts 4 as input, which is neither larger than largest (i.e. 10) nor smaller than the smallest (i.e. 2). So it lands in else part and raises ValueError (as per your code). Hence prints Invalid input twice in your case. So this part is unnecessary as well as makes your solution bogus.
Again, from efficiency point of view -
1 - You are checking smallest == None for every input, which takes O(1) time and is unnecessary if you take it any integer
Here is the solution you are looking for :-
largest=None
smallest=None
while True:
try:
num = input("Enter a number: ")
num = int(num)
if smallest is None:
smallest = num
if largest is None:
largest = num
if num < smallest:
smallest = num
elif num > largest:
largest = num
except ValueError:
if num == 'done':
break
else:
print("Invalid input")
continue
print("Maximum is",largest)
print("Minimum is",smallest)
New to this so please bear with me. I'm trying to run a loop that asks the user to input a number between 1 and 100. I want to make it to where if they enter a number outside of 100 it asks again. I was able to do so but I can't figure out if I'm using the correct loop. Also whenever I do get inbetween 1 and 100 the loop continues.
code below:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
else:
while user_input > 100:
try_again = int(input("try again "))
if try_again >= 1 and try_again <= 100:
print("There you go!")
I think the clearest way to do this is to start with a loop that you break out of when you finally get the right answer. Be sure to handle a bad input like "fubar" that isn't an integer
while True:
try:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
break
print("Not between 1 and 100, try again")
except ValueError:
print("Not a number, try again")
In python 3 you can use range to do bounds checking. If you do
if user_input in range(1, 101)
range will calculate the result without actually generating all of the numbers.
When your code is run, it will continue to ask for an input, even if the input given is less than 100. One way to fix this would be to do this:
try_again = 1000
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
elif user_input > 100:
while try_again > 100:
try_again = int(input("try again "))
if try_again >= 1 and try_again <= 100:
print("There you go!")
This code first tests if the user's input is more than 100, then runs a while statement in which the base value is more than 100. When the user inputs another value, if it is over 100, it continues, otherwise it does not.
Below is an example of a program that gets you the output that you are seeking:
attempts = 0
while True:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input > 100 or user_input < 1:
print('Please try again')
attempts += 1
continue
elif attempts >= 1 and user_input <= 100 and user_input >= 1:
print('There you go!')
break
else:
print('Nice!')
break
Start by putting your prompt for the user within the loop so that the user can be asked the same prompt if the fail to enter a number between 1 and 100 the first time. If the user input is greater than 100 or less than 1, we will tell the user to try again, we will add 1 to attempts and we will add a continue statement which starts the code again at the top of the while loop. Next we add an elif statement. If they've already attempted the prompt and failed (attempts >= 1) and if the new input is less than or equal to 100 AND the user input is also greater than or equal to 1, then the user will get the 'There you go' message that you assigned to them. Then we will break out of the loop with a break statement in order to avoid an infinite loop. Lastly we add an else statement. If the user satisfies the prior conditions on the first attempt, we will print 'Nice' and simply break out of the loop.
As part of a larger menu-driven program, I'd like to test user input to see if that input:
is an integer AND
if it is an integer, if it is within the range 1 to 12, inclusive.
number = 0
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
except ValueError:
print("Invlaid input, please try again >>> ")
continue
else:
if not (1<= number <=12):
print("Need a whole number in range 1-12 >>> ")
continue
else:
print("You selected:",number)
break
I'm using Python 3.4.3, and wanted to know if there's a more succinct (fewer lines, better performance, more "Pythonic", e.g.) way to achieve this? Thanks in advance.
You don't need anything bar one if in the try:
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
if 1 <= number <= 12:
print("You selected:", number)
break
print("Need a whole number in range 1-12 >>> ")
except ValueError:
print("Invlaid input, please try again >>> ")
Bad input will mean you go straight to the except, if the input is good and is in your accepted range, the print("You selected:", number) and will be executed then we break or else print("Need a whole number in range 1-12 >>> ") will be executed if is outside the range.
Your code looks pretty good to me. Minor fix-ups (spelling, indentation, unnecessary continues):
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
except ValueError:
print("Invalid input, please try again >>> ")
else:
if 1 <= number <= 12:
print("You selected: {}".format(number))
break
else:
print("Need a whole number in range 1-12 >>> ")
Use isdigit() to check for non-digit characters. Then you shouldn't need to catch the exception. There's only one if and it uses operator short-circuiting to avoid doing int(blah) if blah contains non-digits.
while True:
num_str = raw_input("Enter a whole number between 1 and 12 >>> ")
if num_str.isdigit() and int(num_str) in range(1,13):
print("You selected:",int(num_str))
break
else:
print("Need a whole number in range 1-12 >>> ")
I don't think you need a whole try/except block. Everything can be fit into a single condition:
number = raw_input("Enter a whole number between 1 and 12 >>> ")
while not (number.isdigit() and type(eval(number)) == int and 1<= eval(number) <=12):
number = raw_input("Enter a whole number between 1 and 12 >>> ")
print("You selected:",number)
I am making a simple 'guess a number between one and ten' game. I have used some basic error handling and am printing the number generated by the random module for testing purposes.
However I would like to know if there is a less verbose way to write this.
This is the code:
import random
while True:
"""Variable declaration"""
number_of_attempts = 1
number = random.randrange (1,11)
print (number)
print("Time to play a guessing game! Muhahaha...")
"""Error handling and main game code/while loop"""
while True:
try:
guess = int(input("Guess a number between one and ten."))
except ValueError:
print("Input a whole number between one and ten silly!")
continue
if guess >= 1 and guess <= 10:
pass
else:
print("Input a number between one and ten silly!")
continue
if guess == number:
print("You were successful and it took you", number_of_attempts, "attempts!!!")
break
else:
print("Try again!")
number_of_attempts = number_of_attempts +1
"""Game Exit/Restart"""
play_again = input("Would you like to play again, y/n?")
if "y" in play_again or "yes" in play_again:
continue
else:
break
Thanks,
Ben
if guess >= 1 and guess <= 10:
Can be written as:
if 1 <= guess <= 10:
Also, your first conditional can simply be written as:
if not 1 <= guess <= 10:
print("Input a number between one and ten silly!")
continue
But this can also be put inside the try bit, saving you from writing continue twice:
try:
guess = int(input("Guess a number between one and ten."))
if not 1 <= guess <= 10:
print("Input a number between one and ten silly!")
continue
except ValueError:
print("Input a whole number between one and ten silly!")
continue
Finally your last conditional can simply be:
if play_again not in ('y', 'yes'):
break
The continue isn't needed.
You may also want to wrap this all up into a function as well, to get rid of those infinite while loops and to prevent you from using continue and break so much.
Why not put the actual conditions on the while loops so you don't have to hunt for breaks to understand the loops? It would make your code clearer and smaller.
if guess == number:
print("You were successful and it took you", number_of_attempts, "attempts!!!")
break
For instance if you put guess == number as the while loop conditional then the print would be the first thing after the loop. Initialize guess to -1 so it always works the first time. The play again if statement could also disappear into the loop conditional as well.