How to Change code from one .py file to another .py file - python-3.x

I need to add some code line in a .py file from another .py file
This is the file i want to add code lines:
Conversor_monedas
def menu():
x = int(input("Escoge tu moneda original, siendo:\n1.Dólares\n2.Euros\n3.Soles\n4.Reales\n5.Pesos uruguayos\n6.Pesos Chilenos\n")) #(eeuu,europa,peru,brasil,uruguay,chile)
y = int(input("Escoge tu moneda convertida, siendo:\n1.Dólares\n2.Euros\n3.Soles\n4.Reales\n5.Pesos uruguayos\n6.Pesos Chilenos\n"))
valorx = float(input("Cantidad a convertir: "))
if x == 1:
dolares(valorx,y)
if x == 2:
euros(valorx,y)
if x == 3:
soles(valorx,y)
if x == 4:
reales(valorx,y)
if x == 5:
pesos_uruguayos(valorx,y)
if x == 6:
pesos_chilenos(valorx,y)
def dolares(valorx,y):
if y == 2:
y = "euros"
valory = valorx*0.89
elif y == 3:
y = "soles"
valory = valorx*3.32
elif y == 4:
y = "reales"
valory = valorx*3.92
elif y == 5:
y = "pesos uruguayos"
valory = valorx*33.81
elif y == 6:
y = "pesos chilenos"
valory = valorx*680.50
print(valorx , "dólares equivalen a ", valory , y)
def euros(valorx,y):
if y == 1:
y = "dólares"
valory = valorx*1.12
elif y == 3:
y = "soles"
valory = valorx*3.73
elif y == 4:
y = "reales"
valory = valorx*4.41
elif y == 5:
y = "pesos uruguayos"
valory = valorx*37.97
elif y == 6:
y = "pesos chilenos"
valory = valorx*764.31
print(valorx , "euros equivalen a ", valory ,y)
menu()
...and so on with some other function like those two.
I want to add some other function with a new variable that defines another conversion variables from a different .py program that asks me what function I want to include in Conversor_monedas.

So, this may be way off from what you were thinking, but by entering conversion factors in a file, I believe you can achieve what you're trying to do. Here's a working sample.
#! python3
import csv
global ConvDict
def menu():
BuildCurrencyDict()
CurrencyList = []
FromCurrLit = "Escoge tu moneda original, siendo:"
ToCurrLit = "Escoge tu moneda original, siendo:"
# \n1.Dólares\n2.Euros\n3.Soles\n4.Reales\n5.Pesos uruguayos\n6.Pesos Chilenos\n")) #(eeuu,europa,peru,brasil,uruguay,chile
for i, Currency in enumerate(ConvDict):
FromCurrLit = FromCurrLit + "\n" + str(i+1) + ". " + Currency
ToCurrLit = ToCurrLit + "\n" + str(i+1) + ". " + Currency
CurrencyList.append(Currency)
FromCurrLit = FromCurrLit + "\n"
ToCurrLit = ToCurrLit + "\n"
x = int(input(FromCurrLit)) #(eeuu,europa,peru,brasil,uruguay,chile)
y = int(input(ToCurrLit))
valorx = float(input("Cantidad a convertir: "))
ConvFactor = float(ConvDict[CurrencyList[x-1]][CurrencyList[y-1]])
valory = valorx * ConvFactor
print(valorx , CurrencyList[x-1], "equivalen a", valory , CurrencyList[y-1])
def BuildCurrencyDict():
global ConvDict
CurrTypes= []
ConvDict = {}
# Put a matrix of currencies in CurrConv.txt
with open('CurrConv.txt') as csvfile:
data = csv.reader(csvfile, delimiter="\t")
for LineIn in data:
# user_info[name] = {'code': code, 'name': name, 'id': id}
for i, Item in enumerate(LineIn):
if data.line_num == 1:
if i == 0:
continue
else:
CurrTypes.append(Item)
else:
if i == 0:
FromCurr = Item
else:
if i == 1:
ConvDict[FromCurr] = {CurrTypes[i-1]:Item}
else:
ConvDict[FromCurr][CurrTypes[i-1]] = Item
# print(ConvDict["Euro"]["Dollar"]) # Testing Code
if __name__ == '__main__':
menu()
CurrConv.txt looks like this. I used tab delimited, but you could use semi-colons or some other delimiter if you wanted to. Line 1 starts with a tab. Then there are tabs between values. Simply add other currencies to the file and they will be added to your conversion prompts.
Euro Dollar Yen
Euro 1 1.12 124.53
Dollar 0.89 1 110.88
Yen 0.008 0.009 1

Related

Looking for general feedback + a few small errors

So as the title states I'm simply looking for general feedback on the overall structure of the script, where I could do better (don't have to tell me how, where would be plenty) and things like that. Any feedback, advice, tips or help in general is always greatly appreciated as I'm real keen to learn deeper!
As for the errors...
Errors:
It doesn't seem to save any of the contacts after closing, if the only method of saving it, to save it to a file?
Updating claims to be out of range, which if I'm correct it shouldn't be, unless I'm just not seeing something?
Not exactly an issue but something I've been playing with, with no good result...is it possible to have a for loop w/if statement in a comprehension format without being in a print statement?
My code so far:
"""
This is project that lets the user pretty much create and edit a contact book by giving them options and using their
input to complete the data needed for the contact book.
"""
import sys
contacts = []
lst = []
def ContactBook():
rows, cols = int(input("Please enter the amount of people you want in the contact book: ")), 5
print(contacts)
for i in range(rows):
print(f"All mandatory fields will include *")
for a in range(cols):
if a == 0:
lst.append(input("Enter a name*: "))
if lst[a] == '' or lst[a] == "": sys.exit(f"Failed to provide a name...Exiting the contact book!")
if a == 1: lst.append(input("Enter a number*: "))
if a == 2:
lst.append(input("Enter an email: "))
if lst[a] == '' or lst[a] == "": lst[a] = None
if a == 3:
lst.append(input("Enter a D.O.B (mm/dd/yy): "))
if lst[a] == '' or lst[a] == "": lst[a] = None
if a == 4:
lst.append(input("What category (Family/Friends/Work/Others): "))
if lst[a] == '' or lst[a] == "": lst[a] = None
contacts.append(lst)
print(f"Your contacts are:\n{contacts}")
return contacts
def Menu():
print(f"\t\t\t{'Contact Book':*^70}", flush=False)
print(f"Your options are:\n1. Add a Contact\n2. Searching Contacts\n3. Edit Contacts\n4. Delete Contacts\n"
f"5. View Contacts\n6. Delete Everything\n7. Exit the book")
choice = int(input("Please select an option: "))
return choice
def AddingContacts(cb):
for i in range(len(cb[0])):
if i == 0: contacts.append(input("Enter a name: "))
elif i == 1: contacts.append(int(input("Enter a number: ")))
elif i == 2: contacts.append(input("Enter a email: "))
elif i == 3: contacts.append(input("Enter a d.o.b (mm/dd/yy): "))
elif i == 4: contacts.append(input("Enter a category: "))
cb.append(contacts)
return cb
def SearchContacts(cb):
s = int(input("Select an option:\n1. Name\n2. Number\n3. Email\n4. D.O.B\n5. Category"))
t, c = [], -1
if s == 1:
q = input("Enter who you want to search: ")
for i in range(len(cb)):
if q == cb[i][0]: c = i, t.append(cb[i])
elif s == 2:
q = int(input("Enter the number you want to find: "))
for i in range(len(cb)):
if q == cb[i][1]: c = i, t.append(cb[i])
elif s == 3:
q = input("Enter the email you want to search: ")
for i in range(len(cb)):
if q == cb[i][2]: c = i, t.append(cb[i])
elif s == 4:
q = input("Enter the date you want to search in mm/dd/yy format: ")
for i in range(len(cb)):
if q == cb[i][3]: c = i, t.append(cb[i])
elif s == 5:
q = input("Enter a category you want to search: ")
for i in range(len(cb)):
if q == cb[i][4]: c = i, t.append(cb[i])
else:
print(f"Invalid search inquiry...")
return -1
if c == -1: return -1
elif c != -1:
ShowContent(t)
return c
def ShowContent(cb):
if not cb: print(f"List has nothing in it...: []")
else: print(f"{[cb[i] for i in range(len(cb))]}")
return cb
def UpdateContacts(cb):
for i in range(len(cb[0])):
if i == 0: contacts[0] = (input("Enter a name: "))
elif i == 1: contacts[1] = (int(input("Enter a number: ")))
elif i == 2: contacts[2] = (input("Enter a email: "))
elif i == 3: contacts[3] = (input("Enter a d.o.b: "))
elif i == 4: contacts[4] = (input("Enter a category: "))
cb.append(contacts)
return cb
def RemovingContacts(cb):
q = input("Enter the person you want to remove: ")
x = 0
for i in range(len(cb)):
if q == cb[i][0]: x += 1, print(f"This contact has now been removed: {cb.pop(i)}")
return cb
if x == 0: print(f"Person doesn't exist. Please check the name and try again....")
return cb
def DeleteBook(cb):
return cb.clear()
if __name__ == "__main__":
print(f"Welcome to your new Contact Book! Hope you find it easy to navigate!")
ch = 1
cb = ContactBook()
while ch in (1, 2, 3, 4, 5, 6):
ch = Menu()
if ch == 1: cb = AddingContacts(cb)
elif ch == 2: cb = SearchContacts(cb)
elif ch == 3: cb = UpdateContacts(cb)
elif ch == 4: cb = RemovingContacts(cb)
elif ch == 5: cb = ShowContent(cb)
elif ch == 6: cb = DeleteBook(cb)
else: sys.exit(f"Thank you for using this contact book! Have a great day!")
I plan on using the Pandas module to display the data in table format, is it possible without mySQL?

How to encrypt lower case input

I am trying to create a simple encryption scheme. The scheme is working fine when I take input of the plain text in uppercase. But when I take input of the plain text in lowercase, it is not decrypted correctly.
Can anyone help me to find out the solution?
Here is my code:
def generateKey(string, key):
key = list(key)
st = list(string)
if len(string) == len(key):
return(key,st)
else:
x=len(string) -len(key)
if x>0:
for i in range(x):
key.append(key[i % len(key)])
else:
y=len(key)-len(string)
for j in range(y):
st.append("X")
return("" . join(key),"" . join(st))
def cipherText(string, key):
cipher_text = []
for i in range(len(string)):
if string[i]== " ":
x = ord(string[I])
i+=1
cipher_text.append(chr(x))
else:
abc = ord(string[i]) + ord(key[I])
x = (abc + 2) % 26
x += ord('A')
cipher_text.append(chr(x))
ci="" . join(cipher_text)
rev = ""
for i in ci:
rev = i + rev
return(rev)
def originalText(cipher_text, key):
orig_text = []
re_rev= ""
for i in cipher_text:
re_rev = i + re_rev
for i in range(len(re_rev)):
if re_rev[i]== " ":
x = ord(re_rev[I])
i+=1
orig_text.append(chr(x))
else:
abc = ord(re_rev[i]) - ord(key[i]) + 26
x = (abc - 2) % 26
x += ord('A')
orig_text.append(chr(x))
return("" . join(orig_text))
if __name__ == "__main__":
string = input("Enter Plain Text: ")
keyword = input("Enter Keyword: ")
key,stri = generateKey(string, keyword)
cipher_text = cipherText(stri,key)
print("Ciphertext :", cipher_text)
print("Original/Decrypted Text :",
originalText(cipher_text, key))

I have to write a code for pattern recognition and replacing the pattern?

I have this problem statement where I have a column of patterns that were if the first four bytes have date it should replace those four bytes to ccyy and the rest to N and zeros to Z's
eg. 20190045689 -> CCYYZZNNNNN
if space we need to consider the space as well.
66-7830956 -> NN-NNNZNNN
def patternGeneration(string):
x = re.findall("[\s0-9a-zA-Z]", string)
n = len(x)
j = 0
r = re.compile("\A[^(19|20)]")
y = list(filter(r.match, x))
b = len(y)
for i in range(0, b):
if y[i] == "0":
y[i] = 0
elif y[i] == " ":
y[i] = " "
else:
y[i] = "n"
print(convert(y))
for i in range(0, n):
if x[i] == "0":
x[i] = 0
j = j + 1
elif x[i] == " ":
x[i] = " "
j = j + 1
else:
x[i] = "n"
print(convert(x))
str1 = input("enter the string\t")
patternGeneration(str1)
#convert to new format
def convert(string):
# check for year
head = string[:4]
tail = string[4:]
if head.isnumeric():
if 1900 <= int(head) <= 2099:
head = "CCYY"
new_string = head + tail
return "".join(["Z" if x == "0" else "N" if x.isnumeric() else x for x in str(new_string)])
sample = "20196705540"
print(convert(sample))
#"CCYYNNZNNNZ"
sample = "66-7830956"
print(convert(sample))
#"NN-NNNZNNN"

I just need a little help to get my if statement to work

I am making a quiz which can work with different difficulties and it works fine. The only thing is that its like my code ignores my if statement at the bottom. even when the variable 'w' = 9, which is when i have answered 9 questions, it still doesn't print the statement it just continues looping.
import csv
w = 0
score = 0
global q
with open("Computing.txt", "r") as file:
reader = csv.reader(file)
for row in reader:
dif_c = str(dif) + " "
if dif_c + str(q) + ")" in row[0]:
print (row[0].split(dif_c)[1])
print (row[1])
if dif == 1:
print (row[2])
input10 = input("Answer 'a' or 'b': ")
elif dif == 2:
print(row[2] + "\n" + row[3])
input10 = input("Answer 'a','b' or 'c': ")
elif dif == 3:
print(row[2] + "\n" + row[3] + "\n" + row[4])
input10 = input("Answer 'a','b','c' or 'd': ")
if input10 == row[dif + 2]:
print("Correct")
score = score + 1
w = w + 1
elif input10 != row[dif + 2]:
print("Incorrect")
w = w + 1
if w == 9:
print("Game over")
print("You got", r, "right out of 10")
while True:
quiz()
this is all the quiz function and i defined w and score as 0 within the function which i know wouldnt work but i have no clue how to fix it
Your 'if' condition to check 'w == 9' should be inside the 'for' loop and you need to break out of the 'for' loop based on that condition. Otherwise it will continue to loop.
Currently your 'if' check is outside the 'for' loop.
So it should be changed to something like this:
import csv
w = 0
score = 0
global q
with open("Computing.txt", "r") as file:
reader = csv.reader(file)
for row in reader:
dif_c = str(dif) + " "
if dif_c + str(q) + ")" in row[0]:
print (row[0].split(dif_c)[1])
print (row[1])
if dif == 1:
print (row[2])
input10 = input("Answer 'a' or 'b': ")
elif dif == 2:
print(row[2] + "\n" + row[3])
input10 = input("Answer 'a','b' or 'c': ")
elif dif == 3:
print(row[2] + "\n" + row[3] + "\n" + row[4])
input10 = input("Answer 'a','b','c' or 'd': ")
if input10 == row[dif + 2]:
print("Correct")
score = score + 1
w = w + 1
elif input10 != row[dif + 2]:
print("Incorrect")
w = w + 1
if w == 9:
print("Game over")
print("You got", r, "right out of 10")
break

Python - Boolean tested while loop is never ending

Hi I am trying to program a raspberry pi Sense hat that moves a pixel around the Matrix using the accelorometer. The idea is to get to the red area to win. If however it hits the green yellow or blue the game will end in a loss. When it finds one of the colours it is suppose to change the boolean varialb e(game_over) to True thus breaking the loop to stop the game.
The problem is when it reads that a colour was hit it changes the variable game_over to True, but then it some how changes back to False when it returns to the while loop. I have tested this using print statements to see what happens.
from sense_hat import SenseHat
from time import sleep
sense = SenseHat()
sense.clear()
r = [150,0,0]
g = [0,150,0]
j = [150,150,0]
b = [0,0,150]
e = [0,0,0]
w = [255,255,255]
v = [125,150,175]
x = 4
y = 4
maze = [[r,r,r,r,r,r,r,b],
[g,r,r,r,r,r,b,b],
[g,g,e,e,e,e,b,b],
[g,g,e,e,e,e,b,b],
[g,g,e,e,e,e,b,b],
[g,g,e,e,e,e,b,b],
[g,g,j,j,j,j,j,b],
[g,j,j,j,j,j,j,j]]
false = [
r,e,e,e,e,e,e,r,
e,r,e,e,e,e,r,e,
e,e,r,e,e,r,e,e,
e,e,e,r,r,e,e,e,
e,e,e,r,r,e,e,e,
e,e,r,e,e,r,e,e,
e,r,e,e,e,e,r,e,
r,e,e,e,e,e,e,r]
def move_marble(pitch,roll,x,y):
new_x = x
new_y = y
if 1 < pitch < 179 and x != 0:
new_x -= 1
elif 359 > pitch > 179 and x != 7 :
new_x += 1
if 1 < roll < 179 and y != 7:
new_y += 1
elif 359 > roll > 179 and y != 0 :
new_y -= 1
x,y = check_wall(x,y,new_x,new_y)
return x,y
def check_wall(x,y,new_x,new_y):
if maze[new_y][new_x] != v:
return new_x, new_y
elif maze[new_y][x] != v:
return x, new_y
elif maze[y][new_x] != v:
return new_x, y
return x,y
game_over = False
def check_win(x,y):
sleep(0.25)
if maze[y][x] == r:
sense.show_message('Vous avez gagner', scroll_speed=0.08)
sleep(1)
game_over = True
elif maze[y][x] == j:
sense.set_pixels(false)
game_over = True
sleep(1)
sense.show_message('Vous avez perdu', scroll_speed=0.08)
elif maze[y][x] == b:
sense.set_pixels(false)
game_over = True
sleep(1)
sense.show_message('Vous avez perdu', scroll_speed=0.08)
elif maze[y][x] == g:
sense.set_pixels(false)
game_over = True
sleep(1)
sense.show_message('Vous avez perdu', scroll_speed=0.08)
while game_over == False:
pitch = sense.get_orientation()['pitch']
roll = sense.get_orientation()['roll']
x,y = move_marble(pitch,roll,x,y)
check_win(x,y)
maze[y][x] = w
sense.set_pixels(sum(maze,[]))
sleep(0.1)
maze[y][x] = e
sense.clear()
I'm sure it is something small, I just can not seem to find it.

Resources