Alternative to Goto, Label in Python? - python

I know I can't use Goto and I know Goto is not the answer. I've read similar questions, but I just can't figure out a way to solve my problem.
So, I'm writing a program, in which you have to guess a number. This is an extract of the part I have problems:
x = random.randint(0,100)
#I want to put a label here
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
#And Here I want to put a kind of "goto label"`
What would you do?

There are lots of ways to do this, but generally you'll want to use loops, and you may want to explore break and continue. Here's one possible solution:
import random
x = random.randint(1, 100)
prompt = "Guess the number between 1 and 100: "
while True:
try:
y = int(raw_input(prompt))
except ValueError:
print "Please enter an integer."
continue
if y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number: "
else:
print "Correct!"
break
continue jumps to the next iteration of the loop, and break terminates the loop altogether.
(Also note that I wrapped int(raw_input(...)) in a try/except to handle the case where the user didn't enter an integer. In your code, not entering an integer would just result in an exception. I changed the 0 to a 1 in the randint call too, since based on the text you're printing, you intended to pick between 1 and 100, not 0 and 100.)

Python does not support goto or anything equivalent.
You should think about how you can structure your program using the tools python does offer you. It seems like you need to use a loop to accomplish your desired logic. You should check out the control flow page for more information.
x = random.randint(0,100)
correct = False
prompt = "Guess the number between 1 and 100: "
while not correct:
y = int(raw_input(prompt))
if isinstance(y, int):
if y == x:
correct = True
elif y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number "
else:
print "Try using a integer number"
In many other cases, you'll want to use a function to handle the logic you want to use a goto statement for.

You can use infinite loop, and also explicit break if necessary.
x = random.randint(0,100)
#I want to put a label here
while(True):
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
# can put a max_try limit and break

Related

Input failing when user inputs a letter. I want to check to make sure they have put in a number

Hi I am trying to check if the user has put in a letter and then let them know it is a letter and they need to put in a number.
it keeps giving me a error whenever this happens, I understand it may be because I am trying to convert a int to a string but I am at a lose to trying to figure this out.
I thought the below code would check to see if its a number input and fail it or pass it depending on what they put. however it doesn't seem to work.
is there anyway around this.
def weapons_(numguns,numknifes,numbombs,numswords):
print(numguns)
aaa = int(str(input("""Enter you're number accordinly to the list above:""")))
while True:
try:
number = int(aaa)
print("this is a num, thank you")
break
except ValueError:
print("this is not a number, please try again")
if aaa <= 50:
print (x)
elif aaa <= 100:
print (y)
elif 101 <= 150:
print (m + p)
elif 151 <= 200:
print (z)
weapons_("numguns","numknifes","numbombs","numswords")
Try this function:
def isNum (var):
flag = True
while (flag):
try:
val = int(var)
flag = False
except ValueError:
var = input("No.. input is not a number! Please enter a number: ")
return int(var)
It keeps asking for a number until the input value is an int. It finally returns the value as output.
Here is a sample screenshot of the output:
sample
Try this code. I put the variables x, y, m, p, z into quotes since they were not defined.
Since you've casted aaa into a number, You should not use aaa anymore to compare with (50, 100, etc.) but the variable number instead. In addition, if the cast fails, the code will show the exception message and ask the use for a new number.
while True:
try:
aaa = input("""Enter you're number accordinly to the list above:""")
number = int(aaa)
print("this is a num, thank you")
if number <= 50:
print ("x")
elif number <= 100:
print ("y")
elif 101 <= 150:
print ("m + p")
elif 151 <= 200:
print ("z")
break
except ValueError:
print("this is not a number, please try again")
Try using regex
import re
def checkInt(string):
ex = re.compile(r'[1-9][0-9]*')
return bool(ex.match(string))
You can use this function like this
aaa = input("""Enter you're number accordinly to the list above:""")
if checkInt(aaa): aaa = int(aaa)
else:
print('Not a Integer')
exit()
# the code you posted on the question

Print in a while loop

I can get the print statements to display to terminal if I enter a number that is not equivalent to 15. I want to display a message when the input is not 15, but it won't. Only when I enter 15, I get only "Right Guess". Why does this not work?
x=15
y=10
while x != y:
y = int(input("Please Try to guess the random number: "))
if y < x:
print("Low guess")
elif y > x:
print("High Guess")
else :
print ("Right Guess!")
Your if, elif, and else is not in the while loop. This means it won't run until after the while loop is finished (when x == y)
You should also use descriptive variable names (not x and y)
I'm on my phone, so I can't test code, but I think working code would be:
number = 15
# why did you initialize your `y` to 10?
guess = 0
while guess != number:
guess = int(input("Guess a number:"))
if guess == number:
print("Yay! You guessed the number")
elif guess > number:
print("You guessed too high")
else:
print("You guessed too low")
You should indent your code properly.
Initialize your values, these have to be separated from the while loop, otherwise you will get an infinite loop.
x = 15
y = 10
Then you can run your script below with properly identation.
while x != y:
y = int(input("Please Try to guess the random number: "))
if y < x:
print("Low guess")
elif y > x:
print("High Guess")
else:
print ("Right Guess!")
Identation
Identation for python means tell us when a function start and when finish:
if x != y:
# start indent
print("I'm in if")
# finish indent
print("I'm out of if")
There, indent tell us when if starts and when finishes. So the first print will be affected by if and the other print not.
I think that you need to indent your if block so that it is contained within the while loop.

How do I check if a string is a negative number before passing it through int()?

I'm trying to write something that checks if a string is a number or a negative. If it's a number (positive or negative) it will passed through int(). Unfortunately isdigit() won't recognize it as a number when "-" is included.
This is what I have so far:
def contestTest():
# Neutral point for struggle/tug of war/contest
x = 0
while -5 < x < 5:
print "Type desired amount of damage."
print x
choice = raw_input("> ")
if choice.isdigit():
y = int(choice)
x += y
else:
print "Invalid input."
if -5 >= x:
print "x is low. Loss."
print x
elif 5 <= x:
print "x is high. Win."
print x
else:
print "Something went wrong."
print x
The only solution I can think of is some separate, convoluted series of statements that I might squirrel away in a separate function to make it look nicer. I'd be grateful for any help!
You can easily remove the characters from the left first, like so:
choice.lstrip('-+').isdigit()
However it would probably be better to handle exceptions from invalid input instead:
print x
while True:
choice = raw_input("> ")
try:
y = int(choice)
break
except ValueError:
print "Invalid input."
x += y
Instead of checking if you can convert the input to a number you can just try the conversion and do something else if it fails:
choice = raw_input("> ")
try:
y = int(choice)
x += y
except ValueError:
print "Invalid input."
You can solve this by using float(str). float should return an ValueError if it's not a number. If you're only dealing with integers you can use int(str)
So instead of doing
if choise.isdigit():
#operation
else:
#operation
You can try
try:
x = float(raw_input)
except ValueError:
print ("What you entered is not a number")
Feel free to replace float with int, and tell me if it works! I haven't tested it myself.
EDIT: I just saw this on Python's documentation as well (2.7.11) here
isn't this simpler?
def is_negative_int(value: str) -> bool:
"""
ref:
- https://www.kite.com/python/answers/how-to-check-if-a-string-represents-an-integer-in-python#:~:text=To%20check%20for%20positive%20integers,rest%20must%20represent%20an%20integer.
- https://stackoverflow.com/questions/37472361/how-do-i-check-if-a-string-is-a-negative-number-before-passing-it-through-int
"""
if value == "":
return False
is_positive_integer: bool = value.isdigit()
if is_positive_integer:
return True
else:
is_negative_integer: bool = value.startswith("-") and value[1:].isdigit()
is_integer: bool = is_positive_integer or is_negative_integer
return is_integer

Hotter/Colder Number Game in Python

I'm working my way through the Code Academy Python course and have been trying to build small side projects to help reinforce the lessons.
I'm currently working on a number game. I want the program to select a random number between 1 and 10 and the user to input a guess.
Then the program will return a message saying you win or a prompt to pick another higher/lower number.
My code is listed below. I can't get it to reiterate the process with the second user input.
I don't really want an answer, just a hint.
import random
random.seed()
print "Play the Number Game!"
x = raw_input("Enter a whole number between 1 and 10:")
y = random.randrange(1, 10, 1)
#Add for loop in here to make the game repeat until correct guess?
if x == y:
print "You win."
print "Your number was ", x, " and my number was ", y
elif x > y:
x = raw_input("Your number was too high, pick a lower one: ")
elif x < y:
x = raw_input("Your number was too low, pick a higher one: ")
You need use a while loop like while x != y:. Here is more info about the while loop.
And you can only use
import random
y = random.randint(1, 10)
instead other random function.
And I think you should learn about int() function at here.
These are my hints :)
import random
n = random.randint(1, 10)
g = int(raw_input("Enter a whole number between 1 and 10: "))
while g != n:
if g > n:
g = int(raw_input("Your number was too high, pick a lower one: "))
elif g < n:
g = int(raw_input("Your number was too low, pick a higher one: "))
else:
print "You win."
print "Your number was ", g, " and my number was ", n

Python while statement error

I am a beginner in python. My program is to set a number (I am not using random.randint for the moment) and I try to guess it. So here is the code:
def game():
print "I am thinking of a number between 1 and 10!"
global x
x = 7
y = raw_input("Guess!")
while x > y:
y = raw_input("Too low. Guess again!")
while x < y:
y = raw_input("Too high. Guess again!")
if x == y:
return "You got it! The number was" + x + " !"
but when I run this, the program states that x < y, no matter WHAT number I put in.
Please, can someone help me? Thank you.
You need to convert y to an integer before comparing it to x:
y = int(raw_input("Guess!"))
Otherwise, you are comparing variables of different types, and the result is not always intuitive (such as x always being less than y). You can apply the same approach for the other times you ask the user to input y.
You may want this:
def game():
print "I am thinking of a number between 1 and 10!"
global x
x = 7
while True:
y = int(raw_input("Guess! ")) # Casting the string input to int
if x > y:
y = raw_input("Too low. Guess again!")
elif x < y:
y = raw_input("Too high. Guess again!")
elif x == y:
print "You got it! The number was " + str(x) + " !"
break # To exit while loop
game()
Y has to be an integer like x. A simple way to do this is:
y=int(raw_input("etc."))
You cannot compare two different variable types in python! Hope this helps!

Categories