I am having this annoying problem with if/elif statements. I'm a newbie, sorry for dumb question. I tried finding a fix but no one had it for Python.
So, I want the program to execute the code in the if clause if both conditions are True. As far as I know the code in the clause will only execute if both the conditions are True, am I right? That doesn't seem to happen in my code, though.
result = userNumber + randomNumber
if not result % 2 == 0 and userChoice == 'e' or 'even':
print ('That number is odd, so you lost :(')
if result % 2 == 0 and userChoice == 'e' or 'even':
print ('That number is even, so you won :)')
if not result % 2 == 0 and userChoice == 'o' or 'odd':
print ('That number is odd, so you won :)')
if result % 2 == 0 and userChoice == 'o' or 'odd':
print ('That number is even, so you lost :(')
So, the userNumber and the randomNumber variables were set before. In this game, what happens is: the user chooses even or odd, and inputs a number from 0 to 5. Then, the computer randomly chooses a number from 0 to 5, using random.randint().
After that, the variable result is set to the sum of userNumber + randomNumber. If the result of that sum is odd and the user chose odd, the user wins, and if the user chose even, the user loses. If the sum is even it's exactly the opposite: if the result of the previous sum result is even and the user chose even, the user wins, and if the user chose odd, the user loses.
I hope you understand!
So, the problem with my code right now is that it executes all four IF statements for some reason, so the final output looks like this:
Welcome to the Even or Odd game!
Type letter 'o' if you want odd and the letter 'e' if you want even.
Your choice: o
Now, type in a number from 0 to 5: 2
Your number: 2
Computer's number: 5
Adding these two numbers together, we get 7
That number is odd, so you lost :(
That number is even, so you won :)
That number is odd, so you won :)
That number is even, so you lost :(
The code for that is:
import random
import time
print ('Welcome to the Even or Odd game!')
print ('Type letter \'o\' if you want odd and the letter \'e\' if you want even.')
userChoice = input('Your choice: ').lower()
time.sleep(1)
userNumber = int(input('Now, type in a number from 0 to 5: '))
randomNumber = random.randint(0,5)
time.sleep(2)
print ('Your number: ' + str(int(userNumber)))
time.sleep(2)
print ('Computer\'s number: ' + str(int(randomNumber)))
time.sleep(2)
result = userNumber + randomNumber
print (str(result))
print ('Adding these two numbers together, we get ' + str(result))
if not result % 2 == 0 and userChoice == 'e' or 'even':
print ('That number is odd, so you lost :(')
if result % 2 == 0 and userChoice == 'e' or 'even':
print ('That number is even, so you won :)')
if not result % 2 == 0 and userChoice == 'o' or 'odd':
print ('That number is odd, so you won :)')
if result % 2 == 0 and userChoice == 'o' or 'odd':
print ('That number is even, so you lost :(')
Any ideas? Sorry for long post, and sorry if duplicate! I just didn't find any answers around the internet :/ Thank you so much!
EDIT: I also tried using elif statements instead of all if, didn't work either.
>>> if False or 'even':
... print('This shouldn\'t work')
...
This shouldn't work
The truth value of a non-empty string is True. Although your other conditions are False, you're still executing those statements because of the way you've written your condition.
As it stands, this is how your condition is evaluated:
if (not result % 2 == 0) and ((userChoice == 'e') or ('even')):
# __________1________________________2_________________3_____
(1) is True. (2) is False. But (3) is True (because of the truthiness of strings). So you execute the first if.
What's more, you only want one of these conditions to execute. Not all of them. You'll need to replace your second if and onwards with elif. So, if one condition is True, all the other conditions are skipped.
You'll need to make a small change:
if not result % 2 == 0 and userChoice in ['e', 'even']:
...
elif result % 2 == 0 and userChoice in ['e', 'even']:
...
elif not result % 2 == 0 and userChoice in ['o', 'odd']:
...
elif result % 2 == 0 and userChoice ['o', 'odd']:
...
Related
I am doing an assignment for school where I need to make a list and assign 4 random integers to the list between 1 and 9. Then, I need to prompt the user for what their guess is for each value. If they get any of the numbers right, I need to say how many, but I've been working on this for like 3 hours and I'm getting nowhere. Currently, all I have is a massive useless nested if/elif statements.
This is the assignment prompt:
Program Specifications:
Computer should generate 4 random numbers from 1 - 9 as the "Secret Code".
User should be prompted for their guess of those four numbers.
After they provide their full guess, the user is told how many are correct.
As long as the user does not get all four correct, they keep getting asked for their guess.
After the user finally gets all of them correct (yes - all four), they are congratulated and then told how many tries it took them.
Technical Requirements:
Use at least one list
Use at least one function with parameters
I'm so confused and I don't know where to start. Here is my current code:
import random
count = 0
guess1 = 1
guess2 = 1
guess3 = 1
guess4 = 1
def getGuess(count,guess1,guess2,guess3,guess4):
while True:
guess1 = input("What is your guess for the first number? ")
guess2 = input("What is your guess for the second number? ")
guess3 = input("What is your guess for the third number? ")
guess4 = input("What is your guess for the fourth number? ")
if str(guess1) == numbers[0] and str(guess2) == numbers[1] and str(guess3) == numbers[2] and str(guess4) == numbers[3]:
print("Your first, second, third, and fourth numbers are correct!")
elif guess1 == numbers[0] and guess2 == numbers[1] and guess3 == numbers[2]:
print("Your first, second, and third numbers are correct!")
elif guess1 == numbers[0] and guess2 == numbers[1]:
print("Your first and second number are correct!")
elif guess1 == numbers[0]:
print("Your first number is correct!")
elif guess2 == numbers[1]:
print("Your second number is correct!")
elif guess2 == numbers[1] and guess3 == numbers[2]:
print("Your second and third numbers are correct!")
elif guess2 == numbers[1] and guess3 == numbers[2] and guess4 == numbers[3]:
print("Your second, third, and fourth numbers are correct!")
elif guess3 == numbers[2]:
print("Your third number is correct!")
elif guess3 == numbers[2] and guess4 == numbers[3]:
print("Your third and fourth numbers are correct!")
elif guess4 == numbers[3]:
print("Your fourth number is correct!")
else:
print("None of your numbers are correct. Try again.")
numbers = []
for i in range(4):
num = int(random.randrange(1,9))
numbers.append(num)
print(numbers)
getGuess(count,guess1,guess2,guess3,guess4)
I see your attempt so I'm going to tell you the problems, as comments said:
Logic flow: your if else statement are serving 4 numbers, what if 10, 100 numbers? It should be generic
You are comparing string with integer, should cast it
Should package your variables inside your function. Which is very ambiguous of guess1 = 1, guess1 function variable, guess1 from input,...
Init random numbers
import random
numbers = []
for i in range(4):
num = int(random.randrange(1,9))
numbers.append(num)
getGuess function, which is getting guess numbers from input string, then split it and convert to int.
def getGuess(numbers):
retryCount = 0
while True:
# You can put try catch here for number validation
guessNums = [int(x) for x in input("Numbers: ").split()]
# To make sure your input must be the same length
if len(guessNums) != len(numbers):
print('Not available numbers')
continue
# Here we just check for incorrect, once it's met, the for loop will be broken and go to the next while loop
isIncorrect = False
for index, num in enumerate(numbers):
if num != guessNums[index]:
isIncorrect = True
retryCount += 1
print('Order of ' + str(index + 1) + ' is incorrect')
break
# When every number is equal, not incorrect occured, return retry count
if isIncorrect == False:
return retryCount
Using:
print('Your retry count: ' + str(getGuess(numbers)))
You can optimize many of the parts of your code.
Assumption: You know how to use lists as you are already using numbers as a list. I am staying away from dictionary. Not sure if you know its use. Also assume you understand list comprehension. If you dont, see this link on list comprehension.
Now let's look at your code. Here are a few things to consider:
You don't need 4 variables to store the 4 input values. You can use a list and store all 4 of them there.
As many have already suggested, you should convert the input value into an integer. When you convert string to integer, there is a potential that the string is not an integer. This can result in code getting broken. So use Try Except to catch the error while converting to int
Your random.randrange(1,9) will create integers. So you dont have to explicitly convert them back to integer.
You have 4 inputs and 4 values to compare. You can map each value to the position and compare. That will reduce the complexity. For the ones that are successful, keep a tab of it. Then print the ones that matched. Again, this can be done using a list or dictionary.
With all that to consider, I have re-written your code as follows. See if this helps you with the solution.
import random
nums = [random.randrange(1,9) for _ in range(4)]
def getGuess():
g = ['first','second','third','fourth']
i = 0
gx = []
while i<4:
try:
x = int(input(f"What is your guess for the {g[i]} number? :"))
gx.append(x)
i+=1
except:
print ('Not numeric, please re-enter')
gwords = [g[i] for i in range(4) if nums[i] == gx[i]]
if gwords:
if len(gwords) == 1:
resp = "Your " + gwords[0] + ' number is correct!'
else:
resp = "Your " + ', '.join(gwords[:-1]) + ' and ' + gwords[-1] + ' numbers are correct!'
print (resp)
else:
print ("None of your numbers are correct. Try again.")
getGuess()
Here's an example run of the above code:
What is your guess for the first number? :1
What is your guess for the second number? :6
What is your guess for the third number? :5
What is your guess for the fourth number? :4
Your second, third and fourth numbers are correct!
I'm new to python so I decided to make a simple dice game using a while loop just to do a simple test of myself. In the game, I use the module random and the method random.randint(1, 6) to print a random integer of any value from "1 to 6", which is evidently how a dice works in real life. But to make this a game, if the integer that is printed is even (random.randint(1, 6) % 2 ==0) then 'you win' is printed. If the integer is odd, then 'you lose' is printed. After this, the console asks if you want to roll the dice again, and if you say yes (not case sensitive hence .lower()) then it rolls again and the loop continues, but if you say anything else the loop breaks.
I thought this is was how it would work, but every now and then, when an even number is rolled, 'you lose' is printed, and the opposite for odd numbers, which is not what I thought I had coded my loop to do. Obviously I'm doing something wrong. Can anyone help?
This is my code:
import random
min = 1
max = 6
roll_again = True
while roll_again:
print(random.randint(min, max))
if random.randint(min, max) % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
print(random.randint(min, max))
if random.randint(min, max) % 2 == 0:
print('you win')
Those are two separate calls to randint(), likely producing two different numbers.
Instead, call randint() once and save the result, then use that one result in both places:
roll = random.randint(min, max)
print(roll)
if roll % 2 == 0:
print('you win')
You are generating a random number twice, the number printed isn't the same the number as the one you are checking in the if condition.
You can save the number generated in a variable like this to check if your code is working fine :
import random
min = 1
max = 6
roll_again = True
while roll_again:
number = random.randint(min, max)
print(number)
if number % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
You need to assign random number to a variable, right now printed and the other one are different numbers.
import random
min = 1
max = 6
dice = 0
while True:
dice = random.randint(min, max)
print(dice)
if dice % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
random.randint(min,max) returns different value every time it is executed. So, the best thing you can do is store the value at the very first execution and check on that stored value for Win or Loss.
You can try this version of code:
import random
while(True):
value = random.randint(1,6)
print(value)
if(value % 2 == 0):
print("You Win!")
else:
print("You Lose!")
again = input("Want to roll Again? Type 'Yes' or 'No'")
if(again.lower() != 'yes'):
break
I'm learning if and then statements. I'm trying to write code that takes any decimal number input (like 2, 3, or even 5.5) and prints whether the input was even or odd (depending on whether the input is actually an integer.)
I get an error in line 8
#input integer / test if any decimal number is even or odd
inp2 = input("Please enter a number: ")
the_number = str(inp2)
if "." in the_number:
if int(the_number) % 1 == 0
if int(the_number) % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
else:
print("You dum-dum, that's not an integer.")
else:
the_number = int(inp2)
if the_number % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
I'm just starting with python so I appreciate any feedback.
You have to include a colon at the end of second if statement, like you did in your other conditional statements.
if int(the_number) % 1 == 0:
Next time, give a closer look at the error message. It'll give you enough hints to fix it yourself, and that's the best way to learn a language.
EOL.
You forgot a :. Line 8 should read if int(the_number) % 1 == 0:.
Try putting the : at the end of the if statement
if int(the_number) % 1 == 0:
You can test your input as following code snippet
num = input('Enter a number: ')
if num.isnumeric():
print('You have entered {}'.format(num))
num = int(num)
if num%2:
print('{} is odd number'.format(num))
else:
print('{} is even number'.format(num))
else:
print('Input is not integer number')
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I have made this code to emulate a rock paper scissors game. I have a procedure which has the main game, and when I run this by itself without the if loop at the end, it works. However, when I try to validate whether or not the user entry is numerical, it does not print the correct message. Here is the full code:
import random
def game(choice):
number = random.randint(1,3)
if choice == 1 and number == 2:
print("You lose.")
if choice == 1 and number ==3:
print("You win.")
if choice == 1 and number == 1:
print("It is a draw")
if choice == 2 and number == 3:
print("You lose.")
if choice == 2 and number ==1:
print("You win.")
if choice == 2 and number == 2:
print("It is a draw")
if choice == 3 and number == 1:
print("You lose.")
if choice == 3 and number ==2:
print("You win.")
if choice == 3 and number == 3:
print("It is a draw")
x = input("Choose 1 (rock), 2 (paper) or 3 (scissors).")
digit = x.isdigit()
if digit == True:
game(x)
By the way, there is no error message, the procedure just does not work!
First of all, there are a few issues with your code. If you wish to ignore, skip to Error Handling for answer to your question. You will find it in there.
Naming Variables
Your variables do not tell a person reading your code what they are. If you showed someone the word number, they would not know that it is what the computer chooses in rock paper scissors. Same with choice (who's choice?) and even more so x. So why don't we name them computer_choice, user_choice and choice respectively. I know these are a bit longer to type, but it is worth sacrificing a few extra keystrokes for a bit more clarity. Also notice that I used snake_case name formatting as per usual Python standards.
Repetitiveness/ game()
Your game function could do with a bit of re-doing. All you need is a general 'formula' for winning and losing. In this case, losing is when (thanks to #Brett Beatty) if computer_choice == (user_choice + 1) % 3, drawing is when computer_choice == user_choice and winning is everything else. Also, when your code is being played, the user only knows if they have won or lost, and not what the computer chose, so to add a bit more clarity, I added a list and another print() line. This feature is also useful to test code. Additionally, use zero-based variable values, such as in the computer_choice and user_choice variables. This is useful when converting values to list indexes. Below is a revised version of your code that i have made which includes all points above (I have also made it a function, as you will see below - I just think it looks better):
import random
def game(user_choice):
user_choice -= 1
rps = ["Rock", "Paper", "Scissors"]
computer_choice = random.randint(0, 2)
print("You: {} Computer: {}".format(rps[user_choice], rps[computer_choice]))
if user_choice == computer_choice:
return 0
elif computer_choice == (user_choice + 1) % 3:
return -1
else:
return 1
Error Handling
To make sure the user enters an integer, you would have to add int() around the input statement. However, this alone would return ValueError if the value entered by the user is not an integer, and this is a problem. However, there is a way to fix this using try: except: else: blocks, as you will see below. This is what you would need to decide if the value is an integer, it also prints the correct message when it is not. I also think this is what you wanted for if digit == True(FYI you would only need if digit if you were to do it that way).
def main():
while True:
try:
value = int(input("Choose 1 (rock), 2 (paper) or 3 (scissors):"))
except ValueError: # If any part of the code in the try block raises a ValueError
print("Not an integer")
else: # If error is not raised
if not 1 <= value <= 3: # If value is not between 1 and 3
print("Must be between 1 and 3")
else:
result = game(value) # sets result to return value from game()
break
if result == 1:
print("You Win")
elif result == -1:
print("You Lose")
else:
print("It's a Draw")
And Finally, the 'if loop'?
Let me just make this clear. There is no such thing as an if loop!!! An if statement runs code **ONCE** if a certain condition is True. I think what you want is a while loop. This runs code **REPEATEDLY** as long as a certain condition is True. In the code below, I created a while True loop, which runs the code each time the user types in "y", and breaks from the loop if not.
Also, use if __name__ == '__main__'. It exists in Python so that Python files can act as either reusable modules, or as standalone programs. It also looks more complex, if you want to look smart.
if __name__ == '__main__':
while True:
main()
if input("Again? Yes(y) No(Anything else): ").lower() != 'y':
break
Example Output (ignore colours):
Choose 1 (rock), 2 (paper) or 3 (scissors):1
You: Rock Computer: Scissors
You Win
Again? Yes(y) No(Anything else): y
Choose 1 (rock), 2 (paper) or 3 (scissors):3
You: Scissors Computer: Scissors
It's a Draw
Again? Yes(y) No(Anything else): y
Choose 1 (rock), 2 (paper) or 3 (scissors):2
You: Paper Computer: Paper
It's a Draw
Again? Yes(y) No(Anything else): n
Process finished with exit code 0
Also, for the OP, if you haven't already, I would recommend downloading Pycharm. It is completely free, and makes coding a lot easier. It also improves presentation too. It picks up on some of the things mentioned above, as well as keeping your code in line with PEP guidelines.
I am a new programmer with experience with Visual Basic for Applications and have recently changed to python.
I'm working on a number guessing game and so far progress has been great. The user enters 4 digits into the program. The program also generates a 4 digit number and the program returns Ys or Ns to show whether any digits are correct or not. EG 1357 as a user guess and 1358 as the programs number shows YYYN as output.
I'm trying to rework the program to make it simpler for users by showing H or L to suggest that they need to guess higher or lower IF the digit guessed is incorrect. If it's correct, then a Y should be shown as per normal. I am aware that it's a condition in the loop I need to change or another loop I need to add but I am struggling to see where to add this and how to write it. Does anybody have a solution for this?
Here is part of my code for the section of the program which returns the result for the guesses.
lives = 10
while lives > 0:
number = input("Enter your guess: ")
letter = ''
for i in range(len(numToGuess)):
letter += 'Y' if int(number[i]) == numToGuess[i] else 'N'
if letter == 'Y' * len(numToGuess):
print("Good job!")
break
print(letter)
lives -= 1
else:
print("Game over! You used up all of your tries.")
Does anybody have a solution for this?
I prefer to use lists for this. Meaning, I'd convert both the correct answer and the user guess into separate digits saves in two lists and then compare them.
Let's say the correct answer is '1234':
lives = 10
correct_answer = 1234
correct_answer = [int(char) for char in str(correct_answer)]
while lives > 0:
letter = ''
number = input("Enter your guess: ")
number = [int(char) for char in str(number)]
if number == correct_answer:
print("Correct!")
break
for i in range(len(correct_answer)):
if correct_answer[i] == number[i]:
letter += 'Y'
elif correct_answer[i] > number[i]:
letter += 'H'
else:
letter += 'L'
print("Your guess is wrong: ", letter)
lives -= 1
print("Game over!")
Now for example:
Enter your guess: 1111
Your guess is wrong: YHHH
Enter your guess: 1235
Your guess is wrong: YYYL
Enter your guess: 1234
Correct!
Game over!
>>>
You can use zip function for compare the letters :
>>> a='1357'
>>> b='1358'
>>> l=[]
>>> for i,j in zip(a,b):
... if i==j :l.append('Y')
... else :l.append('N')
...
>>> ''.join(l)
'YYYN'
And for check the answer you can use a generator expression within all :
>>> all(i=='Y' for i in l)
False
You don't need to change your loop condition. Just change the logic of your if expression.
letter = ''
for i in range(len(numToGuess)):
if int(number[i]) == numToGuess[i]:
letter += 'Y'
elif int(number[i]) > numToGuess[i]:
letter += 'H'
else:
letter += 'L'
Or, in one line:
letter = ''
for i in range(len(numToGuess)):
letter += 'Y' if int(number[i]) == numToGuess[i] else ('H' if int(number[i]) > numToGuess[i] else 'L')