separate input group in python with a print - python-3.x

I am a beginner in python I would like to create an interface which allows to enter text (number) and to cut the output with print to separate the different elements
for example
my texte = NNNNNNNNNKKVVVVVECPM
in output I would like = NNNNNNNNN KK VVVVV E C P M
thank you for your help good day

If you just want to insert spaces between sequences, try this:
text = "NKNNPPOUSSEVNN"
l=[]
for i,char in enumerate(text):
try:
if text[i]==text[i+1]:
l.append(char)
else:
if i==0: l.append(str(text[i])+" "+str(text[i+1]))
else: l.append(" "+str(text[i+1]))
except: pass
print("".join(l))
This gives:
N K NN PP O U SS E V NN
If you want to group the text on characters and then print out, use itertools:
import itertools
text = "NKNNPPOUSSEVNN"
for i,grp in itertools.groupby(sorted(text)):
print("".join(grp),end=" ")
This gives:
E K NNNNN O PP SS U V

hello thank you for the answer my main problem is that my numbers are separated by check I can display my text but I want separation
voici mon programe
#!/usr/bin/python3
from tkinter import *
class MyWindow(Tk):
def __init__(self):
Tk.__init__(self)
self.__code = StringVar()
label = Label( self, text="Scanner le code barre:")
label.pack()
code = Entry(self, textvariable=self.__code )
code.focus_set()
code.pack()
button = Button( self, text="Vérifier!", command=self.doSomething)
button.pack()
self.geometry( "400x300" )
self.title( "Entry widget usage" )
def doSomething(self):
print( "ticket restaurant " + self.__code.get() )
window = MyWindow()
window.mainloop()

Related

I get "Process finished with exit code 0" instead of expected output

I'm new to coding in Python and I starting writing my own program. Things don't work and I'm having great difficulty understanding why.
I've tried changing my variables from global to class to everything under the sun and it's still bugs. I've also went through my code many many times but I kind of feel as if I'm just throwing together random things.
This code is supposed to ask for your name then ask for your height, weight, shape-size and shoe-size. It should have a function for each variable which asks the user for their information then at the end of the code it should state that persons name then state their other information back to them. ex
hello Jimmy! Your Height is 5'6" your weight is 180 lbs your shirt-size is medium and your shoe-size is 10.
My code:
name = input('What Is your Name?')
print('Hello' + name + '!')
# This is the next part in the code
class Information:
global name1
name1 = Information()
height2 = Information()
weight3 = Information()
shirtSize4 = Information()
shoeSize5 = Information()
n = name1
h = height2
w = weight3
sh = shirtSize4
ss = shoeSize5
i=int
def n() : (h,w,sh,ss)
def h(): int(input('Please Enter Your Height'))
if h == i(4):
print("Please provide a Height larger than 4 feet")
else:
print(h)
def w() : i(input("Please Enter Your Weight in number of pounds, ex(100)"))
if w == i(90):
print("There is now way you're under 90 lbs. Please Enter A different weight")
def sh() : i(input("Please Enter your Shirt Size"))
def ss() : i(input("Please enter Your shoe size"))
if ss == i(3):
print('Please Enter a shoe size larger than an infant thank you.')
else:
print(ss)
#in the next line i'm trying to print out a string with variables
def print():
("Hello" + n + '! Your Height is' + h + "Your Weight is" + w + "Your Shirt-Size is"+ sh + "and your ShoeSize is" + ss)
And the result:
What Is your Name?Zack
HelloZack!
<function h at 0x02D09C48>
<function ss at 0x02D09D20>
Process finished with exit code 0
This is what comes up instead of input questions.

Format output right to left

I am trying to learn how to format print to make it look neat. My program would count how many vowels are in a piece of text. But wont print the way I would like which is right to left
As example -
I would like it to print as:
a : 100
e : 50
i : 31
o : 10
u : 1
Currently I have it printing as the following:
a : 100
e : 50
i : 31
o : 10
u : 1
Here is my code and the printing option so far....
import sys
vowels = {i:0 for i in 'aeiou'}
def check(string):
for char in string:
if char in vowels:
vowels[char] +=1
return vowels
def main():
for line in sys.stdin:
lines = line.lower().strip()
check(lines)
sortvowels = sorted(vowels, key=vowels.get, reverse=True)
for r in sortvowels:
print(' {:} {} {:>d}'.format(r,":",vowels[r]))
#for keys, values in sorted(vowels.items(),reverse=False):
# print('{} : {:d}'.format(keys, vowels[maximum]))
if __name__ == '__main__':
main()
I solved this problem by obtaining the max value from my dictionary,
I had to add the additional code,
formt = max(vowels.values())
finalformat = len(str(formt))
I did this by formt = max(vowels.values())
In order to actually use this, I had to convert that into a string.
I did this by finalformat = len(str(formt))
To finally be able to print I did the following:
sortvowels = sorted(vowels, key=vowels.get, reverse=True)
for r in sortvowels:
print('{} {} {:>{}}'.format(r,":",vowels[r],finalformat))

How to specify ANY string

So I have this code:
from tkinter import *
import re
master = Tk()
e1 = Entry(master)
def confirmit():
s = re.findall(r'\b\d+\b', e1.get())
if e1.get() == "Whoscreator":
vyvod.configure(text="Kewbin")
if e1.get() == "Whatscreatorsrealname":
vyvod.configure(text="Peťo Letec")
if e1.get() == "/give " + (what should I type here?):
vyvod.configure(text= s)
vyvod = Label(master, text="First Name")
confirmer = Button(text="Confirm", command = confirmit)
e1.pack()
vyvod.pack()
confirmer.pack()
mainloop()
I have an entry bar.
And I want this for example:
If I type in the bar /give 1000 it will type the number 1000 into Label vyvod. And I want this to work with any number i type after /give
The simplest solution is to split the string on a space, examine the first word, and do whatever is appropriate with the rest.
value = e1.get()
first, rest = value.split(" ", 1)
if first == "/give":
vyvod.configure(text=rest)

What is wrong with my elif statement? Invalid Syntax

if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
from tkinter import *
def mhello():
mtext = ment.get()
mLabel2 = Label(test, text=mtext).pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+10')
test.title('Test')
mlabel = Label(test, text='Time to guess').pack()
mbutton = Button(test, text='Click', command = mhello).pack()
mEntry = Entry(test, textvariable=ment).pack()
test.mainloop()
from tkinter import *
def mhello():
my_word = 'HELLO'
mtext = ment.get()
if my_word == mtext:
mLabel2 = Label(test, text='Correct').pack()
else:
mLabel2 = Label(test, text='Incorrect').pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+300')
test.title('Test')
def label_1():
label_1 = Label(test, text='Hello. Welcome to my game.').pack()
def label_2():
label_2 = Label(test, text='What word am I thinking of?').pack()
button_1 = Button(test, text='Click', command = mhello).pack()
entry_1 = Entry(test, textvariable=ment).pack()
label_1()
test.after(5000, label_2)
test.mainloop()
from tkinter import *
from random import shuffle
game = Tk()
game.geometry('200x200')
game.grid()
game.title("My Game")
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def board_1():
board1 = []
k = 0
for i in range(3):
for j in range(3):
board1.append(Label(game, text = board[k]))
board1[k].grid(row = i, column = j)
k +=1
def board_2():
shuffle(board)
board2 = []
k = 0
for i in range(3):
for j in range(3):
board2.append(Label(game, text = board[k]))
board2[k].grid(row = i, column = j)
k +=1
board_1()
game.after(5000, board_2)
game.mainloop()
#2nd Option
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
The bit that has the Syntax Error is the 1st elif statement (2nd Option). Ignore all the code prior to this if necessary (it is there for context). Whenever I run the code it says that there is a syntax error and just positions the typing line (I don't know what it's called) at the end of the word elif.
This is a simple fix, with if else statements you need to have a closing ELSE and in this case there is not so when your program runs it sees that theres a lonely if without its else :)
if option == "1":
elif option == "2":
else:
'do something else in the program if any other value was recieved'
also a switch statement can be used here so it does not keep checking each condition and just goes straight to the correct case :D
The problem is that your block is separated from the first if-statement, where it actually belongs to. As it is, it follows the game.mainloop() statement, and adds an unexpected indentation. Try to rearrange your code like so:
if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
[ Rest of the code ]

Python 3.3 cypher script

So i have this code here in python 3.3, it cyphers text with the ceaser cypher.
What i need to know is how do i make a script that will convert it back from the original so that the person i send it too can read it.
message = input("Input: ")
key = 11
coded_message = ""
for ch in message:
code_val = ord(ch) + key
if ch.isalpha():
if code_val > ord('z'):
code_val -= ord('z') - ord('a')
coded_message = coded_message + chr(code_val)
else:
coded_message = coded_message + ch
# print ("Input: " + message)
print ("Output: " + coded_message)
One more thing, I plan to be putting this is a tkinter message box, with the two entry fields used for the input and output. one field should be used to type what i want to convert and the other should be used to show what the text looks like after it has been crypted. The button should start the encryption. here is the code:
import sys
from tkinter import *
def mHello():
mLabel = Label(mGui,text = input("Hello World"))
mLabel.grid(row=3, column=0,)
mGui = Tk()
ment = StringVar()
mGui.geometry("450x450+250+250")
mGui.title("My TKinter")
# input label
mLabel = Label(mGui,text = "Input",)
mLabel.grid(row=1,column=0,)
# output label
mLabeltwo = Label(mGui,text = "Input",)
mLabeltwo.grid(row=2,column=0,)
# convert button
mButton = Button(text = "Convert",command = mHello)
mButton.grid(row=3,column=0)
# input entry
mEntry = Entry(mGui,textvariable=ment)
mEntry.grid(row=1,column=1)
# output entry
mEntryTwo = Entry(mGui,textvariable=ment)
mEntryTwo.grid(row=2,column=1)
mGui.mainloop()
By the way i am only 15 and this is my 2nd day learning python.
Some credit goes to sources on this forum that have provided me with some code snippets
Thank-you in advance guys!
Before i say anything else you should be aware that minds much greater the mine have advised against writing your own cypher script for anything other then learning
If you want them to be able to decode your code then provide them with a key. so in your case:
s maps to h
t maps to i
f maps to t
I hope this code illustrates my suggestion:
In [1]: from cyro import your_cyrptic_function
In [2]: key = {'s':'h', 't':'i', 'f':'t'}
In [3]: secret_word = your_cyrptic_function('hit')
In [4]: decyrpted_secret_word = ''
In [5]: for letter in secret_word:
decyrpted_secret_word += key[letter]
...:
In [6]: print(decyrpted_secret_word)
hit
For the code above i turned your original code into a function:
def your_cyrptic_function(secret):
message = secret
key = 11
coded_message = ""
for ch in message:
code_val = ord(ch) + key
if ch.isalpha():
if code_val > ord('z'):
code_val -= ord('z') - ord('a')
coded_message = coded_message + chr(code_val)
else:
coded_message = coded_message + ch
# print ("Input: " + message)
return coded_message
there are several great ways to do this in python. If your interested in cyptopgraphy then check out Udacities class cs387 applied cryptography

Resources