I am trying to do some coursework but I have hit a wall. I am trying to write a function that takes a letter and a digit as the inputs, and returns the letter shifted key positions to the right in the alphabet.
This is what I have so far:
def code_char(c,key):
letter=input("Enter letter to be moved")
shift=int(input("Enter degree of shift"))
letter=ord(letter)
if letter>=65 and letter <=90:
letter=letter+shift
while letter>90:
letter=letter-26
elif letter>=97 and letter <=122:
letter=letter+shift
while letter>122:
letter=letter-26
letter=chr(letter)
print(letter)
code_char("",0)
The problem is the letter=ord(letter) as I keep getting TypeError: ord() expected string of length 1, but list found. I have tried different variations.
I need to convert the input 'letter' into ASCII.
As suggested by Willem in the OP comments, input() is giving you a str containing the letter and the new-line char \n, use .strip() to solve it if you are using an old Python version:
def code_char():
letter = ord(input("Enter letter to be moved").strip())
shift = int(input("Enter degree of shift"))
if (letter >= 65) and (letter <= 90):
letter += shift
while (letter > 90):
letter -= 26
elif (letter >= 97) and (letter <= 122):
letter += shift
while letter > 122:
letter -= 26
print(chr(letter))
code_char()
New Python versions (e.g. 3.6.0) should not need the .strip() part, being your code after the formatting edit I did working perfectly:
def code_char():
letter = ord(input("Enter letter to be moved"))
shift = int(input("Enter degree of shift"))
if (letter >= 65) and (letter <= 90):
letter += shift
while (letter > 90):
letter -= 26
elif (letter >= 97) and (letter <= 122):
letter += shift
while letter > 122:
letter -= 26
print(chr(letter))
code_char()
Related
Write a function
shiftLetter(letter, n)
whose parameter, letter should be a single character. If the character is between "A" and "Z", the function returns an upper case character 𝑛
n
positions further along, and "wrapping" if the + 𝑛
n
mapping goes past "Z". Likewise, it should map the lower case characters between "a" and "z". If the parameter letter is anything else, or not of length 1, the function should return letter.
Hint: review functions ord() and chr() from the section, as well as the modulus operator %.
Down below is what I worked so far. It should return to A after alphabet is over, but it's not working properly from alphabet x. I guess..? I should subtract 90(Z) - 65(A) in ASCII table for x,y,z but confused about that.
def shiftLetter(letter,n):
if letter >= 'A' and letter <= 'Z':
return chr(ord(letter) + n )
elif letter >= 'a' and letter <= 'z':
return chr(ord(letter) + n )
print(shiftLetter('w',3))
You can use the mod operator to wrap the alphabet:
def shiftLetter(letter,n):
if letter >= 'A' and letter <= 'Z':
return chr((ord(letter) - ord('A') + n) % 26 + ord('A') )
elif letter >= 'a' and letter <= 'z':
return chr((ord(letter) - ord('a') + n) % 26 + ord('a') )
print(shiftLetter('w',3)) # z
print(shiftLetter('E',3)) # H
print(shiftLetter('Y',3)) # B
print(shiftLetter('f',26)) # f
print(shiftLetter('q',300)) # e
Output
z
H
B
f
e
So i was making a program for hangman and this is it so far,
word = input("Enter a word: ").upper()
blanks = (len(word)*"_")
print(blanks)
chances = 5
while blanks.count("_") > 0:
letter = input("Enter a letter: ").upper()
if len(letter) > 1:
print("Please enter one letter only")
if letter in list(word):
blanks = blanks[:word.index(letter)] + letter + blanks[word.index(letter)+1:]
print(blanks)
continue
else:
chances -= 1
if chances > 0:
print("That letter isn't in the word, you have", chances, "chance(s) left")
if chances == 0:
print("You lost. The word was", word.lower())
exit()
print("You win! The word was", word.lower())
I was just trying the code out so I would give the word to guess myself, but if I ever gave a word with a letter repeated , like "doggo".
If i gave the letter as "o", it would give out "_ O _ _ _ " instead of " _ O _ _ O" even if i guess "o" again.
Is there anyway I can fix this?
This worked for me:
word = input("Enter a word: ").upper()
blanks = (len(word) * "_")
print(blanks)
chances = 5
while blanks.count("_") > 0:
letter = input("Enter a letter: ").upper()
if len(letter) > 1:
print("Please enter one letter only")
if letter in list(word):
for count, character in enumerate(word):
if letter == character:
blanks = blanks[:count] + letter + blanks[count + 1:]
print(blanks)
else:
chances -= 1
if chances > 0:
print("That letter isn't in the word, you have",
chances, "chance(s) left")
if chances == 0:
print("You lost. The word was", word.lower())
exit()
print("You win! The word was", word.lower())
The difference is that instead of making one replacement we iterate over the word to find all the coincidences and make all the necessary replacements of the same letter.
One solution is to use zip and join in a list compression. zip combines two strings pairwise. The list comprehension steps through the pairs of letters from blanks and word and compares them to the letter. join combines the result - a list of letters - back into a string.
word = "hello"
letter = 'o'
blanks = ''.join([(l if l == letter else b) for b, l in zip(blanks, word)])
#'__ll_'
You can use bytearray and memoryview or list:
# bytearray and memoryview
blank = '_' * 5
print(blank)
fill = 'abcde'
ctr = 0
ba = bytearray(blank, 'utf-8')
mv = memoryview(ba)
while ba.count(b'_') > 0:
mv[ctr] = ord(fill[ctr])
ctr += 1
blank = ba.decode()
print(blank)
Output:
_____
abcde
Second approach, list:
blank = '_____'
print(blank)
blank_list = list(blank)
fill = 'abcde'
while blank_list.count('_') > 0:
blank_list[ctr] = fill[ctr]
ctr += 1
blank = ''.join(blank_list)
print(blank)
Output:
_____
abcde
I'm trying to write a program that determines if a character is uppercase, lowercase, digit, or non-alphanumeric without string methods like isupper, islower, isdigit. The program is that everything I enter, it's telling me that its a lower case letter. Can someone help me out?
character = input("Enter a character: ")
lowerLetters = "abcdefghijklmnopqrstuvwxyz"
upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
lowerCount = 0
upperCount = 0
digitCount = 0
nonAlphaCount = 0
for ch in character:
for ch in lowerLetters:
lowerCount += 1
for ch in upperLetters:
upperCount += 1
for ch in digits:
digitCount += 1
else:
nonAlphaCount += 1
if lowerCount > 0:
print(character, "is a lower case letter.")
elif upperCount > 0:
print(character, "is an upper case letter.")
elif digitCount > 0:
print(character, "is a digit.")
elif nonAlphaCount > 0:
print(character, "is a non-alphanumeric character.")
You can use ascii value
Numbers 0-9 ASCII 48 to 57
Lowercase letters a-z ASCII 97 to 122
Uppercase letters A-Z ASCII 65-90
use ord function. like this:
>>ord('a')
97
So, to check if a is a lowercase letter or not, do:
if 97<=ord('a')<=122:
print "lowercase character"
Your code is good (though not the best one for your purpose even without using the methods you mentioned) but you have a couple of typos :) This is what you have:
for ch in character:
for ch in lowerLetters:
lowerCount += 1
for ch in upperLetters:
upperCount += 1
for ch in digits:
digitCount += 1
else:
nonAlphaCount += 1
And this is want you wanted to type:
for ch in character:
if ch in lowerLetters:
lowerCount += 1
elif ch in upperLetters:
upperCount += 1
elif ch in digits:
digitCount += 1
else:
nonAlphaCount += 1
The problem is with following part of your code :
for ch in character:
for ch in lowerLetters:
lowerCount += 1
for ch in upperLetters:
upperCount += 1
for ch in digits:
digitCount += 1
else:
nonAlphaCount += 1
You increase the variables without any condition you need to use all function for this job :
character = input("Enter a character: ")
lowerLetters = "abcdefghijklmnopqrstuvwxyz"
upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
if all(ch in character ckafor ch in lowerLetters):
print(character, "is a lower case letter.")
elif all(ch in character for ch in upperLetters):
print(character, "is an upper case letter.")
elif all(ch in characterfor ch in digits):
print(character, "is a digit.")
else:
print(character, "is a non-alphanumeric character.")
Now if you are looking for another way you can use regex for this task but is not as efficient as the preceding solutions.
character = input("Enter a character: ")
import re
if re.match(r'[a-z]+',characters):
print(character, "is a lower case letter.")
elif re.match(r'[A-Z]',characters):
print(character, "is an upper case letter.")
elif re.match(r'[0-9]+',characters):
print(character, "is a digit.")
else:
print(character, "is a non-alphanumeric character.")
In a ceasar cipher I need it to be that my upper characters remain upper and that non letter character remain non letters/the same. I have it that I can work with lower letters.
Upper letters however are converted to lower and a different letter. Non-letter characters are converted to a lower letter as well. Upper letters must shift but remain upper. Non-letter characters must remain as non-letter character.
p = raw_input(("enter a word"))
n = input(("how many must it shift"))
a = 0
b = 0
c = 0
d = 0
for i in p:
if i.isupper():
a += 1
elif i.islower():
b += 1
elif i.isdigit():
c += 1
else:
d += 1
e = ""
for i in p:
if i == "":
e += i
else:
integerValue = ord(i)
integerValue-= 97
integerValue += n
integerValue %= 26
integerValue += 97
e += chr(integerValue)
print e
You can use i.isalpha() to check if the current character is a letter or not and you can use i.isupper() to check if the current letter is uppercase or not. When you convert the letter you will need to make the letter lowercase and then convert it back to upper. On top of those changes you have too many parenthesis for your inputs. I used raw_input since I'm using python 2.7. Your formatting is so off your code that's posted won't run due to indentation errors and your line if i == "" checks for an empty string instead of a space which I am assuming you were going for. All that said here is what I did to your code to try and keep it similar to what you had while cutting out extraneous bits.
p = raw_input("enter a word")
n = int(raw_input("how many must it shift"))
e = ''
for i in p:
if not i.isalpha():
e+=i
else:
integerValue = ord(i.lower())
integerValue-= 97
integerValue += n
integerValue %= 26
integerValue += 97
if i.isupper():
e += chr(integerValue).upper()
else:
e += chr(integerValue)
print e
I have this code;
offset = -0
print ("In Command 3 - Brute force")
string = input("Please enter a string to Brute Force:")
while offset > -26:
offset = offset - 1
print("")
for letter in string:
letter = (ord(letter))
letter = letter + offset
if letter > 126:
letter - 95
elif letter < 32:
letter + 32
output = (chr(letter))
print(output,end='')
choice = 0
Output depending on the string something like this;
rc`rcr
qb_qbq
pa^pap
o`]o`o
n_\n_n
m^[m^m
l]Zl]l
k\Yk\k
j[Xj[j
iZWiZi
hYVhYh
gXUgXg
fWTfWf
eVSeVe
dURdUd
cTQcTc
bSPbSb
aROaRa
`QN`Q`
_PM_P_
^OL^O^
]NK]N]
\MJ\M\
[LI[L[
ZKHZKZ
YJGYJY
Now, I need some text before the output for example;
Decryption string rc`rcr
Decryption string qb_qbq
etc...
I have tried;
print("Decryption",output,end='')
and
print("Decryption"+output,end='')
However this gives me that text in front of every letter.
Please assist if you can, and explanation would also be preferred.
Thanks for your time.
Ben
You want to do something like this:
offset = -0
print ("In Command 3 - Brute force")
string = input("Please enter a string to Brute Force:")
while offset > -26:
offset = offset - 1
word = ""
for letter in string:
letter = (ord(letter))
letter = letter + offset
if letter > 126:
letter - 95
elif letter < 32:
letter + 32
output = (chr(letter))
word = word + output
choice = 0
print("Decryption: "+word)
The problem with what you were trying is that it will print the 'Decrypting:' message for each character not for each word, so you need to build the word before printing it.
You are printing the output letter by letter, so adding print("Decryption"+output,end='') will just add the 'Decryption' part to each printout. I suggest doing a:
print("Decryption" + string, end=' ')
before you start your for loop.
You need to build your output string and then print it after the for loop
offset = -0
print ("In Command 3 - Brute force")
string = input("Please enter a string to Brute Force:")
while offset > -26:
offset = offset - 1
output_final = None
for letter in string:
letter = (ord(letter))
letter = letter + offset
if letter > 126:
letter - 95
elif letter < 32:
letter + 32
output_final += (chr(letter))
choice = 0
print 'Description:', output_final