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}!')
Related
we have been tasked with writing a program in python asking a user to enter multiple numbers.
the subject is while loops,so we can only make use of while loops and if statements.
when the user wants to stop the entry of numbers,the user then needs to type '-1'.
once that has been done,the program must return the average of the numbers entered by the user.
this is what i have so far:
#task 13-while.py
#first the program will explain to the user that the user can keep
#entering numbers until -1 occurs.
num = int(input('''please enter any number of your choice\n
please enter -1 to stop entry and run program'''))
num_count = 0
while num > -1:
num_count = num_count + 1
average = sum(num)/num_count
if num == -1:
print("the average of the numbers you have entered is"+ average)
extremely inexperienced with python,all help will be greatly appreciated.
You need to put the input into the while and then only when the loop is over calculate the averageLike this:
num = int(input("enter numbers and then -1 to stop: "))
num_count = 1
sum = num
while num!=-1:
num = int(input("another number: "))
num_count+=1
sum+=num
print(sum/num_count)
In order for it to work you need to add an input() call inside the while loop like in the code bellow :
count = 0
sum = 0
num = int(input('''please enter any number of your choice\n
please enter -1 to stop entry and run program\n'''))
while num != -1:
sum += num
count +=1
num = int(input('''Give another integer\n'''))
print("the average of the numbers you have entered is", sum/count)
Personal advice : I would suggest for you to read more tutorials or ask your peofessor for more work
This code takes the users input and changes it to an integer and then checks if the int is between 0 and 10. I would also like this code to validate the users input against floats and non-numerical strings and loop back if the user enters a bad input. EX: user inputs 3.5 or "ten" and gets an Error and loops again.
pyramid = int(input("Please enter an integer between 0 and 10 to begin the sequence: "))
while pyramid < 0 or pyramid > 10:
print("That value is not in the correct range. Please try again.")
pyramid = int(input("Please enter an integer between 0 and 10 to begin the sequence: "))
I'd suggest to try to:
loop indefinitely (while 1)
Cast the input to a float, if this succeeds you can check if it has any decimals (pyramid % 1 != 0) and print the appropriate error in this case.
Cast the input to a integer and break the loop, if it is.
print an error that the input is not an integer
while 1:
str_in = input("Please enter an integer between 0 and 10 to begin the sequence: ")
try:
pyramid = float(str_in)
if(pyramid % 1 != 0):
print("That value is a float not an integer. Please try again.")
continue
except:
pass
try:
pyramid = int(str_in)
if pyramid >= 0 and pyramid <= 10:
break
except:
pass
print("That value is a string not an integer. Please try again.")
print("Your value is {}".format(pyramid))
got a error while compiling the code.
I tried to find smallest and largest value from user's input by storing the input in lists. After 'int' object not iterate problem, couldn't proceed further
largest=0
smallest=0
num=[]
while True:
num = int(input("Please enter a number: "))
for i in num:
if i>largest:
largest=i
for j in num:
if j<smallest:
smallest=j
if num==12:
break
print(largest)
print(smallest)
The moment you issue below code line num is no longer a list, instead its an int type of data.
num = int(input("Please enter a number: "))
As you can understand, there is nothing to iterate over in case of a single integer value.
The right solution is to read your input to a separate variable and append to your list.
input_num = int(input("Please enter a number: "))
num.append(input_num)
Further you will have to change value of your exit clause
if num==12:
break
If you desire to stop the loop after 12 inputs, then use len(num) == 12 in the if condition. In case you want to break loop if input number is 12 then change if condition to if input_num == 12
Note: Your algorithm has logical errors as well. You are assigning smallest to 0 . In case user enters all positive integers as input, your result will incorrect.
You are trying to iterate through a number which is wrong, you have overwritten your num list to an integer. Instead of the following:
num = int(input("Please enter a number: "))
You should save the number in some other variable and add to num list like:
x = int(input("Please enter a number: "))
num.append(x)
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 writing a Collatz sequence program using the practice projects from chapter 3 of Automate the boring stuff with python.
The program outline is:
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.
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.
My code runs however it stops on 4 rather than 1. For every number I have tried so far the output goes past 1 back to 4.
example output:
6,3,10,5,16,8,4,2,1,4
I am using python 3.4.2
def collatz(number):
if number % 2 == 0:
number = number //2
print(number)
return number
elif number % 2 == 1:
number = 3 * number + 1
print(number)
return number
print ("pick a number:")
while True:
try:
number = int(input())
while number != 1:
number = collatz(number)
collatz(number)
break
except ValueError:
print("Error: Please enter a valid integer")
print("Magic! You are down to 1.")
The problem is that you call collatz() once more after the loop finishes with 1. Just remove that line, and it works fine.
Also if you move the "pick a number" to the input function, you can avoid the new line after the question and are asked again every time, if you input an invalid value.
Additionally you should also check if the number is greater than or equal to 1, to avoid endless loops. The code to do all that would look like that:
while True:
try:
number = int(input("pick a number: "))
if number < 1:
print("Error: Please enter a integer greater than or equal to 1 ")
continue
while number != 1:
number = collatz(number)
# removed the additional call to collatz
break
except ValueError:
print("Error: Please enter a valid integer")
print("Magic! You are down to 1.")
def collatz(number):
number = number // 2 if number % 2 == 0 else 3 * number + 1
print(number)
return number
number = int(input("Pick a Number\n"))
while number != 1:
number = collatz(number)
print("Magic! You are down to 1.")