Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to not accept the username if it is not between 3 and 9 characters.
print (""+winner+", please input your first name, maximum of 10 characters.")
winnername = str(input())
length = (int(len(winnername)))
if 3 > length > 10:
loop5 = 1
while loop5 == 1:
print ("name is too short")
winnername = input()
length = len(winnername)
if (length) <3 and (length) <10:
break
print ("name accept")
I would expect it to loop and ask the user for another input if the provided input doesn't meet the requirements outlined in the above text.
if 3 > length > 10: is checking to make sure that length is LESS than 3 and Greater than 10, which is impossible.
Therefore the check should be if 2 < length < 10: (this will be true for lengths 3 to 9)
Let me fix your code, elegant and clean:
while True:
# I don't know if `winner` is defined
firstname = input(""+winner+", please input your first name, maximum of 10 characters.")
if 3 < len(firstname) < 10:
break
print("name is too short or too long")
print('name accepted')
The problem is 3 > length > 10 will never be executed because 3 will never be greater > than 10
Regarding your first sentence, as far as I can see form the code you are actually trying to allow maximum number of characters to be 10, not 9.
Below is a possible solution for what you're trying to achieve. The below script will keep asking user until name length is within allowed range.
print ("'+winner+', please input your first name, maximum of 10 characters.")
while True:
winnername = str(input())
if(len(winnername) < 3):
print("Name is too short")
elif(len(winnername) > 10):
print("Name is too long")
else:
break
print ("Name accepted")
You may also consider to perform some validation of winnername first (do not allow spaces or any other special characters).
winner = "Mustermann"
# Build a string called "prompt"
prompt = winner + ", please input your first name, between 3 and and 10 characters."
loopLimit = 5 # Make this a variable, so it's easy to change later
loop = 0 # Start at zero
winnername = "" # Set it less than three to start, so the while loop will pick it up
# Put the while loop here, and use it as the length check
# Use an or to explicitely join them
while True: # Set an infinite loop
loop += 1 # Increment the loop here.
# Add the string to the input command. The "input" will use the prompt
# You don't need the "str()", since input is always a string
winnername = input(prompt)
length = len(winnername)
# Separate the checks, to give a better error message
if (length < 3):
print ("Name is too short!") # Loop will continue
elif (length > 10):
print("Name is too long!") # Loop will continue
else: # This means name is OK. So finish
print("Name accepted!")
break # Will end the loop, and the script, since no code follows the loop
if loop >= loopLimit:
# Raise an error to kill the script
raise RuntimeError("You have reached the allowed number of tries for entering you name!")
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 days ago.
Improve this question
print("Welcome to the number program")
number=input("Please give me a number \n")
number=int(number)
total_number=0
entries=0
while number>0:
total_number=total_number+number
print(total_number)
number=input("Please give me another number! \n")
number=int(number)
entries= int(entries)+1
if number < 0 :
print("Sorry, this value needs to be positive. Please enter a
different number.")
if number == -999:
print(total_number)
print(entries)
print(total_number/entries)
I'm in a beginners programming class, and the book is not very helpful at times. I'm trying to write a basic program that takes positive numbers, totals them, and averages them out at the end. Also rejects negative numbers, and asks if -999 is entered I print the average of all entries, amount of entries, and the value tally. Any advice or tips I can learn from to improve it would be helpful. Thanks!
The program runs ok, it just doesn't write out some things I wanted
From what you wrote and the comments in your code I am guessing that you want the program to continue running and asking for input if you enter a non-positive number. In that case I would rewrite it as:
print("Welcome to the number program")
total_number = 0
entries = 0
while True:
number = input("Please give me a number \n")
number = int(number)
if number == -999:
break
if number <= 0:
print("Sorry, this value needs to be positive. Please enter a different number.")
continue
total_number = total_number + number
entries += 1
print(total_number)
print(total_number)
print(entries)
print(total_number / entries)
Also, you can increment numbers with entries += 1
In most cases you should NOT create variables first, however this case you should. Create number = 0, tally = 0 and total_number = 0 first
Accept your first number inside your while loop and handle all of the logic in there as well.
Your while loop should continue to loop until the final condition is met which seems to be number == -999
Should tally be incremented if you enter a negative number? I assume not. What about a 0? Wrap the increment for tally and the addition to total_number in an if number > -1: condition. Use an if else to check for number == -999, and an else for handling invalid entries.
Finally, move your print statements outside of your while loop. It also doesn't need a condition around it because now, if you've exited your while loop, that condition has been satisfied.
Final note here, and this is just a nice to know/have and purely syntactic sugar, MOST languages support abbreviated incrementing. Theres a better word for it, but the gist is simply this.
total_number += number
# is exactly the same as
total_number = total_number + number
# but way nicer to read and write :)
print("Welcome to the number program")
number = 0
total_number = 0
entries = 0
while number != -999:
number = input("Please enter a number! \n")
number = int(number)
if number >= 0
total_number += number
entries += 1
print("Current sum: " + total_number)
elif number == -999:
break
else
print("Sorry, this value needs to be positive.")
print("Sum of entries: "+str(total_number))
print("Number of entries: " + str(entries))
print("Average entry: " +str(total_number/entries))
I have rewritten your code. But I am not sure what the goal was. Anyways, if the value were ever to be under 0 the loop would have been exited and a new value would have never been accepted from an input.
Also some things I have written more elegant.
print("Welcome to the number program")
number=int(input("Please give me a number \n"))
total_number=0
entries=0
while number > 0:
total_number += number
print(total_number)
number = int(input("Please give me another number! \n"))
entries += 1
if number == -999:
print(total_number)
print(entries)
print(total_number/entries)
break
elif number < 0:
number = input("Sorry, this value needs to be positive. Please enter a different number!")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 12 months ago.
I'm new to python and I am trying to figure out how do I enter an error message if the user inputs a number less than zero.
Here is my code to give you a better understanding and I thank you all in advance for any advice.
# Python Program printing a square in star patterns.
length = int(input("Enter the side of the square : "))
for k in range(length):
for s in range(length):
if(k == 0 or k == length - 1 or s == 0 or s == length - 1):
print('*', end = ' ')
else:
print('*', end = ' ')
print()
Here is a simple and straight forward way to use a while loop to achieve this. Simple setting an integer object of check to 0. Then the while loop will evaluate check's value, then take user input, if the user input is greater than 0, let's set out check object to 1, so when we get back to the top of the loop, it will end.
Otherwise, if the if check fails, it will print a quick try again message and execute at the top of the loop again.
check = 0
while check == 0:
length = int(input("Enter the side of the square : "))
if length > 0:
check = 1
else:
print("Please try again.")
You can use this code after the input statement and before for loop.
if length < 0 :
Print("invalid length")
Break
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm trying to create a game of last man standing in python, but when you input a number it outputs the negative version of the correct answer? Also, when i enter anything other than 1, 2, or 3, I get the error: ValueError: could not convert string to float: '(anything other than the numbers)'
any help is appreciated. Thanks!
import random
num = random.randrange(20, 30)
print ("The number is " + str(num) + ", take either one, two or three away from it!")
take = float(input("input either 1, 2 or 3: "))
newnum = take - num
if take == 1:
print(newnum)
elif take == 2:
print(newnum)
elif take == 3:
print(newnum)
else:
print("please enter either 1, 2 or 3!")
You could just use a while loop to make sure the user only inputs 1,2 or 3.
import random
num = random.randrange(20, 30)
print ("The number is " + str(num) + ", take either one, two or three away from it!")
take = None
while take not in {1,2,3}: #{} faster than ()
take = int(input("input either 1, 2 or 3: "))
print("please enter either 1, 2 or 3!")
print(num-take)
Also as the above code shows, you need to use num-take instead of vice-versa.
This question already has answers here:
Limiting user input to a range in Python
(5 answers)
Closed 3 years ago.
I am trying to create a loop where the user is given choices 1-8 and if they do not choose 1-8, it loops them back around re-enter number 1-8. I am attempting to use a while loop with two conditions. What am I missing?
fm_select = int(input("Enter a number 1-8"))
while fm_select <= 8 and fm_select >= 1:
Your ranges are wrong. You want the while loop to fail when they are correct, since you're trying to break out of the loop. So, you want your loop to check against every number that isn't between one and eight. Instead, do
fm_select = 0
while (fm_select < 1 or fm_select > 8):
fm_select = int(input("Enter a number between one and eight: "))
"As long as their input is less than one or higher than eight, keep asking"
something like this should work
while(True):
fm_select = int(input("Enter a number 1-8"))
if 0 < fm_select < 8:
break
print("try again")
print("you have entered %d" %(fm_select) )
I want to write a program with this logic.
A value is presented of the user.
Commence a loop
Wait for user input
If the user enters the displayed value less 13 then
Display the value entered by the user and go to top of loop.
Otherwise exit the loop
You just need two while loops. One that keeps the main program going forever, and another that breaks and resets the value of a once an answer is wrong.
while True:
a = 2363
not_wrong = True
while not_wrong:
their_response = int(raw_input("What is the value of {} - 13?".format(a)))
if their_response == (a - 13):
a = a -13
else:
not_wrong = False
Although you're supposed to show your attempt at coding towards a solution and posting when you encounter a problem, you could do something like the following:
a = 2363
b = 13
while True:
try:
c = int(input('Subtract {0} from {1}: '.format(b, a))
except ValueError:
print('Please enter an integer.')
continue
if a-b == c:
a = a-b
else:
print('Incorrect. Restarting...')
a = 2363
# break
(use raw_input instead of input if you're using Python2)
This creates an infinite loop that will try to convert the input into an integer (or print a statement pleading for the correct input type), and then use logic to check if a-b == c. If so, we set the value of a to this new value a-b. Otherwise, we restart the loop. You can uncomment the break command if you don't want an infinite loop.
Your logic is correct, might want to look into while loop, and input. While loops keeps going until a condition is met:
while (condition):
# will keep doing something here until condition is met
Example of while loop:
x = 10
while x >= 0:
x -= 1
print(x)
This will print x until it hits 0 so the output would be 9 8 7 6 5 4 3 2 1 0 in new lines on console.
input allows the user to enter stuff from console:
x = input("Enter your answer: ")
This will prompt the user to "Enter your answer: " and store what ever value user enter into the variable x. (Variable meaning like a container or a box)
Put it all together and you get something like:
a = 2363 #change to what you want to start with
b = 13 #change to minus from a
while a-b > 0: #keeps going until if a-b is a negative number
print("%d - %d = ?" %(a, b)) #asks the question
user_input = int(input("Enter your answer: ")) #gets a user input and change it from string type to int type so we can compare it
if (a-b) == user_input: #compares the answer to our answer
print("Correct answer!")
a -= b #changes a to be new value
else:
print("Wrong answer")
print("All done!")
Now this program stops at a = 7 because I don't know if you wanted to keep going with negative number. If you do just edited the condition of the while loop. I'm sure you can manage that.