Python : If statement within a while loop - python

I wrote a program, which keeps rolling a "num" sided die until it reaches the maximal roll which is the number you write as "num". However, if it happens that the first roll is the number, the program does not say "You landed on your number!" as it should. Here is the code
import random
num = () #put the number here#
i = random.randint(1,num)
while i != num:
print(i)
print("Not lucky")
i = random.randint(1,num)
if i == num:
print("You landed on your number!")
Again, if the roll equals the number choice, I get "Process finished with exit code 0", not the text I want. How do I fix this?

Put the final print, outside of the while loop, as you're always land there
num = 5 # put the number here#
i = random.randint(1, num)
while i != num:
print("Not lucky,", i, "isn't the one")
i = random.randint(1, num)
print("You landed on your number!")

what if something like that?
import random
num = int(input('Put your number: '))
i = random.randint(1, num)
while True:
if i == num:
print("You landed on your number!")
print(num)
break
else:
print(i)
print("Not lucky")
i = random.randint(1, num)

You can do it like this:
import random
num = (2) #put the number here#
i = random.randint(1,num)
while i != num:
i = random.randint(1,num)
if i != num:
print(i, "Not lucky")
print(i, "You landed on your number!")

import random
num = #put the number here#
while True:
i = random.randint(1,num)
print(i)
if i == num:
print("You landed on your number!")
break
print("Not lucky")

Related

repeat a process in Python

I want to repeat asking number process while guess is not equal with TrueNum but when I put it in while loop it just repeats the print of its "if"
what should I do?
import random
# Defining True Num:
DataRange = list(range(0, 11))
TrueNum = int(random.choice(DataRange))
print("it`s in range from o to 10")
# Getting Guesses From User:
Guess = int(input("Input your number: "))
# Checking Guess:3
while Guess != TrueNum:
if Guess > TrueNum:
print("You Are Getting Far...")
elif Guess < TrueNum:
print("It`s bigger than you think :)")
break
if Guess == TrueNum:
print("yeah that`s it")
You need to put the input inside the while, and is good also to take out some unnecessary conditions:
import random
# Defining True Num:
DataRange = list(range(0, 11))
TrueNum = int(random.choice(DataRange))
print("it`s in range from o to 10")
# Getting Guesses From User:
Guess = int(input("Input your number: "))
# Checking Guess:3
while Guess != TrueNum:
if Guess > TrueNum:
print("You Are Getting Far...")
else:
print("It`s bigger than you think :)")
Guess = int(input("Input your number: "))
print("yeah that`s it")
Using Try/Except allows you to address an invalid choice while also keeping readability.
import random
# Defining True Num:
DataRange = list(range(0, 11))
TrueNum = int(random.choice(DataRange))
print("it`s in range from o to 10")
# Getting Guesses From User:
while True:
try:
Guess = int(input("Input your number: "))
if Guess > TrueNum:
print("You Are Getting Far...")
elif Guess < TrueNum:
print("It`s bigger than you think :)")
elif Guess == TrueNum:
print("yeah that`s it")
break
except ValueError:
print("Invalid Choice")
The variable Guess is defined outside the loop, you should put the input and check the value inside the loop.
import random
datarange = list(range(0, 11))
trueNum = int(random.choice(datarange))
print("Guess the number! It`s in range from o to 10")
while True:
Guess = int(input("Input your number: "))
if Guess == trueNum:
print("Yeah that`s it")
break
elif Guess > trueNum:
print("You Are Getting Far...")
else:
print("It`s bigger than you think :)")

Number Guessing Games with continuation

I know there is a solution to the number guessing game in python. I've seen the code here too. and as a continuation how can I add a function(or anything else) to prompt the user- after successfully guessing it- if he wants to continue or not if not halt it. I know the code don't know how to add it to code.
import random
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
count+=1
so here is what we had in this forum but how can I add this to what I have above :
ask = input('do you want to continue? y stands for yes and n for discontinuing')
if ask=="y":
UserGuess=int(input('Enter youre desired Number: '))
else:
return
Include it in a while loop outside the function. This way, you will get recursion out of the way.
def play_game():
....
....
count+=1
play_game()
while True:
ask = input('do you want to continue? y stands for yes and n for discontinuing')
if ask=="y":
play_game()
else:
break

Random number guessing game throws error: > or < cannot be used between str and int

I have the following code for a random number guessing game:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = input()
if guess1 == number:
print ("Good job, you got it!")
while guess1 != number:
if guess1 > number:
print ('your guess is too high')
if guess1 < number:
print ('your guess is too low')
which throws the error that > or < cannot be used between str and int.
What should I do so it doesn't trigger that error?
There are two errors in your code.
You need to convert the input for guess1 from a string (by default) to an integer before you can compare it to the number (an integer).
The while loop will never stop since you are not letting the user input another value.
Try this:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = int(input()) # convert input from string to integer
while guess1 != number:
if guess1 > number:
print ('your guess is too high. Try again.')
elif guess1 < number:
print ('your guess is too low. Try again.')
guess1 = int(input()) # asks user to take another guess
print("Good job, you got it!")
You can make use of a while loop here - https://www.tutorialspoint.com/python/python_while_loop.htm
The logic should be:
answer_is_correct = False
while not answer_is_correct :
Keep receiving input until answer is correct
I hope this works for you:
import random
myname = input('Hello, what is your name?')
print('Well',myname,'am thinking of a number between 1 and 100')
number = random.randint(1,100)
guess = 0
while guess < 4:
guess_number = int(input('Enter a number:'))
guess += 1
if guess_number < number:
print('Your guess is to low')
if guess_number > number:
print('Your guess is to high')
if guess_number == number:
print('Your guess is correct the number is',number)
break
if guess == 4:
break
print('The number i was thinking of is',number)
from random import randint
print("you wanna guess a number between A to B and time of guess:")
A = int(input("A:"))
B = int(input("B:"))
time = int(input("time:"))
x = randint(1, 10)
print(x)
while time != 0:
num = int(input("Enter: "))
time -= 1
if num == x:
print("BLA BLA BLA")
break
print("NOPE !")
if time == 0:
print("game over")
break
Code in Python 3 for guessing game:
import random
def guessGame():
while True:
while True:
try:
low, high = map(int,input("Enter a lower number and a higher numer for your game.").split())
break
except ValueError:
print("Enter valid numbers please.")
if low > high:
print("The lower number can't be greater then the higher number.")
elif low+10 >= high:
print("At least lower number must be 10 less then the higher number")
else:
break
find_me = random.randint(low,high)
print("You have 6 chances to find the number...")
chances = 6
flag = 0
while chances:
chances-=1
guess = int(input("Enter your guess : "))
if guess<high and guess>low:
if guess < find_me:
print("The number you have entered a number less then the predicted number.",end="//")
print("{0} chances left.".format(chances))
elif guess > find_me:
print("The number you have entered a number greater then the predicted number.",end="//")
print("{0} chances left.".format(chances))
else:
print("Congrats!! you have succesfully guessed the right answer.")
return
else:
print("You must not input number out of range")
print("{0} chances left.".format(chances))
print("The predicted number was {0}".format(find_me))
You can conditions within the while loop to check if its right. It can be done the following way.
import random
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 100)
print('Well, ' + myName + ', I am thinking of a number between 1 and 100.')
inputNumber = int(raw_input('Enter the number')
while inputNumber != number:
print "Sorry wrong number , try again"
inputNumber = int(raw_input('Enter the number')
print "Congrats!"
from random import *
def play_game():
print("Let's play a number guessing game")
# Selecting a random number between 1 and 100
number = randint(1, 100)
choice = int(input("I am thinking of a number between 1 and 100. Could you guess what it is? "))
# Guide the user towards the right guess
# Loop will continue until user guesses the right number
while choice != number:
if choice < number:
choice = int(input("Too low. Can you try again? "))
elif choice > number:
choice = int(input("Too high. Can you try again? "))
continue_game = input("You guessed it right! Would you like to play it again? (Y/N) ")
# Restart the game if user wishes to play again
if continue_game == "Y":
print("--" * 42)
play_game()
else:
print("Thanks for playing :)")
exit(0)
play_game()

The returned value not defined

I am creating a guessing game and I have created two functions. One to take the user input and the other to check whether the user input is correct.
def getGuess(maxNum):
if maxNum == "10":
count=0
guess = -1
guessnum = [ ]
while guess >10 or guess<0:
try:
guess=int(input("Guess?"))
except:
print("Please enter valid input")
guesses.append(guess)
return guesses
return guess
def checkGuess(maxNum):
if maxNum == "10":
if guess>num1:
print("Too High")
elif guess<num1:
print ("Too Low")
else:
print("Correct")
print (guesses)
and the main code is
if choice == "1":
count = 0
print("You have selected Easy as the level of difficulty")
maxNum= 10
num1=random.randint(0,10)
print (num1)
guess = 11
while guess != num1:
getGuess("10")
checkGuess("10")
count = count+1
print (guess)
Although the function returns the users guess the code always takes the guess as 11. If I don't define guess, it doesn't work either. Please help.
First, you are returning two values. A return statement also acts as a break, so the second return will not be called. Also, you are not storing the returned value anywhere, so it just disappears.
Here is your edited code:
def getGuess(maxNum):
if maxNum == "10":
guess = -1
while guess >10 or guess<0:
try:
guess=int(input("Guess?"))
except:
print("Please enter valid input")
return guess
def checkGuess(maxNum, guess, num1):
if maxNum == "10":
if guess>num1:
print("Too High")
elif guess<num1:
print ("Too Low")
else:
print("Correct")
return True
return False
if choice == "1":
count = 0
print("You have selected Easy as the level of difficulty")
maxNum= 10
num1=random.randint(0,10)
print (num1)
guess = 11
guesses = []
while guess != num1:
guess = getGuess("10")
guesses.append(guess)
hasWon = checkGuess("10", guess, num1)
if hasWon:
print(guesses)
break
count = count+1
You have selected Easy as the level of difficulty
2
Guess?5
Too High
Guess?1
Too Low
Guess?2
Correct
[5, 1, 2]
>>>
You have a programming style I call "type and hope". maxNum seems to bounce between a number and a string indicating you haven't thought through your approach. Below is a rework where each routine tries do something obvious and useful without extra variables. (I've left off the initial choice logic as it doesn't contribute to this example which can be put into your choice framework.)
import random
def getGuess(maxNum):
guess = -1
while guess < 1 or guess > maxNum:
try:
guess = int(input("Guess? "))
except ValueError:
print("Please enter valid input")
return guess
def checkGuess(guess, number):
if guess > number:
print("Too High")
elif guess < number:
print("Too Low")
else:
print("Correct")
return True
return False
print("You have selected Easy as the level of difficulty")
maxNum = 10
maxTries = 3
number = random.randint(1, maxNum)
count = 1
guess = getGuess(maxNum)
while True:
if checkGuess(guess, number):
break
count = count + 1
if count > maxTries:
print("Too many guesses, it was:", number)
break
guess = getGuess(maxNum)
A couple of specific things to consider: avoid using except without some sense of what exception you're expecting; avoid passing numbers around as strings -- convert numeric strings to numbers on input, convert numbers to numeric strings on output, but use actual numbers in between.

Could not convert string to float in input

#My code should take a random between 1 and 100 and let you guess it.
#This part works, but I want to add the posibility to reveal the number and then is when I get the error "could not convert string to float"
def reveal(guess):
return secret_number
import random
secret_number = random.random()*100
guess = float(input("Take a guess: ")) #This is the input
while secret_number != guess :
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = float(input("Take a guess: ")) #This input is here in order for the program not to print Higher or Lower without ever stopping
else:
print("\nYou guessed it! The number was " ,secret_number)
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", secret_number)
input("\n\n Press the enter key to exit")
Any help would be a great service. Also I am only programming for just a few weeks so sorry if my code looks wrong.
If you want to use float number to compare, the game may be endless because a float number has many fractional digits. Use int number.
#!/usr/bin/env python3.3
# coding: utf-8
import random
def guess_number():
try:
guess = int(input("Take a guess:"))
except ValueError:
print("Sorry, you should input a number")
guess = -1
return guess
if __name__ == '__main__':
secret_number = int(random.random() * 100)
while True:
guess = guess_number()
if guess == -1:
continue
elif guess < secret_number:
print("Lower...")
elif guess > secret_number:
print("Higher...")
else:
print("\nYou got it! The number was ", secret_number)
input("\n\nPress any key to exit.")
break # or 'import sys; sys.exit(0)'
import random
LOWEST = 1
HIGHEST = 100
def main():
print('Guess the secret number between {} and {}!'.format(LOWEST, HIGHEST))
secret = random.randint(LOWEST, HIGHEST)
tries = 0
while True:
guess = raw_input('Your guess: ').strip().lower()
if guess.isdigit():
tries += 1
guess = int(guess)
if guess < secret:
print('Higher!')
elif guess > secret:
print('Lower!')
else:
print('You got it in {} tries!'.format(tries))
break
elif guess == "reveal":
print('The secret number was {}'.format(secret))
break
else:
print('Please enter a number between {} and {}'.format(LOWEST, HIGHEST))
if __name__=="__main__":
main()
Use random.range instead of random.random.
secret_number = random.range(1,100,1)
And ...,str(secret_number)
...
else:
print("\nYou guessed it! The number was " ,str(secret_number))
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", str(secret_number))
...
That way you will be concatenating a string with a string. Also, you can keep random.random and only make the second change.
EDIT:
Another thing to do is to use raw_input instead of input. Then use try.
guess = raw_input("Take a guess: ")
try:
guess = float(guess)
except:
pass
This will try to convert guess into a float, and it that fails, then it will remain a string. That should solve your problem.
You could isolate concerns by defining a function that asks user for input until a float is provided:
def input_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("You should input a float number. Try again.")
Then you could use it in your script:
guess = input_float("Take a guess: ")
If you want to accept 'reveal' as an input in addition to a float number:
def input_float_or_command(prompt, command='reveal'):
while True:
s = input(prompt)
if s == command:
return s
try:
return float(s)
except ValueError:
print("You should input a float number or %r. Try again." % command)

Categories