Loop is not geting exited in Python - python

I am trying to write a simple progrm in Python but when my number is getting equal to number the else statement keeps repeating itself. Help
print('Tell me your name Ramesh')
import random
name=input()
print('Howdy, '+name)
print('Guess my number which is in between 1 to 20')
number=input()
mynumber = random.randint(1, 20)
count = 0
while(mynumber!=number):
if (int(number) > mynumber):
print('Howdy, Your number is too high. Plz renter')
number=input()
count=count+1
elif (int(number)< mynumber):
print('Howdy, Your number is too low. Plz renter')
number=input()
count=count+1
else :
print('Howdy you got it in '+ str(count)+' chances. The correct number is '+number)

I've only just started python myself and had the same issue.
Your if statements all convert the entered number to an int however your while doesn't. so it's comparing an int and string. Try:
while(mynumber != int(number))
or change the input to read
number = int(input("blah")).
I like this more even though it will throw an error if you enter text.

You may also need to change the while to read while(mynumber != int(number)) as well as adding in the break within the ELSE. You could also remove the else and just let the loop fall out if the numbers match and then show the success message.

Related

Python input control loop

Python beginner here. Practicing user input control.
Trying to make user input loop to the beginning if anything but a whole number between 1 and 10 is used. Been trying for hours, tried using Try and Except commands but couldn't do it correctly. What am i doing wrong? Thank you.
Edit:
Thank you very much for your help everyone, however the problem is still not solved (but very close!) I'm trying to figure out how to loop back to the beginning if anything BUT a whole number is typed. Agent Biscuit (above) gave a great answer for floating numbers, but any word or letter that is typed still produces an error. I´m trying to understand how to loop when anything random (except whole numbers between 1 and 10) is typed. None of the above examples produced corrcct results. Thank you for your help
while True:
print("Enter a number between 1 and 10")
number = int(input())
if (number > 0) and (number < 10):
print("Thank you, the end.")
break
else number != (> 0 and < 10):
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
I have identified some problems.
First, the input statement you are using would just raise an error if a float value is entered, because the int at the start requires all elements of the input to be a number, and . is not a number.
Second; your else statement. else is just left as else:, and takes no arguments or parameters afterwards.
Now, how to check if the number is not whole? Try this:
while True:
print("Enter a number between 1 and 10")
number = float(input())
if (number > 0) and (number < 10) and (round(number)==number):
print("Thank you, the end.")
break
else:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
This accepts a float value, but only accepts it if it is equal to a whole number, hence the (round(number)==number).
Hope that answers your question.
First of all, you can't use a condition in a else statement. Also, you need to use or operator instead of and if one of the conditions is acceptable.
So, your code needs to be like this
while True:
print("Enter a number between 1 and 10")
number = int(input())
if (number > 0) and (number < 10):
print("Thank you, the end.")
break
elif number < 0 or number >10:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
Thanks to ack (above) for pointing me to a useful link. By studying another thread, I found the solution. It may not be perfect code, but it works 100%:
while True:
try:
print("Enter a number between 1 and 10")
number = float(input())
if (number > 0) and (number < 10) and (round(number)==number):
print("Thank you, the end.")
break
else:
print("\n")
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
print("\n")
continue
except ValueError:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
print("\n")

Smallest/largest numbers program, input must stop once negative number is inserted

The purpose of this program is to find the smallest and largest values in a list. The moment the user inputs a negative number, the program should stop. Here is the code I have written so far:
user_inputs = []
number = int(input())
for i in range(number):
value = int(input())
if i >= 0:
user_inputs.append(value)
else:
break
print(min(user_inputs))
print(max(user_inputs))
As you can see, I am new to programming and still struggling to find the logic behind loops. Surely, this code is ridden with mistakes and any helpful improvements is much appreciated. Thanks in advance.
Brother one mistake that you have done is that you are using
for i in range(number):
basically by doing this you are telling compiler that repeat the code in for loop for "number" of times and obviously number would change every time user inputs a new number resulting in error
The right way to make the code do what you want is :
user_inputs = []
while True:
number = int(input('Enter a positive number : '))
if number >= 0 :
user_inputs.append(number)
else:
print(user_inputs)
print('Smallest number in list is : ',min(user_inputs))
print('Largest number in list is : ',max(user_inputs))
break
Here while loop will run continuously until a negative number has been input, so when a negative number is input the while loop woulb break .
You are checking
i
when you should be checking
value
you have to compare value
i.e. if value >= 0
you are using i which is the number of iteration

Why can't I compare an input to a random number in Python

So I basically wanna compare "Number" and "Guess" in the if statement, but no matter what it says they don't match (I get the else response, not included here). Even if I copy the random number they don't match.
Thanks in advance!
import time
def the_start():
points = 0
attempt = 1
print("Attempt:",attempt)
print("Your goal is to guess a number between 1 and 10 - Points:",points)
time.sleep(2)
attempt = attempt + 1
number = random.randint(0,10)
print(number)
guess = input("What is your guess? :")
time.sleep(2)
if guess == number:
points = points + 1
print("OMG YOU WERE RIGHT! Here, have some fake cheers! *cheer*")
time.sleep(5)
guess is a string. You need to do conversion of the string and handle error conditions. int() will convert a string to an integer, but it will throw an exception if the string is not purely numbers.

creating a python program which ask the user for a number - even odd

I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0

Creating a small program in python

I'm trying to make a program in Python 3.5 that asks the user to enter a number from 1 to 9. The the program will also guess a number from 1 to 9. If the user guesses the same number correctly, then the program will print Correct . Otherwise, the program will print Wrong. I wrote a program. Everything went fine with my code. However, when I guessed a number correctly, the program suddenly wrote Wrong instead of Correct. What am I doing wrong?
Here is my code:
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
import random
random = print(random.randint(1,9))
if int(x) != random:
print ('Wrong')
else:
print ('Correct')
You are saving the result of a print() call (and masking random). print() returns None, so it will always be unequal to an integer, and therefore always "wrong."
import random
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
r = random.randint(1,9)
if x != r:
print('Wrong')
else:
print('Correct')
Also note that I've moved the import statement to the top, avoided a second int() cast on something you've already done that to, and removed the space between the print reference and its arguments.
Here is the mistake,
random = print(random.randint(1,9))
You need to do something like this.
random = random.randint(1,9)
print(random)
Also, you have already converted the input to int so, you can do just this.
if x != random:
As pointed out your mistake is the line
random = print(random.randint(1,9))
But why?
functions (like print() take something, do something (with it) and give something back.
Example:
sum(3,4) takes 3 and 4, may add them and returns 7.
print("Hello World") on the other hand takes "Hello world", prints it on the screen but has nothing useful to give back, and therefore returns None (Pythons way to say "nothing").
You then assign None to the name random and test if it equals your number, which it (of course) doesn't.

Categories