I have this little code:
> def names():
prefixes='JKLMNOPQ'
suffix='ack'
for letter in prefixes:
if letter == 'O'or 'Q' in prefixes:
print letter +'u' +suffix
else:
print letter+suffix
And I would like to achieve the following format after printing it:
Jack
Kack
Lack
Mack
Nack
Ouack
Pack
Quack
However I get this one:
Juack
Kuack
Luack
Muack
Nuack
Ouack
Puack
Quack
For any reason I cannot see the if statement is not work. How can I manage to make it work?
You probably might want to change your code to:
def names():
prefixes='JKLMNOPQ'
suffix='ack'
for letter in prefixes:
if letter == 'O' or letter == 'Q':
print letter +'u' +suffix
else:
print letter+suffix
Your problem is you have a "always" True condition:
def names():
prefixes='JKLMNOPQ'
suffix='ack'
for letter in prefixes:
if letter == 'O'or 'Q' in prefixes: # here
print letter +'u' +suffix
else:
print letter+suffix
'Q' is always in prefixes - the condition is alwas True.
Use if letter in 'O Q': instead.
Related
The following code is for one of my excercises to pass the subject,
This is my code:
rot13=raw_input("Please write your text! ")
This is where i ask the user for a text
for i in range(len(rot13)):
And in this part I check the text letter by letter with for.
if rot13[i]=="a":
rot13[i]="n"
elif rot13[i]=="b":
rot13[i]="o"
elif rot13[i]=="c":
rot13[i]="p"
elif rot13[i]=="d":
rot13[i]="q"
elif rot13[i]=="e":
rot13[i]="r"
elif rot13[i]=="f":
rot13[i]="s"
elif rot13[i]=="g":
rot13[i]="t"
elif rot13[i]=="h":
rot13[i]="u"
elif rot13[i]=="i":
rot13[i]="v"
elif rot13[i]=="j":
rot13[i]="w"
elif rot13[i]=="k":
rot13[i]="x"
elif rot13[i]=="l":
rot13[i]="y"
elif rot13[i]=="m":
rot13[i]="z"
elif rot13[i]=="n":
rot13[i]="a"
elif rot13[i]=="o":
rot13[i]="b"
elif rot13[i]=="p":
rot13[i]="c"
elif rot13[i]=="q":
rot13[i]="d"
elif rot13[i]=="r":
rot13[i]="e"
elif rot13[i]=="s":
rot13[i]="f"
elif rot13[i]=="t":
rot13[i]="g"
elif rot13[i]=="u":
rot13[i]="h"
elif rot13[i]=="v":
rot13[i]="i"
elif rot13[i]=="w":
rot13[i]="j"
elif rot13[i]=="x":
rot13[i]="k"
elif rot13[i]=="y":
rot13[i]="l"
elif rot13[i]=="z":
rot13[i]="m"
print rot13
Does anyone knows why this is not working? I do not want to do it with encode.
There are a couple of issues with your code.
First, you're trying to assign a character to a string, but strings are immutable, so you can't swap out chars using =. Second, you don't need to hardcode each character and its mapping. You should use the modulus operator (%).
The basic solution is to loop through each char, turn it into a number, add 13 to it, and turn it back into a character. You'll have to consider the case where your input is "z" and the resulting character lies beyond the alphabet. That's where you'll have to use the modulus operator to force the character to wrap around.
Here's an example:
def rot13(string):
result = []
for char in string:
shiftBy = 65 # uppercase 'A'
if char.islower():
shiftBy = 97 # lowercase 'a'
newChar = chr(((ord(char) + 13 - shiftBy) % 26) + shiftBy)
result.append(newChar)
return ''.join(result)
print rot13("abcXYZ")
ord converts a character to its numeric representation (e.g. 'a' becomes 97)
chr does the reverse computation (e.g. 97 becomes 'a')
I wanted to enter a word with upperandlower letter combination letters and then when i press enter it will change vice versa
def changer(word):
for letter in word:
if letter.isupper():
letter.lower()
elif letter.islower():
letter.upper()
print word
word = raw_input()
changer(word)
You must append the converted letters to new string, and returning the new string could be helpful, too.
def changer(word):
newWord = ""
for letter in word:
if letter.isupper():
newWord += letter.lower()
elif letter.islower():
newWord += letter.upper()
print newWord
return newWord
...you do not return anything. and strings in python are immutable; you can not change them in-place.
this is something you could try:
def swapcase(word):
return ''.join(c.lower() if c.isupper() else c.upper() for c in word)
print(swapcase(word='Hello')) # hELLO
where i use str.join to join the generator that iterates over the characters with the swapped case.
speed-wise str.translate may be the better choice:
from string import ascii_lowercase, ascii_uppercase
trans_table = str.maketrans(ascii_lowercase + ascii_uppercase,
ascii_uppercase + ascii_lowercase)
def swapcase(word):
return word.translate(trans_table)
print('Hello'.translate(trans_table)) # hELLO
I am new to python.
My Issue- need to terminate the raw_input if no input is passed
I am basically asking user for number of key-value pairs to be added to dictionary. Then adding the key-value pairs in dictionary. Later querying the dictionary which should result value if key exist, else print Not found.
I searched the Stack Overflow and found solution in terms of timer but I am trying to use ord function to get ascii value of string and check it against null that is ascii value of 0. My code does not seem to terminate, please advice on necessary changes in code.
Please find the code that I am using in the program:
def convert_to_ascii(text):
return "".join(str(ord(char)) for char in text)
n=int(raw_input().rstrip())
phonebook = dict(raw_input().split() for i in range(n))
print phonebook
list1=[]
while True:
choice = raw_input()
temp=convert_to_ascii(choice)
print temp
if temp != '0':
list1.append(choice)
else:
break
for word in list1:
if word in phonebook :
print '{0}={1}'.format(word,phonebook[word])
else:
print 'Not found'
You should have the empty string '' instead of '0' as your check. This code worked for me. I also added some prints in the raw_inputs to help me look through your code, but the only change that matters is the '0' to '':
def convert_to_ascii(text):
return "".join(str(ord(char)) for char in text)
n=int(raw_input('How many entries in your phonebook?\n').rstrip())
phonebook = dict(raw_input('Please enter "[name] [number]" for entry '+str(i+1)+':\n').split() for i in range(n))
print phonebook
list1=[]
while True:
choice = raw_input('Who do you want to choose?\n')
temp=convert_to_ascii(choice)
if temp != '': #<-- changed to empty string from '0'
list1.append(choice)
else:
break
for word in list1:
if word in phonebook :
print '{0}={1}'.format(word,phonebook[word])
else:
print word,'was not found'
I'm making a hang man game. When I made the code with out a conditional and classes, it worked fine. Basically my issues with the code below are:
Only the letter "t" will match. I can't get any other letter to match.
If I enter "t" on the first try, then purposely get the next 4 letters wrong, it won't end until after 7 turns. Yet if I enter any other letter first, it will end after 4 wrong turns, like it should.
My questions....
How can I get it to match with the other letters that are in the self.word index?
Why is it not obeying the condition I set with the while loop in the main method if I enter "t" on my first try and get every other letter wrong thereafter?
class Hang():
def __init__(self):
self.turns = 0
self.word = ['t', 'h', 'i', 's']
self.empty = ["__", "__", "__", "__"]
self.wrong = []
def main(self):
while self.turns < 4:
for i in self.word:
choice = raw_input("Enter a letter a-z: ")
if choice == i:
index = self.word.index(i)
self.empty.pop(index)
self.empty.insert(index, i)
print self.empty
else:
print "Wrong"
self.wrong.append(choice)
print self.wrong
print self.empty
self.turns += 1
char1 = Hang()
char1.main()
In the game of hangman you can guess any character in the phrase in any order. But you're using a for loop to go through each character in order and it is only correct if the player correctly guesses the characters in order
Try this instead
while self.turns < 4:
choice = raw_input("Enter a letter a-z: ")
# optional, if user enters more than a single letter
if len(choice) > 1:
print "invalid choice"
continue # loop again from start
index = self.word.index(choice)
if index != -1:
# -1 indicates character in not int the string
# so this block is only executed if character is
# in the string
self.empty[index] = choice # no need to pop, you can simply change the value of the list at a given index
else:
print "wrong"
self.turns += 1
print self.empty
a_lst = ['chair','gum','food','pizza']
letter = 'x'
for word in a_lst:
if letter not in word:
print ('no',letter)
elif letter in word:
print ('yes',letter)
Output:
no x
no x
no x
no x
Is there a way i can iterate though each item in "a_lst", check if each item has letter 'x'. if no item has letter 'x' print 'no x' just Once. If a word contains letter 'x', print 'yes x' just Once.
I think my logic is flawed somewhere.
Any suggestions?
Thanks
You could do this:
letter = 'x'
result = [a for a in a_lst if letter in a]
if result:
print('yes', letter)
else:
print('no', letter)
Explanation:
result will be [] if none of the words in a_lst has the letter. When you do a if result on an empty list, it returns False, otherwise it returns True. The conditional statements check and print the output statement accordingly.
Another way to do it in python is to use the filter function:
if filter(lambda x: letter in x, a_lst):
print('yes', letter)
else:
print('no', letter)
Yet another way to do it is to use any:
if any(letter in word for word in a_list):
print('yes', letter)
else:
print('no', letter)
any(letter in word for word in a_list) returns True if any of the words have the letter.
You can use the any function!
if any(letter in word for word in a_lst):
print('yes', letter)
else:
print('no', letter)
Have you tried something like this:
a = ['chair', 'gum', 'food', 'pizza']
letter = 'a'
result = 'no ' + letter
k = 0
for i in a:
if letter in a[k]:
print(a[k])
result = 'yes ' + letter
k += 1
print(result)