I wrote this program in order to be able to find the number of A/U and C/G pairs from the users input. When I run it, it keeps saying "Invalid Syntax" while highlighting the first "else:" after the while loop in red. Anyone know what I need to change to fix it?
def main():
first = input("Please enter the RNA sequence for which you wish to find the number of pairs. \nFirst line:")
second = input("Second String:")
a1base = first.count('A')
u1base = first.count('U')
c1base = first.count('C')
g1base = first.count('G')
a2base = second.count('A')
u2base = second.count('U')
c2base = second.count('C')
g2base = second.count('G')
while (a1base >= 1) and (u1base >= 1) or (a2base >= 1) and (u2base >= 1):
abases = (a1base+ a2base)
ubases = (u1base + u2base)
firstset = min(abases, ubases)
print("You have", firstset,"A/U bases.")
else:
print("You have zero A/U bases.")
while (c1base >= 1) and (g1base >= 1) or (c2base >= 1) and (g2base >= 1):
cbases = (c1base + c2base)
gbases = (g1base + g2base)
secondset = min(cbases, gbases)
print("You have", secondset,"C/G bases.")
else:
print("You have zero C/G bases.")
main()
You have an else: that isn't attached to any if, for, while, or try statement, which is illegal.
If you meant for the else to be attached to the while, the solution is simple: Change the indentation to attach it:
while (a1base >= 1) and (u1base >= 1) or (a2base >= 1) and (u2base >= 1):
abases = (a1base+ a2base)
ubases = (u1base + u2base)
firstset = min(abases, ubases)
print("You have", firstset,"A/U bases.")
else:
print("You have zero A/U bases.")
See break and continue Statements, and else Clauses on Loops in the tutorial (and Compound statements in the language reference for full details).
Your else needs to be indented at the same level as your while, which doesn't really make sense in this case because there's no break in your loop, or you need to add an if on some line before it.
I see two obvious things:
Everything after def main(): should be indented;
Else should be at the same level of indentation as while. It is not a child, but a sibling of while.
Others have already explained the error.
Try changing you while loops to this:
abases = (a1base+ a2base)
ubases = (u1base + u2base)
firstset = min(abases, ubases)
print("You have", firstset if firstset else 'zero',"A/U bases.")
cbases = (c1base + c2base)
gbases = (g1base + g2base)
secondset = min(cbases, gbases)
print("You have", secondset if secondset else 'zero',"C/G bases.")
Without any while or else:.
Also the following snippet should do the same thing:
first = input("Please enter the RNA sequence for which you wish to find the number of pairs. \nFirst line:")
second = input("Second String:")
bases = {k: (first + second).count(k) for k in 'AUCG'}
print('You have', min(bases['A'], bases['U']), 'A/U bases.')
print('You have', min(bases['C'], bases['G']), 'C/G bases.')
Related
I am creating an Among Us ripoff (for fun!) and the while True & if/elif/else statements will only return false (not An Impostor) with the inputs. I had created a list for the names and 2 random elements from the list will be chosen as An Impostor. However, whenever I input a name that is The Impostor, it will only return
(player) was not An Impostor.
Here is my code;
import sys, time, random
names = ["player1", "player2", "player3", "player4", "player5", "player6", "player7", "player8", "player9", "player10"]
print("Players: ")
for x in names:
print(x)
print('—————————————————————————')
impostor1 = random.choice(names)
impostor2 = random.choice(names)
crewmates = 8
impostors = 2
tries = 6
while True:
talk = input("Guess who The Impostor(s) are. " + str(crewmates) + " Crewmates are left. " + str(impostors) + " Impostors are left. You have " + str(tries) + " tries left.")
if talk in names:
print(talk + " was voted for.")
time.sleep(0.1)
if talk != impostor1 or talk != impostor2:
notimp = talk + " was not An Impostor. "
names.remove(talk)
for y in notimp:
sys.stdout.write(y)
sys.stdout.flush()
time.sleep(0.05)
crewmates -= 1
tries -= 1
elif talk == impostor1 or talk == impostor2:
wasimp = talk + " was An Impostor. "
names.remove(talk)
for v in wasimp:
sys.stdout.write(v)
sys.stdout.flush()
time.sleep(0.1)
impostors -= 1
else:
print("That player was either ejected or is not a valid player.")
However, whenever I put the Impostor in the input, it says it isn't An Impostor?
I think this line is the source of the problem:
if talk != impostor1 or talk != impostor2:
Let's say impostor1 is player1 and impostor2 is player2 and someone input in player1, according to Python Boolean expression operator or that if statement will evaluate like this:
if player1 != impostor1 evaluated to False because player1 is indeed equals to impostor1.
So far so good, but because the first test is a False, Python simply evaluates and returns the right side operand which may be either True or False. In your case Python will evaluate if talk != impostor2 and return True, thereafter executes the nested block.
I'm building a command line game using python.A main feature of this game is to get the user's input of either 1 or 2 as integer values.Any other character must be rejected.I used try-except & if-else condition to do this like shown below.I want to know whether there is any better method to get this done in one line or some other way without having to indent a whole bunch of code.
if __name__ == '__main__':
# INITIALIZE THE TOTAL STICKS , DEPTH OF THE TREE AND THE STARTINGG PLAYER
i_stickTotal = 11 # TOTAL NO OF STICKS IN THIS GAME
i_depth = 5 # THE DEPTH OF THE GOAL TREEE THE COMPUTER WILL BUILD
i_curPlayer = 1 # THIS WILL BE +1 FOR THE HUMAN AND -1 FOR THE COMPUTER
print("""There are 11 sticks in total.\nYou can choose 1 or 2 sticks in each turn.\n\tGood Luck!!""")
# GAME LOOP
while i_stickTotal > 0:
print("\n{} sticks remain. How many would you pick?".format(i_stickTotal))
try:
i_choice = int(input("\n1 or 2: "))
if i_choice - 1 == 0 or i_choice - 2 == 0:
i_stickTotal -= int(i_choice)
if WinCheck(i_stickTotal, i_curPlayer):
i_curPlayer *= -1
node = Node(i_depth, i_curPlayer, i_stickTotal)
bestChoice = -100
i_bestValue = -i_curPlayer * maxsize
# Determine No of Sticks to Remove
for i in range(len(node.children)):
n_child = node.children[i]
#print("heres what it look like ", n_child.i_depth, "and",i_depth)
i_val = MinMax(n_child, i_depth-1, i_curPlayer)
if abs(i_curPlayer * maxsize - i_val) <= abs(i_curPlayer*maxsize-i_bestValue):
i_bestValue = i_val
bestChoice = i
#print("Best value was changed # ", i_depth, " by " , -i_curPlayer, " branch ", i, " to ", i_bestValue)
bestChoice += 1
print("Computer chooses: " + str(bestChoice) + "\tbased on value: " + str(i_bestValue))
i_stickTotal -= bestChoice
WinCheck(i_stickTotal, i_curPlayer)
i_curPlayer *= -1
else:
print("You can take only a maximum of two sticks.")
except:
print("Invalid input.Only Numeric Values are accepted")
You can create a function to check user input and use below code.
while True:
var = int(input('Enter value (1 or 2) - '))
if var not in range(1, 3):
print('Invalid entry, please try again...')
continue
else:
break
Write a function that loops, calling input, until the value satisfies your constraint. Perhaps call it get_user_input. Then call that in your main function instead of input. For added value, pass a lambda into that function as a predicate to test the user input value - that'll make get_user_input more general.
So, I had 2 scripts, a Vigenere cipher and a Caesar cipher, however, when I decided to merge them into a "mainproject" file by using "import" to import the script after the wanted answer from the user is sent on the Terminal page, when I've done the code and decided to execute the mainproject, I've got the question whether to choose to use Vigenere or Caesar, once I typed caesar (1) it played the first 2-4 lines and stopped the code once I've encountered the "def" line on both of scripts, if thats the problem, I can't use imports with "def", how can I merge them both into one file that asks which script I would like to use?
Caesar:
import time
import sys
print("Welcome to Caesar Cipher")
time.sleep(3)
print("Choose the corresponding number to Encrypt or Decrypt in Caesar Cipher")
def encryption():
print("Encryption")
print("You have chose ENCRYPTION")
msg = input("Enter message: ")
key = int(input("Enter key(0-25): "))
encrypted_text = ""
for i in range(len(msg)):
if ord(msg[i]) == 32:
encrypted_text += chr(ord(msg[i]))
elif ord(msg[i]) + key > 122:
temp = (ord(msg[i]) + key) - 122
encrypted_text += chr(96+temp)
elif (ord(msg[i]) + key > 90) and (ord(msg[i]) <= 96):
temp = (ord(msg[i]) + key) - 90
encrypted_text += chr(64+temp)
else:
encrypted_text += chr(ord(msg[i]) + key)
print("Your Encrypted Message: " + encrypted_text)
def decryption():
print("Decryption")
print("You have chose DECRYPTION")
encrp_msg = input("Enter encrypted Text: ")
decrp_key = int(input("Enter key(0-25): "))
decrypted_text = ""
for i in range(len(encrp_msg)):
if ord(encrp_msg[i]) == 32:
decrypted_text += chr(ord(encrp_msg[i]))
elif ((ord(encrp_msg[i]) - decrp_key) < 97) and ((ord(encrp_msg[i]) - decrp_key) > 90):
temp = (ord(encrp_msg[i]) - decrp_key) + 26
decrypted_text += chr(temp)
elif (ord(encrp_msg[i]) - decrp_key) < 65:
temp = (ord(encrp_msg[i]) - decrp_key) + 26
decrypted_text += chr(temp)
else:
decrypted_text += chr(ord(encrp_msg[i]) - decrp_key)
print("Text has been Decrypted: " + decrypted_text)
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
encryption()
elif choice == 2:
decryption()
else:
print("Wrong Choice")
Vigenere:
import time
print("Welcome to Vigenere Cipher")
time.sleep(2)
print("Choose the corresponding number to Encrypt or Decrypt in Vigenere Cipher")
time.sleep(2.5)
def msg_and_key():
msg = input("Enter message: ").upper()
key = input("Enter key: ").upper()
key_map = ""
j=0
for i in range(len(msg)):
if ord(msg[i]) == 32:
key_map += " "
else:
if j < len(key):
key_map += key[j]
j += 1
else:
j = 0
key_map += key[j]
j += 1
return msg, key_map
def create_vigenere_table():
table = []
for i in range(26):
table.append([])
for row in range(26):
for column in range(26):
if (row + 65) + column > 90:
table[row].append(chr((row+65) + column - 26))
else:
table[row].append(chr((row+65)+column))
return table
def cipher_encryption(message, mapped_key):
table = create_vigenere_table()
encrypted_text = ""
for i in range(len(message)):
if message[i] == chr(32):
encrypted_text += " "
else:
row = ord(message[i])-65
column = ord(mapped_key[i]) - 65
encrypted_text += table[row][column]
print("Encrypted Message: {}".format(encrypted_text))
def itr_count(mapped_key, message):
counter = 0
result = ""
for i in range(26):
if mapped_key + i > 90:
result += chr(mapped_key+(i-26))
else:
result += chr(mapped_key+i)
for i in range(len(result)):
if result[i] == chr(message):
break
else:
counter += 1
return counter
def cipher_decryption(message, mapped_key):
table = create_vigenere_table()
decrypted_text = ""
for i in range(len(message)):
if message[i] == chr(32):
decrypted_text += " "
else:
decrypted_text += chr(65 + itr_count(ord(mapped_key[i]), ord(message[i])))
print("Decrypted Message: {}".format(decrypted_text))
print("Key and Message can only be alphabetic")
time.sleep(1.5)
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
print("You have chose ENCRYPTION")
message, mapped_key = msg_and_key()
cipher_encryption(message, mapped_key)
elif choice == 2:
print("You have chose DECRYPTION")
message, mapped_key = msg_and_key()
cipher_decryption(message, mapped_key)
else:
print("Wrong choice")
Any help would be appreciated!
def only defines a function. To actually execute it you need to call it.
It seems the following part should be outside of decryption function body i.e. indented to the left. It:
call be executed directly on the module level
can be a separate function e.g. main that you can call
As main:
def main():
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
encryption()
elif choice == 2:
decryption()
else:
print("Wrong Choice")
And now you can call the main function:
main()
Welcome to Stackoverflow. This answer ended up more as general advice than a specific point solution to your problem, but I hope it's helpful.
One obvious remark is that it would be nice not to have to import the code for the cypher you don't intend to use.
Imports are executable statements, so this is quite practical.
Your code is far from optimally organised. Much of the code on the two files is the same or very similar. This is not unusual for new programmers, as it takes a while to learn how to break problems down and extract the common elements. The real problem is that while it defines lots of functions, none of them actually get called (unless there's more code you haven't included).
I would recommend that you modify your code so that there's a top-level program that collects the key and data and performs the required operations, along with your two
encryption/decryption modules. The encryption and decryption routines shouldn't do any input or output at all, just deal with the data.
Let's assume you have a variable mtype that holds the type of encryption you want to use. The top-level logic could look something like this:
if mtype == "caesar":
from caesar import encrypt, decrypt
elif mtype == "vigniere":
from vigniere import encrypt, decrypt
else:
sys.exit("Unrecognised message type")
If this code succeeds you would then have an encrypt and a decrypt function from the correct module. This means that they have to have the same interface, since your logic must now be written to accommodate either.
The remainder of your logic would look something like this (untested):
operation = input("E(ncrypt) or D(ecrypt)? ")
if operation.upper().startswith("E"):
function = encrypt
elif operation.upper().startswith("D"):
function = decrypt
else:
sys.exit("Unknown operation")
message = input(...)
key = input(...)
output = function(message, key)
This will hopefully make your code clearer by separating out the I/O responsibility
from the encryption and decryption tasks.
I am trying to increase the correct answer count by 1 every time the users answer is correct. However, when parsed into the display_result() function, the correct function displays "0 correct"
I haven't been able to get this working no matter how I try to wiggle around it, so any help is really appreciated.
code removed for academic integrity
If the user has answered 1 of 3 questions correctly, I expect the answer to be "You have answer 1 questions out of 3 correctly."
Currently, it would display you have answered 0 questions out of 3 correctly"
In menu_option() you never modify count, so it stays at 0. Two simple fixes. Change to:
count = check_solution(user_solution, real_solution, count)
return count
Or just
return check_solution(user_solution, real_solution, count)
One other thing I noticed: in get_user_input() you need to return the result of the recursive calls:
else:
print("Invalid input, please try again")
return get_user_input()
There are a number of problems:
you are doing correct = menu_option(option, correct) when instead you should be accumulating the correct scores like correct +=
in the menu_option you are never assigning to count, I presume it should be count = check_solution(...)
you shouldn't do return option for index == 5 because that will add to the correct.
Finally the code run as I expected(python3.6+ is required):
#!/usr/bin/env python3
import random
def get_user_input():
while True:
try:
index = int(input("Enter your choice: "))
if 0 < index < 6:
return index
except ValueError:
print("Invalid input, should be Integer.\n")
else:
print("Invalid input, please try again")
def get_user_solution(problem):
while True:
print("Enter your answer")
user_solution = input(f"{problem} = ")
try:
return float(user_solution)
except ValueError:
print("Invalid input, should be float\n")
def check_solution(user_solution, solution, count):
if user_solution == solution:
print("Correct.")
return count + 1
else:
print("Incorrect.")
return count
def menu_option(index, count):
first_num = random.randrange(1, 21)
second_num = random.randrange(1, 21)
if index == 1:
problem = f"{first_num} + {second_num}"
real_solution = first_num + second_num
print(real_solution)
user_solution = get_user_solution(problem)
return check_solution(user_solution, real_solution, count)
if index == 2:
problem = f"{first_num} - {second_num}"
real_solution = first_num - second_num
print(real_solution)
user_solution = get_user_solution(problem)
return check_solution(user_solution, real_solution, count)
if index == 3:
# blah blah blah, repeated code but removed for neatness
pass
if index == 5:
option = 5
return option
def display_result(total, correct):
if total == 0:
print("You answered 0 questions with 0 correct")
print("Your score is 0.0%")
else:
percentage = round(correct / total * 100, 2)
print(
f'You answered {total} questions with {correct} correct.\n'
f'Your score is {percentage}%'
)
def display_intro():
pass
def display_menu():
pass
def display_separator():
print('-'*20)
def main():
display_intro()
display_menu()
display_separator()
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exit the quiz.")
display_separator()
display_result(total, correct)
if __name__ == "__main__":
main()
I was working on a small project, and I've run across a little error in my programming. It's a basic battleship game, and so far I have two "ships" set, and I have the game to end when both on either my side or the enemy side is hit.
def enemy_board():
global enemy_grid
enemy_grid = []
for i in range (0,10):
enemy_grid.append(["="] * 10)
def random_row_one(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_col_one(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_row_two(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_col_two(enemy_grid):
return randint(0, len(enemy_grid) - 1)
global x_one
x_one = random_row_one(enemy_grid)
global y_one
y_one = random_col_one(enemy_grid)
global x_two
x_two = random_row_two(enemy_grid)
global y_two
y_two = random_col_two(enemy_grid)
print(x_one)
print(y_one)
print(x_two)
print(y_two)
So that's the basis of my list, but later on in the code is where it's giving me a little trouble.
elif enemy_grid.count("H") == 2:
print("\nYou got them all!\n")
break
Update
Sorry I was a little unclear about what I meant.
def my_board():
global my_grid
my_grid = []
for i in range (0,10):
my_grid.append(["O"] * 10)
def my_row_one(my_grid):
int(input("Where do you wish to position your first ship on the x-axis? "))
def my_col_one(my_grid):
int(input("Where do you wish to position your first ship on the y-axis? "))
global x_mio
x_mio = my_row_one(my_grid)
global y_mio
y_mio = my_col_one(my_grid)
def my_row_two(my_grid):
int(input("\nWhere do you wish to position your other ship on the x-axis? "))
def my_col_two(my_grid):
int(input("Where do you wish to position your other ship on the y-axis? "))
global x_mit
x_mit = my_row_two(my_grid)
global y_mit
y_mit = my_col_two(my_grid)
def enemy_board():
global enemy_grid
enemy_grid = []
for i in range (0,10):
enemy_grid.append(["="] * 10)
def random_row_one(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_col_one(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_row_two(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_col_two(enemy_grid):
return randint(0, len(enemy_grid) - 1)
global x_one
x_one = random_row_one(enemy_grid)
global y_one
y_one = random_col_one(enemy_grid)
global x_two
x_two = random_row_two(enemy_grid)
global y_two
y_two = random_col_two(enemy_grid)
print(x_one)
print(y_one)
print(x_two)
print(y_two)
title()
my_board()
enemy_board()
m = 20
guesses = m
while guesses > 0:
def printmi_board(my_grid):
for row in my_grid:
print(" ".join(row))
def printyu_board(enemy_grid):
for row in enemy_grid:
print (" ".join(row))
print(printmi_board(my_grid))
print(printyu_board(enemy_grid))
try:
guess_x = int(input("Take aim at the x-xalue: "))
except ValueError:
print("\nI SAID TAKE AIM!\n")
guess_x = int(input("Take aim at the x-xalue: "))
try:
guess_y = int(input("Take aim at the y-value: "))
except ValueError:
print("\nDo you have wax in your ears?? AIM!\n")
guess_y = int(input("Take aim at the y-value: "))
comp_x = randint(0, len(my_grid) - 1)
comp_y = randint(0, len(my_grid) - 1)
if x_one == guess_x and y_one == guess_y:
print("\nYou hit one! \n")
enemy_grid[guess_x - 1][guess_y - 1] = "H"
continue
elif x_two == guess_x and y_two == guess_y:
enemy_grid[guess_x - 1][guess_y - 1] = "H"
print("\nYou hit one! \n")
continue
elif enemy_grid[guess_x - 1][guess_y - 1] == "O":
print("\nYou've tried there before! Here's another round.\n")
print("You have " + str(guesses) + " rounds left, cadet.\n\n")
continue
elif enemy_grid.count("H") == 2:
print("\nYou got them all!\n")
break
else:
if guess_x not in range(10) or guess_y not in range(10):
print("\nThat's not even in the OCEAN!! Take another free round then.\n")
print("You have " + str(guesses) + " rounds left, cadet.\n\n")
continue
elif enemy_grid[guess_x][guess_y] == "O":
print("\nYou've tried there before! Here's another round.\n")
print("You have " + str(guesses) + " rounds left, cadet.\n\n")
continue
else:
print("\nYou missed, soldier!\n")
guesses = guesses - 1
print("You have " + str(guesses) + " rounds left, cadet.\n\n")
enemy_grid[guess_x - 1][guess_y - 1] = "O"
if comp_x == x_mio and comp_y == y_mio:
my_grid[comp_x - 1][comp_y - 1] = "H"
print("\nThe enemy hit you! \n")
continue
elif comp_x == x_mit and comp_y == y_mit:
my_grid[comp_x - 1][comp_y - 1] = "H"
print("\nThe enemy hit you! \n")
continue
elif my_grid.count("H") == 2:
print("We have to retreat! They've sunken all of your ships...")
break
else:
my_grid[comp_x - 1][comp_y - 1] = "="
continue
I'm using python 3 if that makes any difference. So it's that if the player hits the correct spot on the grid, then it'll show as "H" and not as "=" or "O". So I was just wondering about if I could count those "H"'s to use to end the IF loop.
You haven't really explained the problem, and so much of the code is missing that it's very hard to tell you what's wrong, I'm going to guess at it though.
My guess is that you create an '=' grid to represent a player's board, and then if their ship is 'hit' you replace the '=' in that position with an 'H'.
The structure you create (enemy_grid) seems to look something like:
[[====]
[====]
[====]
[....]]
in which case your test, enemy_grid.count("H") doesn't make sense as enemy_grid is a list that contains other lists (so the count of Hs will always be 0 - they're deeper down in the 2nd layer of lists).
You probably want a test more along the lines of:
[cell for row in enemy_grid for cell in row].count('H')