how to stop the infinite loop in my programme - python

I wrote the following program to recognize the negative and positive numbers, but I do not know why it gets stuck in an infinite loop?
I would appreciate it if anyone helps me!!!
# negative and positive numbers
num = input('please enter a number:')
while True:
num = int(num)
if num < 0:
print('your num is negative!')
elif num == 0:
print('your num is zero!')
else:
print('your num is positive!')

The code gets stuck in an infinite loop because you have used while True.
Do this instead,
num = int(input('please enter a number:'))
if num < 0:
print('your num is negative!')
elif num == 0:
print('your num is zero!')
else:
print('your num is positive!')
To break out of an infinite loop you can use the break keyword.
Using break -
num=input('please enter a number:')
while True:
num = int(num)
if num < 0:
print('your num is negative!')
break
elif num == 0:
print('your num is zero!')
break
else:
print('your num is positive!')
break

If you want to ask the user for a number repeatedly. You need to add a condition in the while loop to break it. For example, you can check if the user enters "stop" to break the loop.
while (True):
# Read the user input.
numStr = input('Please, enter a number: ')
# Check if the user enters "stop".
if (numStr == "stop"):
break
else:
# Convert the user string input to float to accept any digit.
num = float(numStr)
if (num < 0):
print('Your num is negative!')
elif (num == 0):
print('Your num is zero!')
else:
print('Your num is positive!')
If you want to ask the use for a number only once. You need to remove the while loop.
# Read the user input.
numStr = input('Please, enter a number: ')
# Convert the user string input to float to accept any digit.
num = float(numStr)
# Check the number: +ve, 0, -ve.
if (num < 0):
print('Your num is negative!')
elif (num == 0):
print('Your num is zero!')
else:
print('Your num is positive!')

You aren't breaking the while loop, that's why its program stucked in infinite loop.
You can use this
# negative and positive numbers
while True:
try:
num = int(input('please enter a number:'))
if num < 0:
print('your num is negative!')
elif num == 0:
print('your num is zero!')
elif num > 0:
print('your num is positive!')
choice = input("Do you want to check other number. press y|n")
if choice == "n":
break
except ValueError:
print("Please give integer value only")
You can look into https://www.geeksforgeeks.org/python-exception-handling/
Happy coding :)

you will be in the loop till the while condition is true and you have stated it true.. so it goes into an infinite loop.
num = input('please enter a number:')
while True:
num = int(num)
if num < 0:
print('your num is negative!')
break
elif num == 0:
print('your num is zero!')
break
else:
print('your num is positive!')
break
Add break statement
or
num = int(input('please enter a number:'))
if num < 0:
print('your num is negative!')
elif num == 0:
print('your num is zero!')
else:
print('your num is positive!')
Try avoiding using while True. It may create the issue of infinite loop if we forget to add break statement

Related

Why does the process just stop even though I have some command? [duplicate]

This question already has answers here:
Python input never equals an integer [duplicate]
(5 answers)
Closed 2 years ago.
I am trying to make a code guessing game where the user can choose the range of the code. The user tries to guess the randomly generated code until he/she gets it right. The computer also shows which digits the user gets correct. The problem is that when the user does guess the code correctly, the process just stops even though my codes says to print a congratulations message and go to the play again function. Please can anyone help? Thanks. Code:
import random
import string
def get_range():
Min = input("ENTER THE MINIMUM NUMBER THE CODE CAN BE: ")
Max = input("ENTER THE MAXIMUM NUMBER THE CODE CAN BE: ")
validate_range(Min, Max)
def validate_range(Min, Max):
Check_Min = Min.isdigit()
Check_Max = Max.isdigit()
if Check_Min is not True or Check_Max is not True:
print("INPUT MUST ONLY INCLUDE INTEGERS! ")
get_range()
elif Min == Max:
print("MINIMUM AND MAXIMUM NUMBER MUST NOT BE EQUIVALENT! ")
get_range()
elif Min > Max:
print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
get_range()
else:
Random = random.randrange(int(Min), int(Max))
get_guess(Random)
def get_guess(Random):
Guess = str(input("ENTER YOUR GUESS: "))
Check_Guess = Guess.isdigit()
if not Check_Guess:
print("INPUT MUST ONLY CONTAIN INTEGERS! ")
get_guess(Random)
else:
validate_guess(Guess, Random)
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if Guess == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
else:
Digits = ["?"] * Length
for i in range(0, int(Length)):
if str(Guess)[i] == str(Random)[i]:
Digits[i] = Guess[i]
Digits_Correct += 1
else:
continue
if int(Length) > Digits_Correct > 0:
print("NOT QUITE! YOU GOT", Digits_Correct, " DIGITS CORRECT!")
print(Digits)
get_guess(Random)
elif Digits_Correct == 0:
print("NONE OF YOUR DIGITS MATCH! ")
get_guess(Random)
def play_again():
Choice = input("\n DO YOU WISH TO PLAY AGAIN? (Y/N)")
if Choice != "Y" or Choice != "N" or Choice != "y" or Choice != "n":
print("PLEASE ENTER A VALID INPUT! ")
play_again()
else:
get_range()
print("WELCOME TO CODE CRUNCHERS!\n ")
get_range()
I think the problem here is that your Guess is a string and your Random is an integer. To fix this, you can try to convert the Guess to an integer or the Random to a string.
Try this:
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if int(Guess) == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
I think your problem is with types str and int. First of all your Min and Max are strings, so your line:
elif Min > Max: print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
does not work correctly. The other problem is that your variables Guess and Random are of different types, so Guess == Random will return False all the time.
Here's correct version of your code.
I've also added a few if cases to be able to quit the program without closing it.
import random
import string
def get_range():
Min = input("ENTER THE MINIMUM NUMBER THE CODE CAN BE: ")
Max = input("ENTER THE MAXIMUM NUMBER THE CODE CAN BE: ")
if Min == 'q':
return
validate_range(Min, Max)
def validate_range(Min, Max):
Check_Min = Min.isdigit()
Check_Max = Max.isdigit()
if Check_Min is not True or Check_Max is not True:
print("INPUT MUST ONLY INCLUDE INTEGERS! ")
get_range()
Min = int(Min)
Max = int(Max)
if Min == Max:
print("MINIMUM AND MAXIMUM NUMBER MUST NOT BE EQUIVALENT! ")
get_range()
elif Min > Max:
print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
get_range()
else:
Random = random.randrange(int(Min), int(Max))
get_guess(Random)
def get_guess(Random):
Guess = str(input("ENTER YOUR GUESS: "))
Check_Guess = Guess.isdigit()
if not Check_Guess:
print("INPUT MUST ONLY CONTAIN INTEGERS! ")
get_guess(Random)
else:
validate_guess(Guess, Random)
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if int(Guess) == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
else:
Digits = ["?"] * Length
for i in range(0, int(Length)):
if str(Guess)[i] == str(Random)[i]:
Digits[i] = Guess[i]
Digits_Correct += 1
else:
continue
if int(Length) > Digits_Correct > 0:
print("NOT QUITE! YOU GOT", Digits_Correct, " DIGITS CORRECT!")
print(Digits)
get_guess(Random)
elif Digits_Correct == 0:
print("NONE OF YOUR DIGITS MATCH! ")
get_guess(Random)
def play_again():
print("\n DO YOU WISH TO PLAY AGAIN? (Y/N)")
Choice = input()
if Choice != "Y" or Choice != "N" or Choice != "y" or Choice != "n":
print("PLEASE ENTER A VALID INPUT! ")
play_again()
else:
get_range()
print("WELCOME TO CODE CRUNCHERS!\n ")
get_range()

Making a Calculator which take input from user until user enter 0 but not working correctly

I am a newbie in python and trying to make a calculator but no getting how to make it
I am making a Calculator which will take input from the user until the user enters 0 and then do the operations
but I am stuck here
if anyone can help me doing this work I will be very thankful to him/her.
num = None
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
options = int(input("Enter Your Choice: "))
# For Addition or Option 1
if options == 1:
total = 0
while(num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total + num
print("Your Calculated Number is: {} ".format(total))
# For Subtraction or Option 2
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
print("Your Calculated Value is: {}".format(total))
# Multiplication for Option 3
elif options == 3:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
# Division for Option 4
elif options == 4:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
# When User Wants to Exit
else:
print("Thank You for Using the Calculator")
Here is a better approach using itertools.reduce. Instead of repeating the same code for inputting a number multiple times, put it into a function. This will also help avoid the errors in your code and clarify the logic. A second generator function can be used to get the series of values until the user enters zero.
from functools import reduce
import operator
def input_number():
while True:
try:
return float(input("(Enter '0' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
def input_series():
while True:
n = input_number()
if n == 0:
return
yield n
operations = {
1: operator.add,
2: operator.sub,
3: operator.mul,
4: operator.truediv
}
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
option = int(input("Enter Your Choice: "))
# For Addition or Option 1
if option == 5:
print("Thank You for Using the Calculator")
else:
total = reduce(operations[option], input_series())
print("Your Calculated Value is: {}".format(total))
Instead of
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
use (the changes are only in the 2nd line and in the last one)
elif options == 2:
total = None
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num if total is not None else num
The same method you may use for the elif options == 4: branch.
The problem with subtraction is that the variable total is not initialized.
The problem with multiplication and division is that when the user inputs "0", the variable total is multiplied or divided by zero before it is checked in the while statement. what I would normally do is this:
elif options == 3:
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number ")) # No need to escape single quotes when your string uses double quotes
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
However, if you wanted a quick fix, you can have the user input 1 instead of 0 for multiplication and division:
elif options == 4:
total = 1
while (num != 1):
try:
num = float(input("(Enter '1' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
Edit: If you want division to work the way you specified, you could do something like this:
elif options == 2:
total = 1
try:
first_number = float(input("(Enter '0' When Complete.) Enter Number "))
if first_number == 0:
print("Your Calculated Value is: 0")
exit()
except ValueError:
print("Error, Enter Valid Number")
continue
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number "))
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total + first_number))

How do u add lives and a counter to display the lives

I want to add lives to and a counter displaying how many lives I have left
I tried adding a counter using range but it prints all the no like 1, 2, 3 I just need it to display 1 number that represents lives u have left
num = random.randint(1,10);
print(num)
guess = int(input('Guess a number: '))
if(guess == num):
print("correct")
else:
print("incorrect")
Try a for loop:
import random
num = random.randint(1,10)
for i in range(3):
guess = int(input('Guess a number: '))
if(guess == num):
print("correct")
break
else:
print("incorrect")
print(2 - i, 'tries left')
I would use a while loop for this. Each guess a counter would be decreased by one. The loop would run while lives > 0.
num = random.randint(1,10);
print(num)
lives = 3
while lives > 0:
guess = int(input('Guess a number: '))
if(guess == num):
print("correct")
break
else:
print("incorrect")
print("%s lives left." % lives-1)
lives -= 1

higher or lower game unexpected EOF while parsing

need help with a higher or lower game I think the problem has something to do with the loop. I have been told been told to add an except but I have no idea where to add it
print('Welcome to higher or lower game')
input('press enter to start.\n')
import random
Max = 10
Min = 0
num = random.randint(1, 10)
print('your starting number is a ' + str(num))
while 'well done.\n' :
guess = input('higher (h) or lower (l).\n')
new_num = random.randint(1, 10)
print('your new number is a ' + str (new_num))
try :
if new_num > num and guess == 'h':
print('well done.\n')
elif new_num < num and guess == 'l':
print('well done.\n')
break
if num and guess == 'l' and new_num > num and guess:
print('game over')
elif num and guess == 'h' and new_num < num and guess:
print('game over')
else:
print('game over you got a score of ' + str(score))
You do not have an except clause in the try statement. That clause is required unless you have a finally clause.
You really shouldn't have a try statement there. You could take it out and just go with some if and elif statements.
Example:
import random
number = random.randint(1,10)
lives = 3
Success = False
while lives > 0:
guess = int(input("What is your guess between 1 and 10? \r\n"))
if guess > number:
print("Too high! Go lower. \r\n")
lives -= 1
elif guess < number:
print("Too low! Go higher. \r\n")
lives -= 1
elif guess == number:
print("Congratulations, you win!")
global Success = True
break
if Success != True:
print("Sorry. Try again! The number was ", number, ".")
As far as I understand, try statements are mainly used for error handling.

Python: How to check if a number is in range and if not have the user enter a new number?

I first asked the user to enter a number and then ran a try/except block. I now want to check to see if the number is in a range between 1-9.
If not I want it to check if int and then check if it is in range.
Here is what I have so far:
def getInt(low, high):
start = 0
while start == 0:
try:
num = input("Enter a number for your calculation in range of 1- 9: ")
num = int(num)
start = 1
asdf = 0
while asdf == 0:
if num > 9 or num < 0:
print("Error: Please only enter numbers between 1-9")
else:
asdf = +1
return num
except:
print("Error: Please only enter numbers")
# main
TOTAL_NUMBERS = 2
LOW_NUMBER = 1
HIGH_NUMBER = 9
num1 = getInt(LOW_NUMBER, HIGH_NUMBER )
print(num1)
num2 = getInt(LOW_NUMBER, HIGH_NUMBER )
print(num2)
Maybe you need this:
def getInt(low, high):
while True:
try:
num = int(input("Enter a number for your calculation in range of 1- 9: "))
except ValueError:
print("Error: Please only enter numbers")
continue
if num not in range(1, 10):
print("Error: Please only enter numbers between 1-9")
else:
return num
You could replace
print("Error: Please only enter numbers between 1-9")
with
num = input("Error: Please only enter numbers between 1-9: ")
or move
num = input("Enter a number for your calculation in range of 1- 9: ")
num = int(num)
into the while loop so it gets called again if the user inputs a number outside the range
def getInt(low, high):
while True: # Keep asking until we get a valid number
try:
numStr = raw_input("Enter a number for your calculation in range of {0} - {1}: ".format(low, high) )
if numStr.isdigit():
num = int(numStr)
if num <= high and num >= low:
return num
except: # Field left empty
pass
getInt(1, 9)

Categories

Resources