Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am making a simple python project for encrypting messages. Before I share what I want to shorten here is the link to my code for decrypting a message (that I need help with):
https://www.sendspace.com/file/jji74r
My problem is I don't know how to read the message without having to have 25 lines of code, this program tests for 25 characters of encrypted message so if I want to test 30 characters of encrypted text I need 5 more lines of code. Is there any method of decreasing the size of any part of my program?
You could do this with some nested loops -
INCREMENT = 3
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
BEM_LENGTH = 25
#data needed from user to decrypt a message encrypted via BEM
BEM = input("Please input your BEM key: ")
message = input("please input the message you wish to decrypt (up to 26 characters): ")
# processing
for i in range(0, len(message)//INCREMENT):
mess = message[(i*INCREMENT):(i+1)*INCREMENT]
for j in range(0, BEM_LENGTH):
bem = BEM[(j*INCREMENT):(j+1)*INCREMENT]
if mess == bem:
print(ALPHABET[j], end="")
print()
I noticed that the change in the values was always 3, so the INCREMENT I set to 3.
I also needed the alphabet. I put in a BEM_LENGTH constant so that you can easily change it.
After that, I got the input.
Then, I looped through the message, with increments of 3 like you had hardcoded in. Then, I looped through the BEM key and compared it, similar to your if statements. Then, if they were matching, I printed the right character of the alphabet. If you need more help I could email you or chat on discord if you need some help!
I could do this in around 4 lines, using list comprehension, but it would be very difficult to read. This is the most readable, clean way of doing it.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
This post was edited and submitted for review 3 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
my Code doesent understand letters in the list i would like somone to help me fix this
usernames = (BTP, btp, Btp, BTp)
def username(usernames2):
if usernames == input('whats your username? : ')
Its a simple username system, i plan to use for a interface im making.
usernames is defined as a tuple of 4 items, with the names BTP, btp, Btp, and BTp. You said "list" in your title but your code has no actual lists. Lists use brackets, tuples use parentheses.
Anyway, I'm assuming you actually want to check if the user's input actually was equal to the letters "btp" and you want the check to be case-insensitive, hence why you included all combos of uppercase and lowercase.
The main issue is that you didn't put quotes around the strings, so you have just 4 bare names sitting in your code which the interpreter expects to have been defined previously. But, you actually don't have to define all the possible combinations of uppercase and lowercase in the first place - there's a much easier method to do a case-insensitive string compare, here.
So, your code just needs to look like:
usename = "btp"
def username(usernames2):
if input('whats your username? : ').lower() == username
Or, if you want to check against multiple usernames, you can use the in operator:
usenames = ["btp", "abc", "foo", "bar"]
def username(usernames2):
if input('whats your username? : ').lower() in usernames
If you haven't declared BTP, btp, Btp, and BTp you will get a NameError
If you wanted to use strings you need single or double quotation marks:
usernames = ("BTP", "btp", "Btp", "BTp")
With that you create a tuple containing four string elements.
The next issue is with your if condition as you compare if a tuple is equal a string.
Try storing the input given from the user in a variable:
def username(usernames):
user_input = input('whats your username?: ')
if user_input in usernames:
# Do something when username is found
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I am wanting to rearrange strings in python, but don understand what functions would be useful in doing so? Can someone help me understand how do this: remove the first letter of a word and place that letter at the end of the word. Then you append "IE" to the end of the word. I would appreciate it, if someone can link to the functions that might be used, so I can learn how they work.
EDIT: I have tried to make this work with a phrase, but I am having issues with getting it to the ie to go at the end of the words. For example HankTIE ouYIE would be the output of the input Thank You.
Here is what I have:
string = input("Please input a word: ")
def silly_encrypter(string):
words = string.split()
for words in string:
first_letter= words[1:] + words[0]
ie_end = first_letter + "IE"
print (ie_end)
silly_encrypter(string)
As other users pointed out, I strongly suggest you to read Python tutorial, which is very friendly and contains a lot of examples that you can try out in your python console.
Having said that, you could take advantage of string indexing plus concatenation to accomplish the things you want (Both things are mentioned in the tutorial):
remove the first letter of a word and place that letter at the end of the word:
s = "myString"
first_letter_at_the_end = s[1:] + s[0]
# If you print `first_at_the_end` you'll get: 'yStringm'
then append "IE" at the end
ie_at_the_end = first_letter_at_the_end + "IE"
# If you print `ie_at_the_end` you'll get: 'yStringmIE'
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
In the war against Skynet, humans are trying to pass messages to each other without the computers realising what's happening.
To do this, they are using a simple code:
They read the words in reverse order They only pay attention to the words in the message that start with an uppercase letter So, something like:
BaSe fOO ThE AttAcK contains the message:
attack the base
However, the computers have captured you and forced you to write a program so they can understand all the human messages (we won't go into what terrible tortures you've undergone). Your program must work as follows:
soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess.
code: soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess.
says: destroy their ice-cream supplies
Notice that, as well as extracting the message, we make every word lowercase so it's easier to read.
Could you please help me with my code? This is my code so far:
output=[]
b=0
d=0
code=input("code: ")
code=code.split()
print(code)
a=len(code)
print(a)
while b<a:
c=code[b]
if c.isupper:
output.append(c)
b=b+1
elif c.islower:
b=b+1
else:
b=b+1
print(output)
I need the last line to say "BaSe ThE AttAck" eliminating "fOO" and I will be reversing the string in the last step to make sense, but it is not differentiating between a lowercase word and an uppercase word.
I have rewritten your code.
#code=input("code: ")
code = "soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess"
code=code.split()
output = []
for word in reversed(code): #iterate over the list in reverse
if word[0].isupper(): #check if the FIRST letter (word[0]) is uppercase.
output.append(word.lower()) #append word in lowercase to list.
output = " ".join(output) #join the elements of the list together in a string seperated by a space " "
print(output)
output
destroy their ice-cream supplies
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
First, I would like to say I am new to coding and python in general. I just learned about importing and the random function.
Anyways, I am trying to create a text game, in python, where a letter is chosen randomly from some string/word and the user has to try and guess which letter was chosen. I think I understand how to do for loops well enough so that it continues until the correct letter is chosen, but I have no idea how to even go about randomly choosing the letter.
I would just like some help getting started. Thank you.
Since strings are sequences in Python, you can use random.choice to pick a random element from a list - in your case, a random letter in a string.
>>> import random
>>> c = random.choice("abcdefgh")
>>> c
'g'
>>> c = random.choice("abcdefgh")
>>> c
'a'
The >>>'s are from the REPL console (running Python by itself) and shouldn't be included if you include the code in a python file.
There is a library for randomizing things. Simply use it like this:
import random
text = "Some text"
your_variable = random.choice(text)
and you get your random letter from a sequence in that case which is saved in your_variable.
Since you are relatively new to programming, I'd like to give you an informative example of the game to clarify some concepts.
String str is implemented as sequence in Python (you can think that a string is an array of chars). So it supports indexing s = 'abc'; print(s[1]); shows b.
The standard library random includes a bench of functions to carry out randomized operations. As mentioned in the other answers that the function random.choice randomly pick an element from a sequence. So it can be used to randomly pick a character from a string.
You mentioned loops and you seem to be able to master them. So I hereby use another approach called recursion to continue the game until the desired answer is found.
The game is written in an Object-Oriented manner. If you gonna be a developer latter in your career, it's good practice to see this.
Here is the Code:
import random
class Game:
def __init__(self, string):
self.string = string
def start_game(self):
self.answer = random.choice(string)
self.ask_player()
def ask_player(self):
char = input("Just enter your guess: ")
self.cheat(char)
if char == self.answer:
print("Bingo!")
return None
else:
print("You missed, try again! (Or press Ctrl+C to goddamn exit!)")
self.ask_player()
def show_answer(self):
print('The answer iiiis: %s \n' % self.answer)
def cheat(self, user_input):
if user_input == 'GG':
self.show_answer()
if __name__ == '__main__':
string = "This is the string from which the letters are ramdomly chosen!"
gg = Game(string)
gg.start_game()
Some test runs:
Just enter your guess: 2
You missed, try again! (Or press Ctrl+C to goddamn exit!)
Just enter your guess: T
You missed, try again! (Or press Ctrl+C to goddamn exit!)
Just enter your guess: GG (Haha, I left a cheat code in order to get the right anwser!)
The answer iiiis: o
You missed, try again! (Or press Ctrl+C to goddamn exit!)
Just enter your guess: o
Bingo!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want my program to ask a value of n. After user inputs the value,
program takes input for n values and stores them in a list or something like array (in C).
Input must be in the format:
Enter value of n: 4
2
5
7
1
I want to store this input in a list for my later use.
The simplest approach is something like this:
n = int(input())
l = [int(input()) for _ in range(n)]
However this has a number of problems:
It will crash on invalid inputs.
It evaluates the inputs which is dangerous - the user could modify your program state. (Python 2.x)
The user could enter floating point numbers and the program won't complain, it will just silently truncate. (Python 2.x)
Instead you can use raw_input and parse the result as an integer. You will also need error handling in the appropriate locations. How you handle errors depend on the program.
You might find this function might be useful as a starting point:
def getNumber(prompt = ''):
while True:
try:
return int(raw_input(prompt))
except:
print "Invalid input, try again."
Note that the behaviour of input and raw_input has changed between Python 2.x and Python 3.x. Python 3.x's input function behaves like Python 2.x's raw_input function.
The interface you propose is rather badly designed. Why not simply let the user enter the numbers? Let the computer do the counting, if a count is really needed:
line = raw_input("Numbers: ")
numbers = [int(s) for s i line.split()]
The code will be more complex with error checking, but the basic approach is to make things easier for the user.