if, elif not working as expected - python

I am new to Python and I do not know why but the if, elif in the following code is not working as I expect it to. However,
It works perfectly when I type 1 to 7
it works perfectly when I type 0 8 or 9 (it says "Try again")
It does not work if I type 10 to 69, 100 to any number
When I say it does not work I mean it prints
my_shape_num = h_m.how_many()
But I do not know why. It has to stop if choice is not between 1 and 7
def main(): # Display the main menu
while True:
print
print " Draw a Shape"
print " ============"
print
print " 1 - Draw a triangle"
print " 2 - Draw a square"
print " 3 - Draw a rectangle"
print " 4 - Draw a pentagon"
print " 5 - Draw a hexagon"
print " 6 - Draw an octagon"
print " 7 - Draw a circle"
print
print " X - Exit"
print
choice = raw_input(' Enter your choice: ')
if (choice == 'x') or (choice == 'X'):
break
elif (choice >= '1' and choice <= '7'):
my_shape_num = h_m.how_many()
if ( my_shape_num is None):
continue
d_s.start_point() # start point on screen
if choice == '1':
d_s.draw_triangle(my_shape_num)
elif choice == '2':
d_s.draw_square(my_shape_num)
elif choice == '3':
d_s.draw_rectangle(my_shape_num)
elif choice == '4':
d_s.draw_pentagon(my_shape_num)
elif choice == '5':
d_s.draw_hexagon(my_shape_num)
elif choice == '6':
d_s.draw_octagon(my_shape_num)
elif choice == '7':
d_s.draw_circle(my_shape_num)
else:
print
print ' Try again'
print
Edit: Ok, sorted:
choice = raw_input(' Enter your choice: ')
if (choice == 'x') or (choice == 'X'):
break
try:
choice = int(choice)
if (1 <= choice <= 7):
my_shape_num = h_m.how_many()
if ( my_shape_num is None):
continue
d_s.start_point() # start point on screen
if choice == 1:
d_s.draw_triangle(my_shape_num)
elif choice == 2:
d_s.draw_square(my_shape_num)
elif choice == 3:
d_s.draw_rectangle(my_shape_num)
elif choice == 4:
d_s.draw_pentagon(my_shape_num)
elif choice == 5:
d_s.draw_hexagon(my_shape_num)
elif choice == 6:
d_s.draw_octagon(my_shape_num)
elif choice == 7:
d_s.draw_circle(my_shape_num)
else:
print
print ' Number must be from 1 to 7!'
print
except ValueError:
print
print ' Try again'
print

Strings are compared lexicographically: '10' is greater than '1' but less than '7'. Now consider this code:
elif (choice >= '1' and choice <= '7'):
In addition to accepting '7', this will accept any string beginning with 1, 2, 3, 4, 5 or 6.
To fix, convert choice to integer as soon as you've tested for 'x', and use integer comparisons thereafter.

'43' < '7' # True
43 < 7 # False
int('43') < int('7') # False
You're comparing strings (text), so the order is like a dictionary. You need to convert them into integers (numbers), so that comparisons put them in counting order.
Then, course, you also need to be prepared for people typing things that aren't numbers:
int('hi') # ValueError

I think it's because you are using string for comparing... try
choice = int(choice)
before if, elif block and change their comparisons to
if choice == 1:
(without quotes)

Related

I can't count the number of tries in this game in pythin

I am a beginner in python and I got a task to make a game of guesses using python. In my assignment, I was told to count the number of tries. But I can't make it work. Any suggestion would be appreciated. (note: the list is for nothing...I was just messing with the code and trying things.)
`
# import random
# a=random.randint(1,30)
a = 23
Dict1 = ["Hello there! How are you?", 0,
"Guess a number Between 1 to 50",
"Your number is too high",
"Your Number is too low",
"Make Your Number A Bit Higher",
"Make Your Number a Bit Lower",
"Congratulations You Have guessed the right number :)"
]
print(Dict1[0])
name = input("What is your Name?\n=")
# print("hi!,{}, Wanna Play a game?".format(name))
print(Dict1[2])
while 1:
inp = float(input("="))
if inp > 50:
print(Dict1[3])
continue
elif inp < 1:
print(Dict1[4])
continue
elif inp < a:
print(Dict1[5])
continue
elif inp > a:
print(Dict1[6])
continue
elif inp == a:
print(Dict1[7])
q = input("Do You Want to Go again? Y or N\n=")
if q.capitalize() == "Y":
print('You have', 5 - 4, "tries left")
print(Dict1[2])
continue
elif q.capitalize() == "N":
break
else:
break
op = inp
while 1:
x = 4
if -137247284234 <= inp <= 25377642:
x = x + 1
print('You have', 5 - x, "tries left")
if x == 5:
break
if x == 5:
print("Game Over")
`
One way to go about it would be to set up a variable to track attempts outside the while loop between a and Dict1
a = 23
attempts = 1
Dict1 = [...]
Then each time they make an attempt, increment in the while loop:
if inp > 50:
print(Dict1[3])
attempts += 1
continue
elif inp < 1:
print(Dict1[4])
attempts += 1
continue
elif inp < a:
print(Dict1[5])
attempts += 1
continue
elif inp > a:
print(Dict1[6])
attempts += 1
continue
EDIT:
Looking more carefully at your code, it seems like you want a countdown. So you could change it to
attempts = 5
and in the while loop
while 1:
...
if q.capitalize() == "Y":
attempts -= 1
print('You have', attempts, "tries left")
print(Dict1[2])
continue

Making Mastermind in Python

I am simply wondering how I can make my game of Mastermind work, more specifically how I would go about making "finish" global, how I would call these functions so that the program works correctly, and overall tips that would help enhance my code. I would also like to know how to make it so the program doesn't 'reroll' the computer-generated number every single loop. This was just a difficult problem for me and I can't seem to understand how to close it out with the correct function calls and niche aspects such as that. Thank you.
run = True
def get_guess():
while run:
guess = input("Provide four unique numbers: ")
count = 0
if len(guess) == 4:
guessdupe = guess[0] == guess[1] or guess[0] == guess[2] or guess[0] == guess[3] or guess[1] == guess[2] or guess[1] == guess[3] or guess[2] == guess[3]
else:
guessdupe = False
try:
try:
for i in range(4):
if int(guess[i]) <= 7 and int(guess[i]) >= 1 and len(guess) == 4:
count += 1
if len(guess) != 4:
print "Your guess must consist of 4 numbers!"
if guessdupe:
count -= 1
print "You can only use each number once!"
except ValueError:
print "You can only use numbers 1-7 as guesses"
except IndexError:
print "You can only use numbers 1-7 as guesses"
if count == 4:
break
return guess
def check_values(computer_list, user_list):
final_list = [''] * 4
for i in range(4):
if user_list[i] in computer_list:
if user_list[i] == computer_list[i]:
final_list[i] = "RED"
else:
final_list[i] = "WHITE"
else:
final_list[i] = "BLACK"
random.shuffle(final_list)
print final_list
return final_list
def check_win(response_list):
if response_list[0] == "RED" and response_list[1] == "RED" and response_list[2] == "RED" and response_list[3] == "RED":
print "Congratulations! You've won the game!"
global finish
finish = True
def create_comp_list():
while run:
compList = [random.randint(1, 7), random.randint(1, 7), random.randint(1, 7), random.randint(1, 7)]
listBool = compList[0] == compList[1] or compList[0] == compList[2] or compList[0] == compList[3] or compList[1] == compList[2] or compList[1] == compList[3] or compList[2] == compList[3]
if listBool:
continue
else:
return compList
def play_game():
for i in range(5):
print create_comp_list()
print get_guess()
check_win(check_values(create_comp_list(), get_guess()))
if finish:
break
play_game()```

Game of Chance in Python 3.x?

I have this problem in my python code which is a coinflip game, the problem is that when It asks, "Heads or Tails?" and I just say 1 or Heads(same for 2 and Tails) without quotation marks and with quotation marks, it does not give me an answer that I am looking for.
I've Tried using quotation marks in my answer which didn't seem to work either.
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails?")
coinnum = random.randint(1, 2)
if coinnum == 1:
return 1
elif coinnum == 2:
return 2
win = bet*2
if choice == "Heads" or "1":
return 1
elif choice == "Tails" or "2":
return 2
if choice == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
elif choice != coinnum:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
The expected output was either "Well done! You have won 200 Dollars!" or "Sorry, you lost 100 Dollars!"
The first thing to note here is that your usage of return seems to be wrong. Please look up tutorials about how to write a function and how to use return.
I think this is what you were trying to do:
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails? ")
coinnum = random.randint(1, 2)
win = bet*2
if choice == "Heads" or choice == "1":
choicenum = 1
elif choice == "Tails" or choice == "2":
choicenum = 2
else:
raise ValueError("Invalid choice: " + choice)
if choicenum == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
else:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
Now, lets go through the mistakes I found in your code:
return was totally out of place, I wasn't sure what you were intending here.
if choice == "Heads" or "1" is invalid, "1" always evaluates to true. Correct is: if choice == "Heads" or choice == "1":
elif choice != coinnum: is unnecessary, if it doesn't run into if choice == coinnum: a simple else: would suffice.

Value error when making a rock, paper, scissors game

I have just started programming in Python. I am currently trying to build a rock, paper, scissors game. The user is asked to pick a number representing one of the three options. Whereas the pc picks a random number. However, i get a value error for the input line. The same line worked fine in a different context (no while loop) but I fail to see what I did wrong. Any help would be greatly appreciated.
I have tried to turn the string into a float and then into an integer. That did not work. Moreover, I have replaced the player input number y a random number to test the rest of the code. This worked just fine.
This is the error message I get:
answerplayer = int (input('What is your choice? ')) #Error
ValueError: invalid literal for int() with base 10: "runfile
The code:
import random
win = False
while win == False:
print ('Rock, Paper, Scissors. 0: Rock; 1: Scissors; 2: Paper')
print ('Make your choice')
answerplayer = int (input('What is your choice? ')) #Error
answer = random.randrange (3)
print (answerplayer)
print (answer)
if answer == 0 and answerplayer == 0 :
print ('TIE')
elif answer == 0 and answerplayer == 1 :
print ('PC Win')
win = True
elif answer == 0 and answerplayer == 2 :
print ('Player Win')
win = True
elif answer == 1 and answerplayer == 0 :
print ('Player Win')
win = True
elif answer == 1 and answerplayer == 1 :
print ('TIE')
elif answer == 1 and answerplayer == 2 :
print ('PC Win')
win = True
elif answer == 2 and answerplayer == 0 :
print ('Player Win')
win = True
elif answer == 2 and answerplayer == 1 :
print ('PC Win')
win = True
elif answer == 2 and answerplayer == 2 :
print ('TIE')
else:
print ('Player Win')
win = True
print ('done')
The code is fine. User input must be something that int() can convert to integer however.
Passes: 1 2 3.444
Fails: sqfe zero
you can solve with:
while win == False:
print ('Rock, Paper, Scissors. 0: Rock; 1: Scissors; 2: Paper')
print ('Make your choice')
answerplayer = input('What is your choice? ')
if not answerplayer.isnumeric() :
print ('No number')
break
answerplayer = int(answerplayer)
answer = random.randrange (3)
print (answerplayer)
print (answer)

Python error in changing item in 2d list

I am making a Tic Tac Toe game and can't assign the sign of player/computer to 2d list.
array = []
player_choice = 0
computer_choice = 0
player_move_col = 0
player_move_row = 0
def starting_array(start_arr):
for arrays in range(0, 3):
start_arr.append('-' * 3)
def print_array(printed_arr):
print printed_arr[0][0], printed_arr[0][1], printed_arr[0][2]
print printed_arr[1][0], printed_arr[1][1], printed_arr[1][2]
print printed_arr[2][0], printed_arr[2][1], printed_arr[2][2]
def player_sign():
choice = raw_input("Do you want to be X or O?: ").lower()
while choice != 'x' and choice != 'o':
print "Error!\nWrong input!"
choice = raw_input("Do you want to be X or O?: ").lower()
if choice == 'x':
print "X is yours!"
return 2
elif choice == 'o':
print "You've chosen O!"
return 1
else:
print "Error!\n Wrong input!"
return None, None
def player_move(pl_array, choice, x, y): # needs played array, player's sign and our col and row
while True:
try:
x = int(raw_input("Which place do you choose?: ")) - 1
y = int(raw_input("What is the row? ")) - 1
except ValueError or 0 > x > 2 or 0 > y > 2:
print("Sorry, I didn't understand that.")
# The loop in that case starts over
continue
else:
break
if choice == 2:
pl_array[x][y] = 'X'
elif choice == 1:
pl_array[x][y] = "O"
else:
print "Choice didn't work"
return pl_array, x, y
starting_array(array)
print_array(array)
# print player_choice, computer_choice - debugging
player_move(array, player_sign(), player_move_col, player_move_row)
print_array(array)
It gives me an error :
pl_array[x][y] = "O"
TypeError: 'str' object does not support item assignment
How can i change the code to make it change the item I show the program to write "X" or "O" in it?
Just like the error says, 'str' object does not support item assignement, that is you cannot do:
ga = "---"
ga[0] = "X"
But you can use lists in your example by changing:
start_arr.append('-' * 3)
to
start_arr.append(["-"] * 3)

Categories

Resources