Python issues for user inputting specific values - python

I am having issues regarding python. My issue is that my code always prints the first if statements return even if the user inputs a valid integer. I genuinely do not know the issue. I have to allow the user to input a value that is restricted to 1-10 and I have to be able to output either, "Please input an integer between 1-10" or "That's not even a number silly!". Could someone please help me and do more than just write the code, but explain it too?
value = input("Please input an integer: ")
def numValue(value):
for value in range(-1000, 1000):
if (value < 1, value > 10):
return "Please input a number between 1-10."
elif (value >= 1, value <= 10):
return "Great choice!"
print (numValue(value))

First you need to tell python that you are expecting an integer. This is done by wrapping int(..) around input
You have an unnecessary for loop with range. It is not needed
The syntax to check if a number is between a range is start < num < end or (<=) if you want the range to be inclusive
You don't to add the inverse check in elif, using else will automatically fallback if original condition fails
value = int(input("Please input an integer: "))
def numValue(value):
if 1 <= value <= 10:
return "Great choice!"
else:
return "Please input a number between 1-10."
print (numValue(value))

Related

Fixing While Loops Python

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}!')

Can anyone figure out this code for me?

import random
print "Welcome to the number guesser program. We will pick a number between 1 and 100 and then ask you to pick a number between 1 and 100. If your number is 10 integers away from the number, you win!"
rand_num = random.randint(1, 100)
user_input = raw_input('Put in your guess:').isdigit()
number = int(user_input)
print number
if abs(rand_num - number) <= 10:
print "Winner"
else:
print "Loser"
Whenever I try to run this code, the computer always generates the number 1. And if I put in a number that is 10 (or less) integers away from one it will still display the else statement. I will have my gratitude to whoever can solve my predicament. I am new to python try to keep your answers simple please.
raw_input returns a string you entered as input. isdigit() checks whether a string is a digit or not and returns True or False.
In your code you're assigning the return value of isdigit to user_input So, you get either True or False. Then you convert it to a number, thus getting either one or zero. This is not what you want.
Let user_input be just a result of raw_input. Then check whether it is a valid number with user_input.isdigit(). If it's not a number, print an error message and exit (or re-ask for input), else convert user_input to an integer and go on.
The problem is product by this sentenc:
user_input = raw_input('Put in your guess:').isdigit().
The return value of isdigit() is True or False. When you enter 1 or any digit number, it will return True(True=1,False=0), so you will always get 1, if you enter digit. You can change like this:
import random
print "Welcome to the number guesser program.
We will pick a number between
1 and 100 and then ask you to pick a number
between 1 and 100. If your number is 10 integers
away from the number, you win!"
rand_num = random.randint(1, 100)
user_input= raw_input('Put in your guess:')
is_digit = user_input.isdigit()
if is_digit==True:
number = int(user_input)
print number
if abs(rand_num - number) &lt= 10:
print "Winner"
else:
print "Loser"
else:
print 'Your input is not a digit.'
Look at this line:
user_input = raw_input('Put in your guess:').isdigit()
The function raw_input gives you user input, but then you call isdigit and as consequence in your variable user_input you get result of isdigit. So, it has boolean value.
Then in
number = int(user_input) you cast it to integer type. In python true is 1 and false is 0. That's why you always get 1.

limiting invalid input in python 3

I need to limit the number of invalid inputs allowed so that after the given amount of tries the program exits.
Invalid is defined by the input being less than zero.
The number of attempts let say is 3.
def number():
number = float(input('please enter a number (must be greater thatn zero): '))
if number >= 0 :
print ('you choose number:', number)
else:
print ('invalid input')
return
number()
How would I limit the number of invalid input attempts and make it so that the code would return to asking the question again and prompt for input but still keep track of previous attempts?
You have to use a loop, in this case a while loop will be convinient. You have to declare a variable invalid_attempts to keep the count of how many invalid inputs the user has given.
The condition to finish the loop will be when invalid_attempts, which is increased when you get an invalid input, is greater or equal to 3. You may want to change 3 to fit your requirements:
def get_input():
invalid_attempts = 0
while invalid_attempts < 3:
number = float(input('please enter a number (must be greater thatn zero): '))
if number >= 0 :
print ('you choose number:', number)
return number # so you can call the method as 'some_variable = get_input()'
else:
print ('invalid input')
invalid_attempts += 1
Note: Since number is the name of the method, you shouldn't call a variable inside with the same name (because if you do, you won't be able to use that function inside, if it's necessary), in this case I'm calling the method get_input.
Use whilie loop before number = ..., for instance:
count = 0
while count < 3:
# do rest of the stuffs
count += 1
Actually, I think a for loop looks nicer:
for retry in range(5): # number of retries
try:
choice = float(input('please enter a number (must be greater thatn zero): '))
except ValueError:
print('Please enter an actual number')
continue
if choice >= 0:
print('You chose ', choice)
break
else:
print('Number must be >= 0')
continue
else:
print('Too many failures: be more cooperative')
(This is called a for-else construct; the else runs only if the for loop did not break).
You can also do it slightly more elegantly using recursion:
def get_number(max_tries, count = 0)
if count < max_tries:
valid_input = False
number = 0
try:
number = float(input('Please enter a number > 0'))
if number > 0:
valid_input = True
except:
pass
if valid_input:
return number
else:
return get_numbers(max_tries, count+1)
else:
print('Sorry, Too many Tries!)
return None
Whether you use a while loop or recursion is usually a matter of taste. They're functionally equivalent in many situations, of which this is on. This example also accounts for what happens if the user enters something that isn't a number, which will cause the float cast to throw.
Update:
To clarify a question asked by the OP:
def get_numbers(max_tries, count = 0)
Defines a function get_numbers, which takes two inputs, max_tries and count. count is given a default value, count = 0, which means if you call the function without specifying the count parameter, it will automatically assign it to be 0. max_tries is left without a default value, meaning you need to specify it every time you call the function or python will throw an error. If you usually have the same number of maximum tries, you could also assign this a default value, which would allow you to simply do number = get_numbers() and have it work as expected.
Recursion, to over-simplify, is basically when a function calls itself during its execution. Let's assume we did the following:
number = get_number(10)
And the user enters -1, which will cause the code to reach:
else:
return get_numbers(max_tries, count+1)
Since we said get_numbers(10), max_tries = 10, and count = 0, so this line becomes:
else:
return get_numbers(10, 1)
This causes the function to return the result of calling get_numbers again. Eventually the user will either enter valid input, or count > max_tries, which will cause the function to finally return a value.
Read the wiki I liked to, recursion is hard to explain without drawing it, but hopefully that helps.

Flowchart in Python

I need to write a prog in Python that accomplishes the following:
Prompt for and accept the input of a number, either positive or negative.
Using a single alternative "decision" structure print a message only if the number is positive.
It's extremely simply, but I'm new to Python so I have trouble with even the most simple things. The program asks for a user to input a number. If the number is positive it will display a message. If the number is negative it will display nothing.
num = raw_input ("Please enter a number.")
if num >= 0 print "The number you entered is " + num
else:
return num
I'm using Wing IDE
I get the error "if num >= 0 print "The number you entered is " + num"
How do I return to start if the number entered is negative?
What am I doing wrong?
Try this:
def getNumFromUser():
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
else:
getNumFromUser()
getNumFromUser()
The reason you received an error is because you omitted a colon after the condition of your if-statement. To be able to return to the start of the process if the number if negative, I put the code inside a function which calls itself if the if condition is not satisfied. You could also easily use a while loop.
while True:
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
break
Try this:
inputnum = raw_input ("Please enter a number.")
num = int(inputnum)
if num >= 0:
print("The number you entered is " + str(num))
you don't need the else part just because the code is not inside a method/function.
I agree with the other comment - as a beginner you may want to change your IDE to one that will be of more help to you (especially with such easy to fix syntax related errors)
(I was pretty sure, that print should be on a new line and intended, but... I was wrong.)

Getting an Integer Input in a Range

I'm trying to take a raw input and detect whether it is in a range.
Here's my code.
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if next == int in range(50):
how_much = int(next)
else:
dead("Man, learn how to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
When I enter a number it gives me the else: "Man, learn how to type a number."
I guess the line that isn't working is "if next == int in range(50):
Could anyone help me out?
Thanks in advance!
Edit:
I'm a noob so that line was just me ballparking.
I thought it would check next to see if it was an integer in the range of numbers 0-50.
If you want to "get an integer input in a range", you'll need two things:
Check if the input is an int
Check if it's in your range
Check if the input is an int
try/except will be perfect here:
n = raw_input('> ')
try:
n = int(n)
except ValueError:
dead() # or what you want
Why this is good?
Because if n is an int you'll have it convert it to an integer and if it's not an exception get raised and you can call your dead() funcion.
Check if it's in your range
If you get to this point it means that the exception before it was not raised and n was converted to an integer.
So you just need to do:
if 0 <= n <= 50:
print 'You win'
else:
print 'You lose'
Don't do:
if n in range(50):
# ...
Beacuse it will build a list of 50 numbers for nothing.
Note: don't use next as a variable, beacuse it'll shadow the built-in next()
Since raw_input returns a string, you need to convert to an int first. Try replacing the line with this:
if int(next) in range(50):
The result of raw_input() will be a string, so first you need to check to see if next is all digits. There are a few ways to do this, the easiest is to use the str.isdigit() function:
next = raw_input("> ")
if next.isdigit():
how_much = int(next)
else:
dead("Man, learn how to type a number.")
Note that you do not need to check to see if the value for next is in the range from 0 to 50, since your next if statement already checks to see if the value is less than 50 and negative numbers will be excluded by next.isdigit().
The test "next == int in range(50)" evaluates to "(next == int) and (int in range(50))" which is fairly meaningless and always equates to false.
Instead you could try
try:
how_much = int(next)
if not (0<=how_much<50):
print 'Too greedy'
except ValueError:
dead("Man, learn how to type a number.")
Using try .. except will allow you to make sure entered value is an int. # raise is a place holder for your handling a non-int contition:
try:
next = int(raw_input("> "))
except ValueError:
# raise
if not 0 <= next <= 50:
print 'Too greedy'

Categories