If/else stops after a few statements - python

I am trying to create and if/elseif statement so that when user inputs a number it gives him the answer of how many integers he has.
message = int(input("Enter an integer:"))
if message < 0:
print("1 digit, negative")
elif message < 10:
print("1 digit")
elif message >= 10:
print ("2 digits")
elif message >= 100:
print("3 digits")
elif message >= 1000:
print("more than 3 digits")
To my knowledge the if/else statement can be used as many times as you want and it seems like it stops working after 3statement (elif message >= 10:) , but if I temporarily comment out the 3nd statement the 4th statement(elif message >= 100:) works ,but the 5 statements does not.
What am I doing wrong?

I think you meant this instead:
if message < 0:
print("negative")
elif message < 10:
print("1 digit")
elif message < 100:
print ("2 digits")
elif message < 1000:
print("3 digits")
else:
print("more than 3 digits")
Note how all of these conditions use <.

Related

how to stop the infinite loop in my programme

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

Python guessing game -if/elif/else

I've just started learning Python and have constructed a little guessing game. It works but I would like to add a statement that if inputted number is out of range 1-10 there will be an error... Could you help or give me a hint? I suppose I should use nested if/else statement but not sure where:
import random as r
rand_num = r.randrange(1, 10)
odp = 0
i = 0
print("Guess the number from range 1-10")
while True:
i += 1
odp = int(input("Input number: "))
if (rand_num < odp):
print("Selected number is lower than you had inputted...")
elif (rand_num > odp):
print("Selected number is higher than you had inputted...")
elif (rand_num == odp):
break
print("Congrats! You have guessed the number after ", i, " tries")
You are on the right track there. You can use a nested if-elif block to check whether the number is in the range (1-10) and on error you could prompt a message saying that.
However, whenever you are using user inputs, you must use try except blocks.
You are assuming that the user would enter a stringified integer. What if the user enters an invalid character? What if the user enters a fraction?
You could keep on using if-elifs to check all the probable inputs. You probably can see how inefficient and verbose your code becomes.
If you are new to Python's error handling and haven't learnt try except finally use the nested if elifs.
However, this is how I would do the same problem
import random as r
rand_num = r.randrange(1, 10)
odp = 0
i = 0
print("Guess the number from range 1-10")
try:
while True:
i += 1
odp = int(input("Input number: "))
if odp > 10 or odp < 1:
raise ValueError("Out of bound error")
if (rand_num < odp):
print("Selected number is lower than you had inputted...")
elif (rand_num > odp):
print("Selected number is higher than you had inputted...")
elif (rand_num == odp):
break
except ValueError as e:
print(e)
You should also check for invalid types. Here's the official doc error handling
import random as r
rand_num = r.randrange(1, 10)
odp = 0
i = 0
print("Guess the number from range 1-10")
while True:
r.seed(r.random())
i += 1
input_user = int(input("Input number: "))
if abs(input_user) <= 10:
print(abs(input_user) <= 10)
if rand_num < input_user:
print("Selected number is lower than you had inputted...")
elif rand_num > input_user:
print("Selected number is higher than you had inputted...")
elif rand_num == input_user:
print("Selected number is correct!")
break
else:
print("Invalid number")
Put the else statement after all of the if/elif statements. Also, use a different seed each time to randomize the variable each time you run it.
You should definitely read how the control flow works and maybe try another good option like continue to skip the current iteration and run next one (without the use of large branching statements):
def game(minimum=1, maximum=10):
rand_num = r.randrange(minimum, maximum)
odp = 0
i = 0
print(f"Guess the number from range {minimum}-{maximum}")
while True:
i += 1
odp = int(input("Input number: "))
# Validate the input value.
if odp < minimum or odp > maximum:
print("Invalid input")
# To skip the following lines and start next cycle of while-loop
continue
if rand_num < odp:
print("Selected number is lower than you had inputted...")
continue
if rand_num > odp:
print("Selected number is higher than you had inputted...")
continue
if rand_num == odp:
if i == 1:
print("Cheater!")
else:
print("You win!")
break
game(2, 25)

Getting Invalid Syntax error for elif statement. how to overcome this?

I'm trying to run this code but getting the error and spent all my time debugging.looking out for help
n = int(input())
if n % 2 == 1:
print("Weird")
elif(n%2==0) and 2<=n<=5:
print("Not Weird")
elif(n%2==0) and 6<=n<=20:
print("Weird")
else:
print(" Not Weird")
The if/elif/else statements must all be at the same indentation level.
if x:
# do stuff
elif y:
# do other stuff
elif z:
# do more stuff
else:
# do something else
You should not indent elif and else. They should be at same indent as if. Also, you don't need to encase your conditional statements in parenthesis. This works:
n = int(input())
if n%2 == 1:
print("Weird")
elif n%2 == 0:
print("Not Weird")
elif n%2 == 0 and 6 <= n <= 20:
print("Weird")
else:
print(" Not Weird")

Trying to use list function to limit input in while loop in my guessing game

def random():
x_val = randint(1,100)
limit = []
limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if limit2 <= 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print limit2
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif limit2 > 5:
return "You guessed over 5 times. You lose, sucker..."
break
elif limit2 == 4:
print "Last guess!"
continue
print "Welcome to my world! You will have to pick a correct number from 1 to 100!
If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Hi, I am working on a guessing game from 1-100 that I built from ground up by myself and doing research, my original code is not even close to this.
Now, I am stuck on the last part I cannot use the list to limit the input in while loop. I want to stop the game after 5 guesses. However every time it always keep going and once it win it printed out "0" for limit2 variable.
Thank you
The main problem with your code is that you never update the "counter" of the attempted tries made by the user. You initialize it at the beginning (through limit2 = len(limit)), but you never update that value, therefore causing an endless loop.
You simply need to perform the check on len(limit) instead of on limit2.
Working solution can be found below. I took the liberty of commenting limit2 (as it is not needed anymore), improving the indentation, adding two imports, replacing sleep with time.sleep, and fixing the number of checks to perform (if you are aiming at 5 maximum tries, len(limit) needs to be less than 5).
from random import randint
import time
def random():
x_val = randint(1,100)
limit = []
# limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if len(limit) < 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
time.sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
time.sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print len(limit)
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif len(limit) >= 5:
return "You guessed over 5 times. You lose, sucker..."
break
print "Welcome to my world! You will have to pick a correct number from 1 to 100! If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Worthy of note is that -- among several other things that should be fixed in your code -- you should avoid calling a function random, since it is already a name used by a very common module.

Python 3.4 :While loop not looping

Python loop isn't wanting to loop back if the user's guess is greater than or less than the randomly generated value. It either exits the loop or creates an infinite loop. Where am I going wrong?
import random
correct = random.randint(1, 100)
tries = 1
inputcheck = True
print("Hey there! I am thinking of a numer between 1 and 100!")
while inputcheck:
guess = input("Try to guess the number! " )
#here is where we need to make the try statement
try:
guess = int(guess)
except ValueError:
print("That isn't a number!")
continue
if 0 <= guess <= 100:
inputcheck = False
else:
print("Choose a number in the range!")
continue
if guess == correct:
print("You got it!")
print("It took you {} tries!".format(tries))
inputcheck = False
if guess > correct:
print("You guessed too high!")
tries = tries + 1
if guess < correct:
print("You guessed too low!")
tries = tries + 1
if tries >= 7:
print("Sorry, you only have 7 guesses...")
keepGoing = False
The problem is with this line:
if 0 <= guess <= 100:
inputcheck = False
This will terminate the loop whenever the user enters a number between 0 and 100. You can rewrite this part as:
if not 0 <= guess <= 100:
print("Choose a number in the range!")
continue
The correct code is below:
import random
correct = random.randint(1, 100)
tries = 1
inputcheck = True
print("Hey there! I am thinking of a numer between 1 and 100!")
while inputcheck:
guess = input("Try to guess the number! " )
#here is where we need to make the try statement
try:
guess = int(guess)
except ValueError:
print("That isn't a number!")
continue
if 0 > guess or guess > 100:
print("Choose a number in the range!")
continue
if guess == correct:
print("You got it!")
print("It took you {} tries!".format(tries))
inputcheck = False
if guess > correct:
print("You guessed too high!")
tries = tries + 1
if guess < correct:
print("You guessed too low!")
tries = tries + 1
if tries > 7:
print("Sorry, you only have 7 guesses...")
inputcheck = False
The problem here was that you were setting inputcheck to False when the value of guess was in between 0 and 100. This changed the value of while to False and the loop was exiting since while wasn't True anymore.
Also, you should change the last if case in the while loop since this now fixes the case of running indefinitely:
if tries > 7:
print("Sorry, you only have 7 guesses...")
inputcheck = False

Categories

Resources