I have trouble with Python outputting "None" with every line of output - python

I am trying to make python cipher and decipher text with the Playfair method. But I hit a roadblock because it seems to output "None" with every line out output.
I'd be grateful if anyone tells me why it's doing so.
(This is my first post, so please bear with any mistakes I might have made).
My code:
def cip():
key=input(print("Please Enter Keyword: "))
return key
def inp():
c = int(input(print("1.Cipher text \n2.Exit\n\t>>")))
if c==1:
cip()
else:
exit
inp()
Output:
C:\Users\XYZ\Desktop\Code\Py programs>python -u "c:\Users\XYZ\Desktop\Code\Py programs\Playfair.py"
1.Cipher text
2.Exit
>>
None1
Please Enter Keyword:
NoneTron

The problem is your use of print() in the input() call.
c = int(input(print("1.Cipher text \n2.De-cipher text\n3.Exit\n\t>>")))
^^^^^
print() prints its argument, and returns None. input() uses the value of its argument as the prompt, so it's printing None as the prompt.
Just pass a prompt string to input(), don't call print()
c = int(input("1.Cipher text \n2.De-cipher text\n3.Exit\n\t>>"))

The problem is when you use input with print in it. Print should be outside.
def cip():
print("Please Enter Keyword: ")
key=input()
return key
def inp():
print("1.Cipher text \n2.De-cipher text\n3.Exit\n\t>>")
c = int(input())
if c==1:
cip()
elif c==2:
decip()
else:
exit
inp()
You could also put the string in input(), like this:
c = int(input("1.Cipher text \n2.De-cipher text\n3.Exit\n\t>>"))

Related

Remove prompt from console after user enters text with input() [duplicate]

This question already has answers here:
How to stop the input function from inserting a new line?
(9 answers)
Closed 4 years ago.
Is it possible to remove the prompt and the text that the user typed when using input()? I am using cmd on Windows 10 and would prefer a solution that works cross platform, but I don't really mind.
First attempt
Using the code:
user_input = input("Enter some text: ")
print("You just entered " + user_input)
produces:
Enter some text: hello
You just entered hello
but I would like:
Enter some text: hello
and then:
You just entered hello
Second attempt
I've used the getpass module, but that hides what the user is typing because it is designed for passwords. I looked at the code for getpass2 here and found that it uses the getch() function from msvcrt. I tried using a similar method, but it did not work. This code:
import msvcrt
prompt = "Enter some text: "
user_input = ""
print(prompt, end="\r")
current_character = ""
while current_character != "\r":
current_character = msvcrt.getch()
user_input += str(current_character, "utf8")
print(prompt + user_input, end="\r")
print("You entered" + user_input)
produces this output:
Enter some text: h e l l o
and then when I press enter:
nter some text: h e l l o
It also allows the user to use the backspace key to delete the prompt.
Third attempt
I know I can use os.system("cls") to clear everything in the console, but this removes text that was in the console before. For example, this code:
import os
print("foo")
user_input = input("Enter some text: ")
os.system("cls")
print("You just entered " + user_input)
removes the foo that was printed to the console before the input. If what I'm asking isn't directly possible, is there a workaround that can save the text in the console to a variable, and then after the user input clear the console and reprint the text that was in the console?
This is definitely not the optimal solution;
However, in response to
is there a workaround that can save the text in the console to a
variable
, you could keep appending the required text to a variable, and re-print that each time, as you suggested. Again, I would not recommend this as your actual implementation, but while we wait for someone to come along with the correct approach...
import os
to_print = ""
to_print += "foo" + "\n"
print(to_print)
user_input = input("Enter some text: ")
os.system("cls")
to_print += "You just entered " + user_input + "\n"
print(to_print)

Program won't run

I have this exercise and the first part of the program was running fine but I must've done something because now when I try to run it will just show None and and nothing seems to be 'wrong'. I don't know enough to even figure out what's wrong.
def main():
"""Gets the job done"""
#this program returns the value according to the colour
def re_start():
#do the work
return read_colour
def read_names():
"""prompt user for their name and returns in a space-separaded line"""
PROMPT_NAMES = input("Enter names: ")
users_names = '{}'.format(PROMPT_NAMES)
print (users_names)
return users_names
def read_colour():
"""prompt user for a colour letter if invalid colour enter retry"""
ALLOWED_COLOURS = ["whero",
"kowhai",
"kikorangi",
"parauri",
"kiwikiwi",
"karaka",
"waiporoporo",
"pango"]
PROMPT_COLOUR = input("Enter letter colour: ").casefold()
if PROMPT_COLOUR in ALLOWED_COLOURS:
return read_names()
else:
print("Invalid colour...")
print(*ALLOWED_COLOURS,sep='\n')
re_start()
main()
The only function you call is main(), but that has no statements in it, so your code will do nothing. To fix this, put some statements in your main() and rerun your code.

Continuous results from a single function call

I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...

python syntax for terminating a program when the user enters quit

Im trying to write a program that assigns an empty str to the variable myvar. then in a while loop the program asks for the user to type text, anything they want and it will print to the screen until the user enters the text quit which will end the loop and stop the program.
this is what I have
myvar = str("")
while myvar != "quit":
user_input = raw_input()
user_input = myvar
print myvar
Thanks.
how about
for output in iter(raw_input,"quit"):
print output
you're pretty close, but the indentation's off and the logic needs a slight tweak:
myvar = ""
while myvar != "quit":
myvar = raw_input()
print myvar
note that this will also print "quit". I'll leave that as a final exercise to you to figure out how to cut that out.

Python (latest version) Syntax Error

I wrote this sample program that is meant to open a text file (database1.txt) from the computer, and display the results that are currently in the file. Then prompt the use if their name is in the document, if it is it should print the contents of the text file then close, otherwise it should prompt the user to enter their first name, then the program writes the name into the same text document, then prints the contents of the text file again so that the user can see the new added data. I have typed the code, and somehow it keeps saying I have a syntax error. I checked a few times and I cannot fix the error. I was wondering if someone could take a look and if they might be able to explain the error to me. Thank you
#This program reads/writes information from/to the database1.txt file
def database_1_reader ():
print('Opening database1.txt')
f = open('database1.txt', 'r+')
data = f.read()
print data
print('Is your name in this document? ')
userInput = input('For Yes type yes or y. For No type no or n ').lower()
if userInput == "no" or userInput == "n"
newData = input('Please type only your First Name. ')
f.write(newData)
f = open ('database1.txt', 'r+')
newReadData = f.read()
print newReadData
f.close()
elif userInput == "yes" or userInput == "ye" or userInput == "y"
print data
f.close()
else:
print("You b00n!, You did not make a valid selection, try again ")
f.close()
input("Presss any key to exit the program")
database_1_reader()
print is a function in py3.x:
print newReadData
should be :
print (newReadData)
Demo:
>>> print "foo"
File "<ipython-input-1-45585431d0ef>", line 1
print "foo"
^
SyntaxError: invalid syntax
>>> print ("foo")
foo
statements like this:
elif userInput == "yes" or userInput == "ye" or userInput == "y"
can be reduced to :
elif userInput in "yes"

Categories

Resources