I'm making a curency converter, time converter and weather app for an year 12 computer sciences project. Im unable to interrupt the loop that is being used for the main menu/location selector.
Can anyone help?
The code is below.
##This program is intended to help travellers with date and currency conversions ##
##Changelog----->##
##V1 - Include code for Forex Converter, code modified from - https://www.w3schools.in/python/examples/real-time-currency-converter##
##V2 - Implement GUI##
##V2.1 - Implement Multiple Screens GUI##
##V3 - Remove all GUI aspects##
##V3.1 - Create initial loop##
##Import Modules##
from forex_python.converter import CurrencyRates
import time
import datetime
import python_weather
import asyncio
##Opening info##
##V3.1##
global enter
enter = 'GO'
while enter == 'GO':
print("========================================================================================================================================================================================")
print("")
print("Welcome to the Traveller Assisstant. This program is able to help you with currency conversions, date and time conversions and viewing weather details of your destination.")
print("")
print("========================================================================================================================================================================================")
time.sleep(2.5)
ori = str(input("Please enter your current country: "))
dest = str(input("Please enter your destination country: "))
time.sleep(5)
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
if check == 'YES':
enter = 'STOP'
elif check == 'NO':
print("Returning to Location Selector")
enter = 'GO'
##V1##
##Change Currency##
#cr = CurrencyRates()
#output = cr.convert(entry1, entry2, entry3)
#final = round(output, 2)
#print("THE FINAL AMOUNT IS:", final, c2)
A simple typo, that's all that was wrong.
In this line of code:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
You are attempting to use the method
.upper()
But your fatal flaw is that you forgot the parentheses.
I changed this:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
To this:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper()
And the code worked perfectly for me
EXPLANATION
In the original code, check could never be equal to 'YES' or 'NO', because of the typo;
.upper was never recognized as a strings' function and returned with this value:
<built-in method upper of str object at 0x105fec130>
.upper() on the other IS in fact a valid function for a string and returned with this value when it was supplied with the input of 'yes':
YES
If you need to exit from the loop when a condition is met you can achieve that easily by using break. So when your condition is met:
either add bellow enter = "STOP" the statement break or just replace enter = "STOP" for break
if check == 'YES':
enter = "STOP"
break
or
if check == 'YES':
break
both should work, I guess you could go with the first answer if you need to keep the state of the variable enter otherwise you could just use the second.
The problem with your original code is that you are missing a parenthesis on the declaration of the upper method in this line:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
instead it should be:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper()
if you don't add the parenthesis to upper() it means you are declaring the object method itself not triggering instead what the method actually does. (In this case making the string uppercase)
i am trying to make a simple login system for python. i tried several things using break,return. but i cant get pass the login system using the second line in the text file onwards. i can only login through the first line of the text file, i took the code fro an other question but didnt know how to get it to work so i tried to change it so i could understand how it can work. I am extremely new to python. please let me know where i got wrong and how i can change it to get it to work!
format for user.txt is
first name|last name|occupation|id|username|password
John|goh|worker|1|admin|1234
import datetime
def check():
x = 0
users = open("users.txt").read().split("\n")
for i in range(len(users)): users[i] = users[i].split("|")
while (x < 3):
username = str(input("Username: \n"))
password = str(input("Password: \n"))
f = open('project_AI.txt', 'a')
f.write(str(datetime.now()))
f.write('\n' + username + '\n')
f.write(password + '\n')
f.close()
for user in users:
uname = user[4]
pword = user[5]
if uname == username and pword == password:
print("Hello " + user[1] + ".")
print("You are logged in as: " + user[2] + '.')
x += 3
else:
print('error')
check()
x += 1
return
check()
many thanks!!
I think the "return" in the penultimate line is at the wrong indentation, and isn't really needed at all.
As soon as python touches a return, it instantly destroys the function. In your code, after every user it checks, it hits the return. Meaning it will never even reach the second user.
You also want to not use check() within the function, as it will create a clone of itself within itself. The while x < 3 will go through the logic multiple times for you.
import datetime
def check():
x = 0
users = open("users.txt").read().split("\n")
for i in range(len(users)): users[i] = users[i].split("|")
while (x < 3):
username = str(input("Username: \n"))
password = str(input("Password: \n"))
f = open('project_AI.txt', 'a')
f.write(str(datetime.now()))
f.write('\n' + username + '\n')
f.write(password + '\n')
f.close()
for user in users:
uname = user[4]
pword = user[5]
if uname == username and pword == password:
print("Hello " + user[1] + ".")
print("You are logged in as: " + user[2] + '.')
x += 3
return
print('error')
x += 1
check()
So I have a multilayered problem. I am trying to I am trying to just print out 'input was jack' if the raw_input was 'jack' and also subtract 'tries' by 1, and then run the function again and print out amount of 'tries' at the end of both the first 'if' statement and the 'else' statement, and if the raw_input wasn't 'jack' it adds 1 to 'tries' and if 'tries' reaches a total of 4 the function prints stop. I have run into a couple of different problems. Either the counter seems to reset every single time so it's always just '1' or I can't just keep running the function. It just doesn't seem like it's following the 'if or else' theory I thought it would be. So I have the following code:
tries = 0
def usrinfo():
name = raw_input('input name ')
a = ('jill','jack',name,'meg')
for element in a:
if element == 'jack':
print('input was jack')
tries =-1
print(tries)
usrinfo()
else:
if element != 'jack':
tries =+ 1
return tries
print(tries)
usrinfo()
if tries == 4:
print('stopped')
usrinfo()
If I type 'jack' I get:
Nothing...as in a blank output
I want:
input was jack
-1
Then I want the function to run again...and get
input was jack
-2
And so on.
If I type anything other than 'jack' I get:
Nothing...as in a blank output
I want to get:
1
Then for the function to run again....and get
2
Then if I type anything other than 'jack'. I want with each attempt to print the increasing level of tries from 1 - 4 such as below:
1
2
3
4
Then when it reaches 4 it prints 'stopped' or runs whatever command. I want to essentially keep the code running and control the value of 'tries' according to whether or not the input is 'jack' or something else. Because even when I create an even simpler code like this:
def userinput():
tries = 0
username = raw_input('input username ')
if username == 'jack':
tries -=1
print(username + ' '+ str(tries) + ' success')
userinput()
else:
if username != 'jack':
tries +=1
print('tries ' + str(tries))
userinput()
userinput()
My results on this code with input of 'f' are:
input username f
tries 1
input username f
tries 1
input username f
Instead I want to get:
input username f
tries 1
input username f
tries 2
input username f
tries 3
And with input of 'jack' I want:
input username jack
jack -1 success
input username jack
jack -2 success
input username jack
jack -3 success
input username jack
jack -4 success
And so on. Any help is much appreciated. I'm not sure what I'm doing wrong. It just seems like 'tries' is constantly resetting itself.
Hopefully this is clear...I've spent a lot of time trying to make code just to be able to demonstrate to someone with more knowledge where my misunderstanding might be...
Thanks guys and gals.
Here's what I came up with, no loops required
#!python3
from os import sys
def usrinfo(tries):
name = input('input name: ')
if tries == 4:
print('end of program because tries equals 4')
sys.exit()
elif name == 'jack':
tries -= 1
print('input was jack')
print('tries ' + str(tries) + '\n')
usrinfo(tries)
elif name != 'jack':
tries += 1
print('tries ' + str(tries) + '\n')
usrinfo(tries)
usrinfo(0) # 'tries' will be initialized to zero
When you are taking user input it is stored in the name variable so you need to do if with 'name' not 'element'. Secondly call the function after you have checked the condition
if tries == 4:
print('stopped')
return
usrinfo()
Here is the correct code:
tries = 0
def usrinfo():
global tries
name = raw_input('input name ')
a = ('jill','jack','meg')
#to check the input against the strings of list a go for
#if name in a:
if name == 'jack':
print('input was jack')
tries =-1
print(tries)
usrinfo()
else:
tries+=1
print(tries)
if tries == 4:
print('stopped')
return
usrinfo()
usrinfo()
I am needing a bit of help on my encryption program. Instead of having the program just move the letters by two (c would become a or r would become p) I'd like to be able to have it reference 2 lists, the first one going from a-z normally and the other with letters in different order to act as the encrypt/decrypt side. Hopefully that makes sense. Here's what i have so far.
result = ''
choice = ''
message = ''
while choice != 0:
choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if choice == '1':
message = input('\nEnter message for encryption: ')
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - 2)
print(result + '\n\n')
result = ''
if choice == '2':
message = input('\nEnter message to decrypt: ')
for i in range(0, len(message)):
result = result + chr(ord(message[i]) + 2)
print(result + '\n\n')
result = ''
elif choice != '0':
print('You have entered an invalid input, please try again. \n\n')
This works fine and dandy but i'd like to have the lists. Lets say list 1 is A,B,C,D,E and list 2 would be W,N,U,D,P. just for ease of use purposes.
Here is a solution, for small letters only. It can easily be modified to handle also capital letters, by adding them to the text strings.
As can be seen, the space character is at the same position in both lists. This is not necessary, as any character can be translated to any other. However if the decrypted or encrypted is not containing unique characters only, the program will break down.
decrypted = b"abcdefghijklmnopqrstuvwxyz "
encrypted = b"qwertyuiopasdfghjklzxcvbnm "
encrypt_table = bytes.maketrans(decrypted, encrypted)
decrypt_table = bytes.maketrans(encrypted, decrypted)
result = ''
choice = ''
message = ''
while choice != '0':
choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if choice == '1':
message = input('\nEnter message for encryption: ')
result = message.translate(encrypt_table)
print(result + '\n\n')
elif choice == '2':
message = input('\nEnter message to decrypt: ')
result = message.translate(decrypt_table)
print(result + '\n\n')
elif choice != '0':
print('You have entered an invalid input, please try again. \n\n')
Ok, so a few things here...
First I'll give you exactly what you were looking for and explain what I used and some of the changes that needed to be made to your original code. Then I'll explain some inherent issues what what you're trying to do and suggest some areas to read up on/some ways you might want to improve what you've got.
Here's the code you're looking for (while retaining the same flow as what you submitted put above):
import random
result = ''
choice = ''
message = ''
characters_in_order = [chr(x) for x in range(32,127)]
while choice != 0:
choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if str(choice) == '1':
message = input('\nEnter message for encryption: ')
r_seed = input('Enter an integer to use as a seed: ')
random.seed(r_seed)
shuffled_list = [chr(x) for x in range(32,127)]
random.shuffle(shuffled_list)
for i in range(0, len(message)):
result += shuffled_list[characters_in_order.index(message[i])]
print(result + '\n\n')
result = ''
elif str(choice) == '2':
message = input('\nEnter message to decrypt: ')
r_seed = input('Enter an integer to use as a seed (should be the same one used to encrypt): ')
random.seed(r_seed)
shuffled_list = [chr(x) for x in range(32,127)]
random.shuffle(shuffled_list)
for i in range(0, len(message)):
result += characters_in_order[shuffled_list.index(message[i])]
print(result + '\n\n')
result = ''
elif str(choice) != '0':
print('You have entered an invalid input, please try again. \n\n')
You'll notice that I set a global 'characters in order' list, which is just every ASCII character (32-126) in order. I also imported the 'random' module and used this to shuffle the characters in order according to a seed that the user inputs. As long as this seed is the same on the encryption and decryption end, it will produce the same shuffled list and it should work to encrypt or decipher the same string. Also notice the str() around your input choices. Without that, the user had to input '1', rather than 1 to submit a choice without an error.
All of that said...
Notice that the way the new function works is by looking at a character's index in one list and pulling out the character at that index in another. The method you were using, of incrementing or decrementing a character's ASCII code is basic (though not much more basic than this), but it also has a pretty critical flaw, which is that characters on one end or another of the ASCII set wouldn't return ASCII characters. If you were encrypting it at a bit-level, which would be preferred, this wouldn't matter/would be irrelevant, but here you're not going to get the kind of string back that you want if you were to, for example, enter a [space] (ASCII 32) into your plaintext to be encrypted.
If you're interested, you might want to read up on symmetric key encryption/DES for some ideas on how encryption is really done, though props on the start/interest and this can certainly be a fun way to create some sort of cryptogram puzzle or something along those lines. I won't pretend to be any kind of expert, but I can at least point you in the write direction. (https://en.wikipedia.org/wiki/Data_Encryption_Standard https://en.wikipedia.org/wiki/Symmetric-key_algorithm)
Consider having your code read in a .txt file and print out to a .txt file, rather than using user input for the message.
Again, I'm not an expert by any means and there are definitely some fun uses of the kind of program you're aiming for, just trying to point you in the right direction if this is something that you're interested in. Hope all of that is helpful!
Here is my solution. It uses a randomizer to encrypt the file by assigning a ASCII value to the plain text and randomly shifts it around.
from random import randint
import sys
def menu():
input1=int(input(""" please select what you want to do:
1.Encrypt
2.Decrypt
3.Extended Encryption
4.exit
"""))#menu to choose what you want to do
if input1==1:
encrypt() #takes you to the encrypt function
elif input1==2:
decrypt()#takes you to the decrypt function
elif input1==3:
enxtended()#takes you to the extended encryption function
elif input1==4:
sys.exit #exits the program
else:
print("invalid entry try again")
menu()
def encrypt():
file_name=str(input("please enter the name of the file that you want to open\n"))
try:
text_file=open(file_name + ".txt","r")#puts the text file into read
text_file=text_file.read()#reads the text file
print(text_file)#prints the strings in the document
except:
print("error try again")
encrypt()
random(text_file)
def random(text_file):
list1=("")#creates blank string
for x in range (0,8):
num=(randint(33,126))#generates a random number between33 and 126
ascii1=chr(num) #converts it into an ascii character
list1=list1+ascii1#adds the ascii character to the blank string list1
print (f"your 8 key code is {list1}") #prints 8 character code
offset(list1,text_file)
def offset(list1,text_file):
total=0
for x in range (8,):
total=total+ord(list1[x]) #turns each character into an ascii value
total=total/8 #divides it by
total=round(total,0)#rounds it to 0 decimel places
print(total)
total=total-32#minuses 32 from total
print(f"your offset factor is {total}")
encrypting(total,text_file)
def encrypting(total,text_file):
length=len(text_file)
string1=("")
for x in range (length,):
numascii=ord(text_file[x])#turns the characters into its ascii value
numascii=int(numascii)#makes sure they are integers
if numascii==32:
letter=chr(32)#converts spaces back into spaces
string1=string1+letter#adds space to thestring
else:
numascii1=numascii+total#adds the character value to the offset factor
numascii1=int(numascii1)#makes sure it is an integer
if numascii1>126:# if the ascii value is great then 126
numascii1=numascii1-94#minus 94 from it
letter=chr(numascii1)#turn it into a character
string1=string1+letter#add it to the string
else:
letter=chr(numascii1)#turn the ascii value into a character
string1=string1+letter#add it to the string
print(f"your encrypted file is {string1}")
savefile(string1)
menu()
I have written separate programs for encryption and decryption. Both of these use file manipulation techniques. Use the username 'eggs' and password 'chicks' so that not anyone can see my secret code. I have used hashlib for more security. Just change the User 'Soumajit' to your respective Username to make it work. The first one is encryption and the next one is for decryption.
#ENCRYPTION
from time import sleep
import subprocess
import hashlib
def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)
def en():
alphabet = "abcdefghijklmnopqsrtuwvxyzABCDEFGHIJKLMNOPQSRTUVWXYZ,./?:;!##$%_&* ()`-+=1234567890"
encrypt = ""
decrypt = ""
print
print "Type y for yes and anything else for no"
start = raw_input("Do you want to import file from desktop? ")
if start == "y":
Open = raw_input("Enter the .txt file you want to open in desktop: ")
a = open("C://Users//Soumajit//Desktop//" + Open + ".txt", "r")
print
x = (a.read())
copy2clip(x)
a.close()
print "Right click and select paste below to encrypt"
print
message = raw_input()
for i in message:
x = alphabet.find(i)
new = (x - 5) % 74
encrypt += alphabet[new]
e2 = encrypt[::-1]
else:
print "Type your message below"
message = raw_input("")
for i in message:
x = alphabet.find(i)
new = (x - 5) % 74
encrypt += alphabet[new]
e2 = encrypt[::-1]
print
a = raw_input("By what name do you want to save it?: ")
file = open(a + ".txt", 'wb')
file.write(e2)
file.close()
copy = raw_input("Do you want to copy your file? ")
if copy == 'y':
copy2clip(e2)
print 'Your encrypted file has been copied to the clipboard'
else:
print "Your encrypted file has been saved with the name " + str(a) + " in desktop"
print "To decrypt it, use my other program"
sleep(3)
u = 'e415bf03b4d860dccba57cea46371f831d772ba1deca47f28fa7d1f7'
p = 'c35f7f79dc34a678beb2b4106c84c9963561e7c64bc170e50c429b9a'
ur = raw_input('Enter your username: ')
ur1 = hashlib.sha224(ur).hexdigest()
pr = raw_input('Enter your password: ')
pr1 = hashlib.sha224(pr).hexdigest()
if ur1 == u and pr1 == p:
print 'Access granted'
sleep(1)
en()
else:
print "Incorrect username or password"
sleep(1)
#DECRYPTION
from time import sleep
import subprocess
import hashlib
def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)
def de():
print "Type y for yes and anything else for no"
start = raw_input("Do you want to import file from desktop? ")
if start == "y":
Open = raw_input("Enter the .txt file you want to open from folder: ")
a = open("C://Users//Soumajit//Desktop//" + Open + ".txt", "r")
x = (a.read())
#print x
copy2clip(x)
print "Right click and select paste below to decrypt"
print
message = raw_input()
a.close()
alphabet = "abcdefghijklmnopqsrtuwvxyzABCDEFGHIJKLMNOPQSRTUVWXYZ,./?:;!##$%_&*()`-+=1234567890"
decrypt = ''
for i in message:
x = alphabet.find(i)
new = (x + 5) % 74
decrypt += alphabet[new]
d2 = decrypt[::-1]
d3 = d2.replace("`", " ")
final = d3.replace("2", " ")
print
print final
else:
print "Type or paste your encrypted text below"
print
message = raw_input()
alphabet = "abcdefghijklmnopqsrtuwvxyzABCDEFGHIJKLMNOPQSRTUVWXYZ,./?:;!##$%_&*()`-+=1234567890"
decrypt = ''
for i in message:
x = alphabet.find(i)
new = (x + 5) % 74
decrypt += alphabet[new]
d2 = decrypt[::-1]
d3 = d2.replace("`", " ")
final = d3.replace("2", " ")
print
print final
u = 'e415bf03b4d860dccba57cea46371f831d772ba1deca47f28fa7d1f7'
p = 'c35f7f79dc34a678beb2b4106c84c9963561e7c64bc170e50c429b9a'
ur = raw_input('Enter your username: ')
ur1 = hashlib.sha224(ur).hexdigest()
pr = raw_input('Enter your password: ')
pr1 = hashlib.sha224(pr).hexdigest()
if ur1 == u and pr1 == p:
print 'Access granted'
sleep(1)
de()
print
end = raw_input('press q to quit: ')
while end != 'q':
print 'You did not type q'
end = raw_input('press q to quit: ')
if end == 'q':
quit()
else:
print 'Incorrect username or password'
sleep(1)
quit()
The code below works fine, however the message prints onto separate lines once it has been encrypted. For example if I type: abc with the shift of 1 it encrypts it but prints it back as:
b
c
d
And I don't understand why. I want it to print as:
bcd
Here is the code:
print("Welcome to the Code-Breaking/Making Software")
print("This program uses something called a Caesar Cipher.")
Message = (input("Please enter the message you wish to Encrypt >> "))
Shift = int(input("Please enter the shift for your message >> "))
for x in Message:
OrdMessage = ord(x)
ShiftedMessage = OrdMessage + Shift
NewMessage = chr(ShiftedMessage)
NewMessageList = list(NewMessage)
print("".join(NewMessageList))
Indentation matters and you shouldn't create new list of NewMessage everytime
print("Welcome to the Code-Breaking/Making Software")
print("This program uses something called a Caesar Cipher.")
Message = (input("Please enter the message you wish to Encrypt >> "))
Shift = int(input("Please enter the shift for your message >> "))
NewMessageList = []
for x in Message:
OrdMessage = ord(x)
ShiftedMessage = OrdMessage + Shift
NewMessage = chr(ShiftedMessage)
NewMessageList.append(NewMessage)
print("".join(NewMessageList))
you should change the following part;
print("".join(NewMessageList), end="")
What happening was is that for each charachter it was running the loop and printing the answer, now I have collected all the encrypted letter and clubbed them as one in the end and printed it.
it at first initialize an empty list with NewMessage = [] and then for every letter that we get encrypted it adds to that empty list using .append() and at end print all by ''.join(NewMessage)
print("Welcome to the Code-Breaking/Making Software")
print("This program uses something called a Caesar Cipher.")
Message = (input("Please enter the message you wish to Encrypt >> "))
Shift = int(input("Please enter the shift for your message >> "))
NewMessage = []
for x in Message:
OrdMessage = ord(x)
ShiftedMessage = OrdMessage + Shift
NewMessage.append(chr(ShiftedMessage))
print(''.join(NewMessage))