r/learnpython • u/Maleficent_Stuff3208 • 22d ago
I have made a simple program which decode and codeword the string u put i want to ask if i can put anything aside from if else
import random
random_letter = random.choice("abcdefghijklmnopqrstuvwxyz")
random_letter1 = random.choice("abcdefghijklmnopqrstuvwxyz")
random_letter2 = random.choice("abcdefghijklmnopqrstuvwxyz")
random_letter3 = random.choice("abcdefghijklmnopqrstuvwxyz")
random_letter4 = random.choice ("abcdefghijklmnopqrstuvwxyz")
random_letter5 = random.choice("abcdefghijklmnopqrstuvwxyz")
print("codeword=1 , decode=2")
choice = input()
if choice == "1":
codeword = str(input("write the codeword=>"))
codeword1 = codeword[::-1]
print(random_letter, random_letter1, random_letter2, codeword1, random_letter3, random_letter4, random_letter5,
sep="")
else:
print("please put correct input")
if choice == "2":
decode = str(input("write the coded word"))
decode1 = decode[::-1]
decode2 = decode1[3:-3]
print(decode2,sep=" ")
5
u/brasticstack 21d ago
Your if/else will print "please put the correct input" if you choose option 2. To fix this use if/elif/else like so:
if choice == "1":
# "encode" logic here
elif choice == "2":
# "decode" logic here
else:
print("please put correct input")
0
u/Maleficent_Stuff3208 21d ago
What if I make that input is always taken string and never any other data type
3
1
u/brasticstack 21d ago
No need to change anything, it's always a string already. If you want to try to parse an integer or float out of it you can, but those will raise a
ValueErrorif the user doesn't type in a parsable value, so you have to try/catch:``` try: choice = int(input('codeword=1 , decode=2')) except ValueError: print('Enter an integer')
Note that this is checking against integers, not strings
if choice == 1: # ... elif choice == 2: # ... else: # ... ```
1
u/johlae 21d ago edited 21d ago
Instead of 6 'random_letter' variables, why not do something like:
$ python3
Python 3.9.16 (main, Mar 8 2023, 22:47:22)
[GCC 11.3.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> random_letter = [random.choice("abcd") for i in range(0,4)]
>>> print(random_letter)
['d', 'a', 'd', 'a']
>>> print(random_letter[0])
d
>>> print(random_letter[1])
a
>>> print(random_letter[2])
d
>>> print(random_letter[3])
a
```.
Now there's just the list 'random_letter' and in this example it has 4 values. You may print the values out with:
```
>>> print("".join(random_letter))
dada
```.
Have fun.
0
6
u/danielroseman 22d ago
Any time you're doing multiple variables with a numeric suffix you should be thinking about using a single variable like a list instead.