Python while statement error - python

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!

Related

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.

Alternative to Goto, Label in 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

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

Calculator in python problems

I made a calculator in python but when I run it and do for example 123 and 321 I get 123321 instead of 444, What am I doing wrong?
import time
print("Calculator 1.0")
print("made by AnAwesomeMiner")
print("Number 1 in calculation")
x = input()
print("Number 2")
y = input()
print("calculating")
time.sleep(3)
print("why is this not done yet")
time.sleep(3)
print("god this is taking forever")
time.sleep(3)
print("done")
answear = x + y
print(answear)
input() returns string not number . That's why instead of addition , String concatenation is performed.
you need to use int(x) and int(y) for conversion.
use this statement answear = int(x) + int(y)
input returns a string, and when you combine two strings the result is what you are seeing.
>>> x = '123'
>>> y = '321'
>>> x+y
'123321'
So you need to convert them to an integer, like this:
answear = int(x) + int(y)
you can use this :
y=int(input())
This is because you are declaring it as a string. Use a = int(input()). This will cast it into an integer. If you want to insert a decimal number use the float data type.
input() accepts and returns a string object and you need to typecast this into an integer (or float) if you want to perform arithmetic operations on it. Performing a + operation on two strings merely concatenates them.
Instead of input(), use int(input()). This will tell Python that the user is about to enter an integer.
def main():
def add(x,y):
return x + y
def sub(x,y):
return x - y
def mult(x,y):
return x * y
def div(x,y):
return x / y
def remainder(x,y):
return x % y
repeat=True
while repeat:
select=int(input("please select any operation:-\n 1.ADD\n2.SUBTRACT\n3.MULTIPLY\n4.DIVIDE\n5.REMAINDER\nselect here:-"))
num1=int(input("Enter the first number"))
num2=int(input("Enter the second number"))
if select==1:
print(num1,"+",num2,"=",add(num1,num2))
elif select==2:
print(num1,"-",num2,"=",sub(num1,num2))
elif select==3:
print(num1,"*",num2,"=",mult(num1,num2))
elif select==4:
print(num1,"/",num2,"=",div(num1,num2))
elif select==5:
print(num1,"%",num2,"=",remainder(num1,num2))
else:
print("invalid input")
print("Do you want to calculate further?\n press y for continue.\n press any other key to terminate.")
repeat="y" in str(input())
if repeat=="y":
print("Ooo yeh! you want to continue")
else:
print("Tnakyou")
main()
This is a simple problem to fix. When adding to integers or doing any other operation including an input and an int you need to do this:
y = int(input())
x = int(input())
a = y+x
so this put into your code looks like this:
import time
print("Calculator 1.0")
print("made by AnAwesomeMiner")
print("Number 1 in calculation")
x = int(input())
print("Number 2")
y = int(input())
print("calculating")
time.sleep(3)
print("why is this not done yet")
time.sleep(3)
print("god this is taking forever")
time.sleep(3)
print("done")
answear = x + y
print(answear)

Python - Need advice

Below I have a script that I have done while trying to complete for a assignment I have.
What the script is suppose to do is ask the user for 2 inputs and then return the greater of the inputs. (This I havent figured out completely yet)
The point of this assignment is too see what happens if I instead of entering 2 numbers, enter two words "Hej" and "Hå".
What I need some advice on is how to enable this script to accept 2 user inputs and return the greater of them two.
def maximum(x, y):
i = 0
maxnra = 0
maxnrb = 0
while i < len(x) :
if x[i] > maxnra:
maxnra = x[i]
i = i + 1
else:
i = i + 1
print "I första ordet är maximum: ", maxnra
i = 0
while i < len(y) :
if y[i] > maxnrb:
maxnrb = y[i]
i = i + 1
else:
i = i + 1
print "I andra ordet är maximum: ", maxnrb
maximum("hej", "hå")
EDIT:
I tried working this out another way, is this a way to solving this?
print "First"
x = input()
print "Second"
y = input()
def printMax(x, y):
if x > y:
print(x, 'is maximum')
elif a == b:
print(x, 'is equal to', y)
else:
print(y, 'is maximum')
right now im missing something cause it's not returning anything when I enter the 2 values.
Read documention on the command raw_input to see how you can get input from the user.
If you just want a simple way to get user input from the terminal window, have a look at the raw_input function.
Your first code would simply takes two lists and prints the maximum value of each individual list. So, this is not that you want.
In the second code, although the approach is right, you made some minor mistakes.
print "First"
x = input() # use raw_input() for python 2.7
print "Second"
y = input()
def printMax(x, y):
if x > y:
print(x, 'is maximum')
elif x == y:
# not a==b
print(x, 'is equal to', y)
else:
print(y, 'is maximum')
Actually, when you enter input in this code, though you enter numbers they are still considered as strings. So, there would be no big difference if you enter a string.
These strings are compared lexicographically using (ASCII value order). As your input isn't from ASCII, it will show error.
So, you need to replace input() or raw_input() with the following
import sys # do this at the top of program.
x = raw_input().decode(sys.stdin.encoding)
# similarly do it for y
Please read the following stackoverflow question to know more on this link

Categories