How to convert the input into lowercase [duplicate] - python

This question already has answers here:
How do I lowercase a string in Python?
(8 answers)
Closed 3 years ago.
I would like to know, what can I do so that even if the answers are uppercase it still marks the points? I am a new python user...
colleges = ["MIT", "UAB", "Harvard", "UA", "Standford"]
votes = [0, 0, 0, 0, 0]
Q1 = input("What is important in your future?\na)Invent something important\nb)Helping other people\nc)Know everything\nd)A job that I love\ne)Make the world better\n")
if (Q1 == "a"):
votes[0] = votes[0]+1
elif (Q1 == "b"):
votes[1] = votes[1]+1
elif (Q1 == "c"):
votes[2] = votes[2]+1
elif (Q1 == "d"):
votes[3] = votes[3]+1
elif (Q1 == "e"):
votes[4] == votes[4]+1

Use Q1 = input("What is...").lower()

Related

Else is never reached in python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I only have to do this:
Take a string entered by the user and print the game grid as in the previous stage.
Analyze the game state and print the result.
Like this:
1. Enter cells: XXXOO__O_ ---------
| X X X |
| O O _ |
| _ O _ | ---------
X wins
The problem is that my program never reaches the elif statements and I don´t know why.
n = input()
number_grid = []
Winner = ""
print("---------")
Cont = {"X": 0, "O": 0, "_": 0} # This will count to check for impossible games
for i in range(0, len(n), 3):
print("|", n[i], n[i+1], n[i+2], "|")
number_grid.append([n[i], n[i+1], n[i+2]])
Cont[n[i]] = Cont[n[i]] + 1
Cont[n[i + 1]] = Cont[n[i + 1]] + 1
Cont[n[i + 2]] = Cont[n[i + 2]] + 1
print("---------")
Impossible = False
if 2 <= Cont["X"] - Cont["O"] or Cont["X"] - Cont["O"] <= -2:
Impossible = True
print("Impossible")
exit()
if Winner == "" and Impossible is False:
for rows in range(0, 3): # Check winner in rows
if number_grid[rows][0] == number_grid[rows][1] == number_grid[rows][2] != "_":
Winner = number_grid[rows][0]
print(Winner, "wins")
for columns in range(0, 3): # Check winner in columns
if number_grid[0][columns] == number_grid[1][columns] == number_grid[2][columns] != "_":
Winner = number_grid[0][columns]
print(Winner, "wins")
if number_grid[0][0] == number_grid[1][1] == number_grid[2][2] != "_": # Check winner in first diagonal
Winner = number_grid[0][0]
print(Winner, "wins")
if number_grid[0][2] == number_grid[1][1] == number_grid[2][0] != "_": # Check winner in second diagonal
Winner = number_grid[0][2]
print(Winner, "wins")
elif Cont["_"] != 0:
print("Game not finished")
elif Cont["X"] + Cont["O"] == 9:
print("Draw")
Reducing your code down...
Winner = ""
Impossible = False
if Winner == "" and Impossible is False:
# Stuff
elif Cont["_"] != 0:
print("Game not finished")
elif Cont["X"] + Cont["O"] == 9:
print("Draw")
In your current code, it's not possible for Winner != "" or Impossible != True. So you will never enter the elif statement.

why my dictionary is not get updated in python [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
Here in my code, I am trying to update values in dic with user input using the play function. But the values(\t) is not getting updated by inputted value. Why? how can I fix this?
dic = {7: "\t",
8:"\t",
9: "\t",
4: "\t",
5: "\t",
6: "\t",
1:"\t",
2: "\t",
3: "\t"}
player1 = "null"
player2 = "null"
#player 1 is true and player 2 is false
playerOnesTurn = True
def printBoard():
print(dic[7]+ "|" +dic[8]+ "|"+ dic[9])
print(dic[4]+ "|"+dic[5]+ "|"+ dic[6])
print(dic[1]+ "|"+dic[2]+ "|"+ dic[3])
def play():
if(playerOnesTurn):
print(player1 + "'s turn")
print("Enter the position: ")
pos = input() # it is an int value
dic[pos] = "X"
play()
printBoard()
pos = input() would be a str, not int. Try changing it to pos = int(input())

Changing the index of a For loop in Python (outside if statement) [duplicate]

This question already has answers here:
How do I use a C-style for loop in Python?
(8 answers)
Closed 3 years ago.
I am trying to change the index of a for loop depending if a user wants to go to the previous image (index = index - 1) and if he wants to go the next image (index = index + 1) however, the index doesnt change in the outerloop (outside the if statements).
flag = False
while flag == False:
for i in range(len(all_image)):
image = all_image[i]
print(i)
userchoice = easygui.buttonbox(msg, image = image, choices=choices)
if userchoice == 'Next':
i = i+1
elif userchoice == 'Previous':
i = i-1
elif userchoice == 'cancel':
print('test')
flag = True
break
Thanks in advance.
Not sure why the for loop is there, I'd be tempted to structure it more like so:
flag = False
idx = 0 #idx is where we are in the image list, and it gets modified by use choices in the while loop.
while flag == False:
image = all_image[idx]
print(idx)
userchoice = easygui.buttonbox(msg, image = image, choices=choices)
if userchoice == 'Next':
idx += 1
elif userchoice == 'Previous':
idx -= 1
elif userchoice == 'cancel':
print('test')
flag = True
break

Mastermind Python coding

Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)

How to exit a script in python [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 6 years ago.
how can I shut down script in python?
sys.exit()
does not work.. so where the problem is?
Edit: changed indentation as in my file
import sys
def sifra():
retezec = input("Zadejte slovo: ")
print("Zadali jste slovo: ",retezec)
zprava = ""
posun = int(input("Zadejte číslo o kolik se má šifra posouvat: "))
for znak in retezec:
i = ord(znak)
i = i + posun
if (i > ord("z")):
i = i - 26
znak = chr(i)
zprava = zprava + znak
print("Zašifrovaná zpráva: ", zprava)
znovu = input("Znovu? A/N ")
if(znovu == "A" or "a"):
sifra()
elif(znovu == "N" or "n"):
sys.exit()
else:
pass
sifra()
znovu == "N" or "n" is not what you want. You need to compare znovu to both these values:
elif (znovu == 'N') or (znovu == 'n'):
sys.exit()
Another alternative would be the one suggested in the comments or simply:
elif znovu in 'Nn': sys.exit()
Assuming that nobody inputs 'Nn' as an answer, but even if they (accidentally) do so, this can still be considered as 'No'.

Categories

Resources