Incorrect if-else statements - python

I've been trying to write a function that will ask for a number between 1-11 and will randomly choose a number and will compare between them.
I can't figure out why no matter what number I type in (equals or smaller or bigger) it will always type the "Your number is less" message.
def loto():
_number = int(input("Enter any number between 1-10: "))
import random
for x in range(1):
print ("Python chose: " + str(random.randint(1,11)))
if ("_number" == "random"):
print ("You Won! :)")
if ("_number" < "random"):
print ("Your number is less")
if ("_number" > "random"):
print ("Your number is more")
else:
print ("You Lost :(")
loto()
I'm using Python 3.
Thanks:)

Your first problem is that you're comparing the strings "_number" and "random". ASCIIbetically (or, rather, Unicoderifically), "_number" < "random", because the _ character is #95 and the r character is #114.
If you want to compare two variables, you just refer to the variables, not strings that happen to be the same as the names of those variables.
Your second problem is that random isn't your random number, it's the module you used to create that number. And, more seriously, you aren't storing that number anywhere—you're just converting it to a string to print it out and then throwing it away.
Your third problem is that you need to change those ifs to elifs. Otherwise, the You Lost message gets printed whenever _number > random is not true, instead of only whenever all of the three comparisons are not true.
Putting that all together:
choice = random.randint(1,11)
for x in range(1):
print ("Python chose: " + str(choice))
if (_number == choice):
print ("You Won! :)")
elif (_number < choice):
print ("Your number is less")
elif (_number > choice):
print ("Your number is more")
else:
print ("You Lost :(")
Of course there's no way to actually lose your game—one of the three conditions is always going to be true. (If you were using complex numbers, or floats including NaN, you could input a number that wasn't comparable in any way to the selected one, but you're not.)
While we're at it:
There's no reason to name your variable _number instead of number.
That for x in range(1): loop doesn't do anything useful—it loops exactly once, setting x to 0, which you never use.
You don't need parentheses around your conditions.
You shouldn't import modules in the middle of a function like that except in special cases where you need unusual things like lazy loading.
You should follow PEP 8 style, or at least pick a consistent style to follow.
It's simpler to just pass multiple arguments to print, or to use string formatting, than to manually convert things to strings and concatenate them.
So:
import random
def loto():
number = int(input("Enter any number between 1-10: "))
choice = random.randint(1, 11)
print("Python chose:", choice)
if number == choice:
print("You Won! :)")
elif number < choice:
print("Your number is less")
elif number > choice:
print("Your number is more")
else:
print("You Lost :(")
loto()

You were comparing strings not variables, you need to remove quotes, and you not saved random number into a variable. The for loop is making one repetition only, you can remove it.
Update your cod like this:
import random
def loto():
_number = int(input("Enter any number between 1-10: "))
rand_number = random.randint(1,11) # can't had the same name as random
if (_number == rand_number):
print ("You Won! :)")
elif (_number < rand_number):
print ("Your number is less")
elif (_number > rand_number):
print ("Your number is more")
else:
print ("You Lost :(")
loto()

Related

What can I do to fix my simple computer-player game code? Syntax Error

I'm new to Python and I wanted to practice doing loops because I’ve been having the most trouble with them. I decided to make a game where the user will pick a number from 0-100 to see if they can win against the computer.
What I have going right now is only the beginning. The code isn’t finished. But trying out the code I got a Syntax error where the arrow pointed at the colon on the elif function.
How do I fix this? What can I do?
I accept any other additional comments on my code to make it better.
Here’s my code:
import random
min = 0
max = 100
roll_again = "yes"
quit = "no"
players_choice = input()
computer = random.randint
while roll_again == "yes":
print("Pick a number between 1-100: ")
print(players_choice)
if players_choice >= 0:
print("Your number of choice was: ")
print(players_choice)
print("Your number is high.")
if computer >= 0:
print("Computers number is: ")
print(computer)
print("Computers number is high.")
if computer >= players_choice:
print("Computer wins.")
print("You lose.")
print("Would you like to play again? ", +roll_again)
elif:
print(quit)
end
Goal:
Fix computer-player game while learning more about python. Providing additional documentation on where to start would be helpful.
The reason you are getting an error pointing to elif is because elif needs a condition to check. You need to use if elif and else like this:
if a == b:
print('A equals B!')
elif a == c:
print('A equals C!')
else:
print('A equals nothing...')
Also, Python relies on indentation to determine what belongs to what, so make sure you are paying attention to your indents (there is no end).
Your code has more errors after you fix the if statements and indentation, but you should be able to look up help to fix those.
There are a lot of problems with your code. Here is a working version, hope it helps you understand some of the concepts.
If not, feel free to ask
import random
# min and max are names for functions in python. It is better to avoid using
# them for variables
min_value = 0
max_value = 100
# This will loop forever uless something 'breaks' the loop
while True:
# input will print the question, wait for an anwer and put it in the
# 'player' variable (as a string, not a number)
player = input("Pick a number between 1-100: ")
# convert input to a number so we can compare it to the computer's value
player = int(player)
# randint is a function (it needs parentheses to work)
computer = random.randint(min_value, max_value)
# print what player and computer chose
print("Your choice: ", player)
print("Computer's choice: ", computer)
# display the results
if computer >= player:
print("Computer wins. You loose")
else:
print("you win.")
# Determine if user wants to continue playing
choice = raw_input("Would you like to play again? (yes/No) ")
if choice != 'yes':
# if not
break
There are a lot of indentiation issues and the if and elif statements are used incorrectly. Also take a look at how while loops work.
Based on the code you provided here is a working solution, but there are many other ways to implement this.
Here is some helpful tutorials for you on if/else statements as well as other beginner topics:
Python IF...ELIF...ELSE Statements
import random
minval = 0
maxval = 100
roll_again = "yes"
quit_string = "no"
while True:
players_choice = int(input("Pick a number between 1-100:\n"))
computer = random.randint(minval,maxval)
#checks if players choice is between 0 and 100
if players_choice >= 0 and players_choice <= 100:
print("Your number of choice was: ")
print(players_choice)
#otherwise it is out of range
else:
print("Number out of range")
#check if computers random number is in range from 0 to 100
if computer >= 0 and computer <= 100:
print("Computers number is: ")
print(computer)
# if computer's number is greater than players number, computer wins
if computer > players_choice:
print("Computer wins.")
print("You lose.")
#otherwise if players number is higher than computers, you win
elif computer < players_choice:
print("You won.")
#if neither condition is true, it is a tie game
else:
print("Tied game")
#ask user if they want to continue
play_choice = input("Would you like to play again? Type yes or no\n")
#checks text for yes or no use lower method to make sure if they type uppercase it matches string from roll_again or quit_string
if play_choice.lower() == roll_again:
#restarts loop
continue
elif play_choice.lower() == quit_string:
#breaks out of loop-game over
break

Python; How do I test if something is in a list?

I was writing a code that will ask you to play a guessing game. It will ask you whether you want to play or not and proceed.
It was supposed to ask a number again if the entered value is not in the list but It is not working. I couldn't get it. Thx by now!
import random
import math
import time
repeat=True
numbers = ["1","2","3","4","5"]
gamestart=False
gamecontinue=True
def guess():
chosennumber=random.choice(numbers)
guessnumber=raw_input(">Guess the number I chose between 0 and 6:")
if guessnumber==chosennumber and guessnumber in numbers:
print ">Congratulations, I chose %d too!" % (int(chosennumber))
print
elif guessnumber!=chosennumber:
print "That is not right."
print "I chose %d." % (int(chosennumber))
print
elif not guessnumber in numbers:
while not guessnumber in numbers:
guessnumber=raw_input(">Please enter a number between 0 and 6:")
if raw_input(">Do you want to play guessing game? Y or N:") == "Y":
gamestart=True
else:
print "Okay, I will play myself."
time.sleep(2)
print "Bye :("
while gamestart==True and gamecontinue==True:
guess()
if raw_input (">Do you want to play again? Y or N:") == "N":
gamecontinue=False
print "Okay, I will play myself."
time.sleep(2)
print "Bye :("
so you figured out what was the issue, good! but i have one more tip for you, a better approach to achieve this is check if the input is correct as soon is readed, if it is correct you keep going, if it not, you ask for it again right there:
while True:
guessnumber=raw_input(">Guess the number I chose between 0 and 6:")
if guessnumber in numbers:
print "good!"
break
else:
print "bad!"
and now you're sure that the input is correct so you only check:
if guessnumber==chosennumber:
print ">Congratulations, I chose %d too!" % (int(chosennumber))
else:
print "That is not right."
print "I chose %d." % (int(chosennumber))
if number not in numbers
That will do the trick
It checks if it is true that the selected number is in the list
The problem is that if you put two elif statements the first one will proceed first.
elif guessnumber!=chosennumber:
print "That is not right."
print "I chose %d." % (int(chosennumber))
print
This condition will be asked first. But if you look again at it whether the input (guessnumber) is in the list or not it will proceed. So if we want it to become a condition which we enter a number that is in a list but not matching with the chosen number, we will add another condition to elif statement.
code will be like this
elif guessnumber!=chosennumber and guessnumber in numbers:
Slight detail but good to keep in mind I think.

Loops not working in Python 3

I originally wrote this program in python 2, and it worked fine, then I switched over to python 3, and the while loop working.
I don't get any errors when I run the program, but it isnt checking for what the value of i is before or during the run. The while loop and the first if loop will run no matter what.
#imports the random module
import random
#Creates variable that is used later
i = 0
#chooses a random number betweeen 1 - 100
randomNumber = random.randint(1,10)
#prints the number
print (randomNumber)
#Creates while loop that runs the program until number is guessed
while i == 0:
#Creates a variable where the answer will be stored, and then asked the question in the quotes
user_answer = input("Try to guess the magic number. (1 - 10) ")
print ("\n")
if user_answer == randomNumber:
print("You guessed correct")
break
else:
print("Incorrect. Try again.")
Thanks for any help in advance.
You are comparing something like '6' == 6, since you didn't convert the user input to an int.
Replace user_answer = input("Try to guess the magic number. (1 - 10) ") with user_answer = int(input("Try to guess the magic number. (1 - 10) ")).
user_answer will store the input as string and random.randint(1,10) will return an integer. An integer will never be equal to a string. So you need to convert user_input to integer before checking.
#imports the random module
import random
#Creates variable that is used later
i = 0
#chooses a random number betweeen 1 - 100
randomNumber = random.randint(1,10)
#prints the number
print (randomNumber)
#Creates while loop that runs the program until number is guessed
while i == 0:
#Creates a variable where the answer will be stored, and then
asked the question in the quotes
user_answer = input("Try to guess the magic number. (1 - 10) ")
# better use exception handling here
try:
user_answer = int(user_answer)
except:
pass
print ("\n")
if user_answer == randomNumber:
print("You guessed correct")
break
else:
print("Incorrect. Try again.")

Guess My number game with limited number of guesses

I'm new to python and I'm trying to make the guess my number game with a limit of only 5 guesses, everything I've tried so far has failed. how can I do it?, I forgot to mention that I wanted the program to display a message when the player uses all their guesses.The code below only prints the "You guessed it" part after the 5 guesses whether they guess it or not.
import random
print ("welcome to the guess my number hardcore edition ")
print ("In this program you only get 5 guesses\n")
print ("good luck")
the_number = random.randint(1, 100)
user = int(input("What's the number?"))
count = 1
while user != the_number:
if user > the_number:
print ("Lower")
elif user < the_number:
print ("Higher")
user = int(input("What's the number?"))
count += 1
if count == 5:
break
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
input ("\nPress enter to exit")
Your edit says you want to differentiate between whether the loop ended because the user guessed right, or because they ran out of guesses. This amounts to detecting whether you exited the while loop because its condition tested false (they guessed the number), or because you hit a break (which you do if they run out of guesses). You can do that using the else: clause on a loop, which triggers after the loop ends if and only if you didn't hit a break. You can print something only in the case you do break by putting the print logic right before the break, in the same conditional. That gives you this:
while user != the_number:
...
if count == 5:
print("You ran out of guesses")
break
else:
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
However, this puts code for different things all over the place. It would be better to group the logic for "guessed right" with the logic for warmer/colder, rather than interleaving them with part of the logic for how many guesses. You can do this by swapping where you test for things - put the 'is it right' logic in the same if as the warmer/colder, and put the number of guesses logic in the loop condition (which is then better expressed as a for loop). So you have:
for count in range(5):
user = int(input("What's the number?"))
if user > the_number:
print("Lower")
elif user < the_number:
print("Higher")
else:
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
break
else:
print("You ran out of guesses")
You have two options: you can either break out of the loop once the counter reaches a certain amount or use or a for loop. The first option is simplest given your code:
count = 0
while user != the_number:
if user > the_number:
print ("Lower")
elif user < the_number:
print ("Higher")
user = int(input("What's the number?"))
count += 1
if count == 5: # change this number to change the number of guesses
break # exit this loop when the above condition is met

Basic roulette simulator in Python (red/black only)

I'm writing a VERY basic roulette simulator in python. At the moment, I'm only focusing on red/black betting (basically the same as betting on heads or tails, using a coin).
My code has various issues. Please forgive my very basic knowledge of the language.
import random
# Defines initial amounts of money and losses
money = 50
losses = 0
# Asks user how much to bet
def roulette_sim():
print "How much do you want to bet?"
bet = raw_input("> ")
if bet > money:
bet_too_much()
else:
red_or_black()
# Prevents one from betting more money than one has
def bet_too_much():
print "You do not have all that money. Please bet again."
raw_input("Press ENTER to continue> ")
roulette_sim()
# Asks user to select red or black, starts the sim, modifies money/losses
def red_or_black():
print "OK, you bet %r" % (bet)
print "Red or black?"
answer = raw_input("> ")
number = random.randint(1, 2)
if number == 1 and answer == "red":
print "You win!"
money += bet
print "You now have %r money" % (money)
print "Your losses are %r" % (losses)
replay()
elif number == 2 and answer == "black":
print "You win!"
money += bet
print "You now have %r money" % (money)
print "Your losses are %r" % (losses)
replay()
else:
print "You lost!"
money -= bet
losses += bet
print "You now have %r money" % (money)
print "Your losses are %r" % (losses)
replay()
# Asks user whether he/she wants to play again
def replay():
print "Do you want to play again?"
play_again = raw_input("y/n> ")
if play_again == "y":
roulette_sim()
else:
print "OK, bye loser!"
roulette_sim()
First issue so far: the bet_too_much function doesn't work. Whatever amount I input, the program states it's too much (ie: 'bet' is always greater than 'money'). Why?
Second issue so far: when I want to add/subtract 'bet' to/from 'money' by using, for example:
money += bet
python treats this as summing an int with a string (at least I think it does) rather than summing two variables. Why is this?
Any help would be appreciated.
Thanks
Both things happen because Python does not do implicit conversions. You have to tell it explicitly that you want something to be an integer, it will not do it for you.
So, for the first issue:
bet = raw_input("> ")
if bet > money:
...
has to be
bet = raw_input("> ")
bet = int(bet)
if bet > money:
...
because you do not want to compare a string with an integer (you can, but with the results you're getting right now).
For the second, you have to be explicit as well:
money += int(bet)
(of course, if you already converted bet to an int, you're fine).
Javascript is notorious for doing this implicit conversions, so if you have happen to be familiar with that or a language that is similar, forget about that and be explicit about the type you're using. Which, on the whole, is safer.
The raw_input() function returns a string value, but money is an integer. Comparing strings to numbers always ends up with Python 2 ordering numbers as smaller than strings.
Convert the result of raw_input() to an integer:
def roulette_sim():
print "How much do you want to bet?"
bet = int(raw_input("> "))
This may throw a ValueError exception if the input given is not a valid number; you may want to catch that exception and tell the user to enter a number instead:
def roulette_sim():
print "How much do you want to bet?"
while True:
try:
bet = int(raw_input("> "))
except ValueError:
print "Please enter a valid amount, a number."
else:
break
You are comparing the string you get from raw_input("> ") with a integer. This will not end well.
Try this function instead (havent tested it fully):
def roulette_sim():
while(1):
print "How much do you want to bet?"
try:
bet = int(raw_input("> "))
break
except ValueError:
print 'You need to input a number'
if bet > money:
bet_too_much()
else:
red_or_black()
EDIT: changed to "except ValueError" according to comment. I know I am a bit lazy on the except handling part of python programing, but perhaps I should not teach that to others :-)

Categories

Resources