Why am i getting a syntax error on line 28? It seems like it should be just a normal line of code that prints the statement, but I keep getting a normal syntax error for it.
print('Welcome to the encryptor program.')
message = input('Enter the message you would like to encrypt.\n')
message = message.lower()
key = input('Enter the key you would like to use.\n')
def encrypt(k, m):
count = 0
keyCount = 0
fullCount = 0
newM = ''
while fullCount < len(m):
if (count) >= len(str(key)):
keyCount = 0
num = ord(m[count]) - 97
if m[count] != ' ':
add = int((str(k))[keyCount])
newNum = (num + add) % 26 + 97
new = chr(newNum)
newM += new
else:
newM += ' '
count += 1
fullCount += 1
keyCount += 1
print(newM)
encrypt(key, message)
def new_key(k):
newKey = int('1' + '0' * (((len(str(k))))-1) - key
The line after this
print('The new key to decrypt the message is', newKey)
new_key(key)
Related
import random
letters=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
numbers=['1','2','3','4','5','6','7','8','9','0']
symbols=['!','#','#','$','%','^','&','*','(',')','-','+','=','?',':','~']
print("welcome to the passward genrator!")
no_of_letters=int(input(f"how many letters would you like in your password: \n"))
no_of_symbols=int(input(f"how many symbols would you like: \n"))
no_of_numbers=int(input(f"how many numbers would you like :\n"))
if (no_of_numbers+no_of_symbols+no_of_numbers)<=12:
print("your passward must be 12 characater")
else:
i = 0
letters_char = ""
while i < no_of_letters:
letters_index = random.randint(0, len(letters) - 1)
i += 1
a = letters[letters_index]
letters_char += a
p = (letters_char)
s = (p[0].upper()) + p[1:]
j = 0
number_char = ""
while j < no_of_numbers:
number_index = random.randint(0, len(numbers) - 1)
j += 1
b = numbers[number_index]
number_char += b
q = (number_char)
k = 0
symbol_char = ""
while k < no_of_symbols:
symbol_index = random.randint(0, len(symbols))
k += 1
c = symbols[symbol_index]
symbol_char += c
r = (symbol_char)
print(f"Your password is: {s+q+r}")
genrally it take error with when i give input 7(no of letters),8(no of symbol),9[enter image description here](https://i.stack.imgur.com/XB8B0.png)(no of numbers)
sometime it give true output in same input
I've been studying in Hackerrank. Question wants me to sort an given array. I know there is some library functions for those but since i don't know any yet, i've tried to write it manually.
Sample input:
15 43 3 2 150
Sample output:
150 2 3 43 15
I've wanted to write a code starts reading the string from the right and stops when it finds a blank. Than adds the string before the blank to the final result. Then keeps going untill it reaches to the [0].
Here's my code:
sortedResult = ""
tempNumbers = ""
tempCount = 0
numbers = input()
for counter in range(len(numbers) - 1, -1, -1):
if counter != 0:
if numbers[counter] in range(-1, 11):
tempCount += 1
continue
else:
for counter2 in range(counter, counter + tempCount + 1):
tempNumbers += numbers[counter2]
sortedResult += tempNumbers
tempNumbers = ""
tempCount = 0
else:
for counter3 in range(counter, counter + tempCount + 1):
sortedResult += numbers[counter3]
print(sortedResult)
You appear to be sorting a string, not a list of numbers. To fix this, change the input line to numbers = [int(x) for x in input().split(" ")]. In addition, you should change tempNumbers and sortedResult to lists and use .append() instead of +=.
Final code:
sortedResult = []
tempNumbers = []
tempCount = 0
numbers = [int(c) for c in input().split(" ")]
for counter in range(len(numbers) - 1, -1, -1):
if counter != 0:
if numbers[counter] in range(-1, 11):
tempCount += 1
continue
else:
for counter2 in range(counter, counter + tempCount + 1):
tempNumbers.append(numbers[counter2])
sortedResult += tempNumbers
tempNumbers = []
tempCount = 0
else:
for counter3 in range(counter, counter + tempCount + 1):
sortedResult.append(numbers[counter3])
print(sortedResult)
Here's my final code. It is working and it works as the way i intented it to.
sortedResult = ""
tempNumbers = ""
tempCount = 0
numbers = input()
firstTenNumbers= "0123456789"
for counter in range(len(numbers) - 1, -1, -1):
if counter != 0:
if numbers[counter] in firstTenNumbers:
tempCount += 1
continue
else:
sortedResult += numbers[slice(counter + 1, tempCount + counter + 1)] + " "
tempCount = 0
else:
sortedResult += numbers[slice(tempCount + 1)]
tempCount = 0
print(sortedResult)
Currently I'm writing a code where I want to ask motor values from motor controller using raspberry pi. However my code is throwing InvalidSyntax Error in else and elif statements. I've already read about if and elif statements in python, but I can't figure out mistake by myself. The code is below:
def motor_values():
while 1:
command_1 = '?A '+str(1)+' \r' #Asking first motor current
command_2 = '?A '+str(2)+' \r' #Asking second motor current
counter = 0
#First motor current
if counter = 0:
ser.write(command_1.encode()) #string to bytes
data_1 = ser.readline().decode().strip() #bytes to string
#Checking if data is received and extracting current value
if 'A=' in data_1:
value_1 = int(data_1.split('=')[1])
print("Motor Current(Channel 1): " + str((value_1) + " Ampers")
counter += 1
else:
print("Message is not received")
#Second motor current
elif counter == 1:
ser.write(command_2.encode()) #string to bytes
data_2 = ser.readline().decode().strip() #bytes to string
if 'A=' in data_2:
value_2 = int(data_2.split('=')[1])
print("Motor Current(Channel 2): " + str((value_2) + " Ampers")
counter += 1
else:
print("Message is not received")
else:
counter = 0
A few syntax errors here:
use == in the if clause condition
#First motor current
if counter == 0: #
remove one of the two ( in str((value_2)
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")
print("Motor Current(Channel 2): " + str(value_2) + " Ampers")
you missed closing brace in print function
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")
How do I complete this recursive function at output_string += ? Output should be: 5! = 5 * 4 * 3 * 2 * 1 = 120
def print_factorial(fact_counter, fact_value):
output_string = ''
if fact_counter == 0: # Base case: 0! = 1
output_string += '1'
elif fact_counter == 1: # Base case: print 1 and result
output_string += str(fact_counter) + ' = ' + str(fact_value)
else: # Recursive case
output_string += str(fact_counter) + ' * '
next_counter = fact_counter - 1
next_value = next_counter * fact_value
output_string +=
return output_string
user_val = 5
print('%d! = ' % user_val, end="")
print(print_factorial(user_val, user_val))
def factorial_str(fact_counter, fact_value):
output_string = ''
if fact_counter == 0: # Base case: 0! = 1
output_string += '1'
elif fact_counter == 1: # Base case: print 1 and result
output_string += str(fact_counter) + ' = ' + str(fact_value)
else: # Recursive case
output_string += str(fact_counter) + ' * '
next_counter = fact_counter - 1
next_value = next_counter * fact_value
output_string += factorial_str(next_counter, next_value)
return output_string
user_val = int(input())
print('{}! = '.format(user_val), end="")
print(factorial_str(user_val, user_val))
Using the above answer I was able to work out the code. I have posted the answer that passed the case test for me.
def print_factorial(fact_counter, fact_value):
output_string = ''
if fact_counter == 0: # Base case: 0! = 1 #This line will never execute, no recursive call will ever be made with fact_counter = 0 and there shouldn't be anyways, so its harmless.
output_string += '1'
elif fact_counter == 1: # Base case: print 1 and result
output_string += str(fact_counter) + ' = ' + str(fact_value)
else: # Recursive case
output_string += str(fact_counter) + ' * '
next_counter = fact_counter - 1
next_value = next_counter * fact_value
output_string += print_factorial(next_counter, next_value)
return output_string
user_val = 5
print('%d! = ' % user_val, end="")
print(print_factorial(user_val, user_val))
You needed to compute the next number in the factorial then add it with "*" too. So a recursive call should be made at the concatenation statement.
Umm, if fact_counter == 0, will NEVER execute and I've written a comment to point this out inside the code.
I am having a problem with my code trying to do an advanced caesar cipher shift. I changed a certain letter to another, and then added a string to certain parts of a file before encoding, but am having problems doing the shifting now. This is my code:
import string
import sys
count = 1
cont_cipher = "Y"
#User inputs text
while cont_cipher == "Y":
if count == 1:
file = str(input("Enter input file:" ""))
k = str(input("Enter shift amount: "))
purpose = str(input("Encode (E) or Decode (D) ?: "))
#Steps to encode the message, replace words/letter then shift
if purpose == "E":
my_file = open(file, "r")
file_contents = my_file.read()
#change all "e"s to "zw"s
for letter in file_contents:
if letter == "e":
file_contents = file_contents.replace(letter, "zw")
#add "hokie" to beginning, middle, and end of each line
lines = file_contents.split('\n')
def middle_message(lines, position, word_to_insert):
lines = lines[:position] + word_to_insert + lines[position:]
return lines
new_lines = ["hokie" + middle_message(lines[x], len(lines[x])//2, "hokie") + "hokie" for x in range(len(lines))]
#math to do the actual encryption
def caesar(word, shifts):
word_list = list(new_lines)
result = []
s = 0
for c in word_list:
next_ord = ord(c) + s + 2
if next_ord > 122:
next_ord = 97
result.append(chr(next_ord))
s = (s + 1) % shifts
return "".join(result)
if __name__ == "__main__":
print(caesar(my_file, 5))
#close file and add to count
my_file.close()
count = count + 1
The error I am getting is:
TypeError: ord() expected a character, but string of length 58 found
I know that I need to split it into individual characters, but am not sure how to do this. I need to use the updated message and not the original file in this step...