Using a While loop in python when asking for something specific - python

Question is to
Prompt the user for a number from 1 to 100. Using a while loop, if they entered an invalid number, tell them the number entered is invalid and then prompt them again for a number from 1 to 100. If they enter a valid number - thank them for their input.
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y is True:
print("invalid.")
int(input("please enter a number 1-100, inclusive: ")
else:
print("thank you for your input")
my code is incorrect. Help me fix it please?

Aren't you missing a parenthesis in the statement before else: ? Looks like it says else: is invalid due to that.

Besides the syntax error (missing ) before the line of else, your code also have logical error, you need to set the y = False when user give proper input to get out from the while loop, like :
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y is True:
print("invalid.")
value = int(input("please enter a number 1-100, inclusive: "))
if value >= 0 and value <= 100:
y = False
else:
print("thank you for your input")

Simplification and correction of your code
while True:
x = int(input("please enter a number 1-100, inclusive: "))
if 1 <= x <= 100: # range check
print("thank you for your input")
break # terminates while loop
else:
print("invalid.") # print then continue in while loop

#Krish says a really good answer about how you are missing a second bracket during the line that you prompt inside the while loop. I assume you receive a SyntaxError about it (probably listing the immediately following line--unfortunately common in software).
Solution
However, you have a much more fundamental issue with your code: you never update y so you have an infinite loop that will always think that the input is invalid.
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y: # it is unnecessary to check a boolean against a condition
print("invalid.")
x = int(input("please enter a number 1-100, inclusive: ")) # missing bracket
y = x<0 or x>100 # necessary to end the loop
else:
print("thank you for your input")
Improvement
Another option is to use break to exit the loop on the spot. It can make for cleaner code with less duplication because now everything is inside the loop.
while True: # infinite loop...but not because of break
x = int(input("please enter a number 1-100, inclusive: "))
if x<0 or x>100:
print("invalid.")
else:
print("thank you for your input")
break
Advanced
For completeness I will also include a couple more advanced features. You can skip this part since you are starting out, but it may be interesting to come back to once you have become more familiar with the language.
Lambda
Helps make the code cleaner.
user_input = lambda: int(input("please enter a number 1-100, inclusive: "))
condition = lambda x: x<0 or x>100
while condition(user_input()):
print("invalid.")
else:
print("thank you for your input")
Cmd
This one is really advanced and overkill for what you are trying to accomplish. Still, it is good to know about for a later, more advanced problem that it would be appropriate for. Docs found here.
from cmd import Cmd
class ValidNumberPrompter(Cmd):
"""
This is a class for a CLI to prompt users for a valid number.
"""
prompt = "please enter a number 1-100, inclusive: "
def parseline(self, line): # normally would override precmd but this is modifying the way the line is parsed for commands later
command, args, line = super().parseline(line) # superclass behaviour
return (command, args, int(line))
def default(self, line): # don't care about commands
if line<0 or line>100:
print("invalid.")
return False
else:
print("thank you for your input")
return True
"""
Only start if module is being run at the cmdline.
If it is being imported, let the caller decide
what to do and when to run it.
"""
if __name__ = '__main__':
ValidNumberPrompter().cmdloop()

Related

Python - Function to check if user input matches a condition

I'm writing a script that is asking for user to input a number between 1-10, the script will then call the function Size and will return true if the number is greater or equal to 5 and false if not. However, I seem to have run into a bit of a wall, I get an error asking me to define x, this is my code currently.
def Size(x):
if x >= 5:
print("True")
else:
print("False")
x = int(input("Please enter a number greater than 5"))
Size(x)
You declared user input x in the Size function. X should be an outside size function
def Size(x):
if x >= 5:
print("True")
else:
print("False")
x = int(input("Please enter a number greater than 5"))
Size(x)
Or if you want to take user input in Size function then initialize x in Size function and pass just Size function then follow the second answer
You were close, you need to correct 3 things in your code.
Ask user for input before doing checks in your function.
Remove variable passed in your user defined function.
You need to change name of your function for safer side to make it more meaningful, so I changed it to funcSize.
#!/usr/bin/python3
def funcSize():
x = int(input("Please enter a number greater than 5: "))
if x >= 5:
print("True")
else:
print("False")
funcSize()
Define x outside the function. Rest of the code is correct.
def Size(x):
if x >= 5:
print("True")
else:
print("False")
x = int(input("Please enter a number greater than 5"))
Size(x)
The error occured because I didn't fix my indentation after the false statement.

How to check every input for isdigit

I am trying to write a game that generates a random integer and the user has to guess it.
The problem is that if the user input is not a digit it crashes. So I tried to use isdigit, and it works at the beginning, but if the user decides to input not a number after the first input was a digit, it still crashes. I don't know how to make it check isdigit for every input.
import random
x =(random.randint(0,100))
print("The program draws a number from 0 to 100. Try to guess it!")
a = input("enter a number:")
while a.isdigit() == False :
print("It is not a digit")
a = input("enter a number:")
if a.isdigit() == True :
a = int(a)
while a != x :
if a <= x :
print("too less")
a = input("enter a number:")
elif a >= x :
print("too much")
a = input("enter a number")
if a == x :
print("good")
I would suggest doing the following:
completed = False
while not completed:
a = input("enter a number: ")
if a.isdigit():
a = int(a)
if a < x:
print("too little")
elif a > x:
print("too much")
else:
print("good")
completed = True
else:
print("It is not a digit")
If your code crashed because the user entered not a number, then either make sure the user enters a number, or handle an error while trying to compare it with a number.
You could go over all chars in the input and ensure that they are all digits.
Or you could use a try/except mechanism. That is, try to convert to the numerical type you wish the user to enter and handle any error throwen. Check this post:
How can I check if a string represents an int, without using try/except?
And also:
https://docs.python.org/3/tutorial/errors.html
The typical pythonic way to tackle that would be to "ask for forgiveness instead of looking before you leap". In concrete terms, try to parse the input as int, and catch any errors:
try:
a = int(input('Enter a number: '))
except ValueError:
print('Not a number')
Beyond that, the problem is obviously that you're doing the careful checking once at the start of the program, but not later on when asking for input again. Try to reduce the places where you ask for input and check it to one place, and write a loop to repeat it as often as necessary:
while True:
try:
a = int(input('Enter a number: '))
except ValueError: # goes here if int() raises an error
print('Not a number')
continue # try again by restarting the loop
if a == x:
break # end the loop
elif a < x:
print('Too low')
else:
print('Too high')
print('Congratulations')
# user vs randint
import random
computer = random.randint(0,100)
while True:
try:
user = int(input(" Enter a number : "))
except (ValueError,NameError):
print(" Please enter a valid number ")
else:
if user == computer:
print(" Wow .. You win the game ")
break
elif user > computer:
print(" Too High ")
else:
print(" Too low ")
I think this can solve the issues.
In your code you want to check whether the user has input no or string since your not using int() in your input it will take input as string and furthur in your code it wont be able to check for <= condition
for checking input no is string or no
code:-
a = input ("Enter no")
try:
val = int(a)
print("Yes input string is an Integer.")
print("Input number value is: ", a)
except ValueError:
print("It is not integer!")
print(" It's a string")
You probably will have to learn how to do functions and write your own input function.
def my_input(prompt):
val = input(prompt)
if val.isdigit():
return val
else:
print('not a number')
# return my_input(prompt)

How to check user input for multiple conditions within same loop or function in Python 3?

I'm trying to take user-input but I need the input to be an integer, AND be between 1 and 9. I tried putting "in range(1,10)" in a few places in the code but it didn't work. I need the program to keep asking the user for the right input until they give the correct input. So far I've only been able to make sure their input is an integer with he following code. I will be taking input by using int(input("...")), rather than using input("...").
while True:
try:
ui1 = int(input("Player 1, Your move. Select your move. "))
break
except ValueError:
print("You have to choose a number between 1 and 9")
continue
Add a check before the break and move the error message to the end of the loop.
while True:
try:
ui1 = int(input("Player 1, Your move. Select your move. "))
if 1 <= ui1 <= 9:
break
except ValueError:
pass
print("You have to choose a number between 1 and 9")
Why not just check isdigit() and in range ?
while True:
ui1 = input("Player 1, Your move. Select your move. ")
if ui1.isdigit() and int(ui1) in range(1,10):
break
print("You have to choose a number between 1 and 9")
# Continue code out of the loop
# beJeb
# Stack overflow -
# https://stackoverflow.com/questions/51202856/how-to-check-user-input-for-multiple-conditions-within-same-loop-or-function-in
# Our main function, only used to grab input and call our other function(s).
def main():
while True:
try:
userVar = int(input("Player 1, Your move. Select your move: "))
break
except ValueError:
print("Incorrect input type, please enter an integer: ")
# We can assume that our input is an int if we get here, so check for range
checkRange = isGoodRange(userVar)
# Checking to make sure our input is in range and reprompt, or print.
if(checkRange != False):
print("Player 1 chooses to make the move: %d" %(userVar))
else:
print("Your input is not in the range of 1-9, please enter a correct var.")
main()
# This function will check if our number is within our range.
def isGoodRange(whatNum):
if(whatNum < 10) & (whatNum > 0):
return True
else: return False
# Protecting the main function
if __name__ == "__main__":
main()
Note: I tested a couple inputs so I believe this should be enough to help you understand the process, if not please comment, message, etc. Also, if this answer helps you, please select it as answered to help others.
Let the number be the input you are taking from the user.
while(1): #To ensure that input is continuous
number = int(input())
if number>=1 and number<=10 and number.isdigit():
break #if the input is valid, you can proceed with the number
else:
print("Enter a valid Number")
The number can be used for further operations.

Programming challenge while loops and for loops

I have been asked to make a piece of code including a for loop and a while loop. I was asked to:
Get the user to input a number
Output the times table for that number
Starts again every time it finishes
I was able to do the for loop like so:
num= int(input ("Please enter a number."))
for x in range (1,13):
print (num,"x",x,"=",num*x)
But I cannot figure out how to make it repeat, any ideas?
Just put your code inside a while loop.
while True:
num = int(input("Please enter a number: "))
for x in range(1,13):
print("{} x {} = {}".format(num, x, num*x))
I think it would be nice for you to handle errors.
If a user decides to enter a non digit character it will throw an error.
while True:
num = input('please enter a number')
if num ==0:
break
elif not num.isdigit():
print('please enter a digit')
else:
for x in range(1, 13):
mult = int(num)
print('%d x %d = %d' %(mult, x, mult*x))

Boolean return value?

def main():
num = int(input('Please enter an odd number: '))
if False:
print('That was not a odd number, please try again.')
else:
print('Congrats, you know your numbers!')
def number():
if (num / 2) == 0:
return True,num
else:
return False,num
main()
I am trying to make it so that if the number entered is odd, it congratulates the user. If not then it should tell them to try again. I am trying to return the Boolean value to main and then when I try to use the code in the main function to prompt the user, it doesn't work.
Your functions are very odd and I'm not talking about numbers that aren't divisible by 2. Try this:
num = int(input('Please enter an odd number: '))
if num % 2 == 0:
print('Better luck next time??') # no really, you should go back to school (;
else:
print('Genius!!!')
Try this:
num_entry = int(input('Please enter an odd number: '))
def number():
return num_entry % 2 == 0
def main():
if number() == True:
print('Sorry, please try again.')
else:
print('Nice! You know your numbers!')
number()
main()
This should work!
Your code does look odd like Malik Brahimi mentioned. This may be because you are trying to write your python code like Java, which requires a main method. There is no such requirement in python.
If you would like to have your check for the "odd-ness" of the number wrapped in a defined function that you can call elsewhere, you should try writing it like this.
def odd_check(number):
if number % 2 == 0:
#This is the check the check formula, which calculates the remainder of dividing number by 2
print('That was not an odd number. Please try again.')
else:
print('Congrats, you know your numbers!')
num = int(input('Please enter an odd number: ')) #where variable is stored.
odd_check(num) #This is where you are calling the previously defined function. You are feeding it the variable that you stored.
If you would like a piece of code that will continue to ask your user to enter a number until they get it right, try something like this:
while True: #This ensures that the code runs until the user picks an odd number
number = int(input('Please enter an odd number: ')) #where variable is stored.
if number % 2 == 0: #the check formula, which calculates the remainder of dividing num by 2
print('That was not an odd number. Please try again.')
else:
print('Congrats, you know your numbers!')
break #This stops the "while" loop when the "else" condition is met.

Categories

Resources