Reading input from Python and print out in while loop - python

I wonder how I can translate the following C++ code to Python code.
int n;
while (cin >> n)
cout << n <<endl;
My guess is it would be something like this
import sys
while n = raw_input():
print n + "\n"
but it doesn't work... Please help me. Thank you.

perhaps something like this:
import sys # why?
n = "string"
while n:
n = raw_input()
print n + '\n'
However
while n = raw_input(): # incorrect.
This won't work because:
n is not defined
In any case, to test equality you should generally use ==, though not in this particular case, as it would mean basically, while n is equal to empty string( '' )
example:
>>> raw_input() == ''
True

That's because n = raw_input() in Python does not return a value whereas cin >> n in C++ does. (This saves the programmers from the most common error of replacing == with =)
You can try something like.
n = raw_input("Enter Something: ")
while n:
print n
n = raw_input("Enter Something: ")
Test Run :
>>>
Enter Something: Monty
Monty
Enter Something: Python
Python
Enter Something: Empty Line Next
Empty Line Next
Enter Something:
P.S- There's no need of the import sys in this case (if you're not using it anywhere else in your code). Also, print statement automatically moves the cursor to the next line, so you need not add \n in this case.

Related

How to get next n[0:1] letter after each loop cycle in Python?

i got this python script:
The problem is i would like this loop to repeat but each time, it checks the next letter of the input, so loop1: n[0:1] loop2: n[1:2] and so on...
import time
while True:
n = input("Ltr:")
h = n[0:1]
if h==' ':
print(" ")
time.sleep(0.001)
if h=='a':
print("01100001")
time.sleep(0.001)
if h=='b':
print("01100010")
time.sleep(0.001)
if h=='c':
print("01100011")
time.sleep(0.001)
if h=='d':
print("01100100")
time.sleep(0.001)
So it basically goes on from a to z, also counts spaces and only supports lowercase letters.
If you already got it, it's an english-to-binary translator i'm trying to make, i dont want to import anything like plusgins and stuff, i want t make it by myself but i struggling with this... :(
Is there anyway to make it work ?
As explained here you can simply do the following:
test = input("enter text")
res = ''.join(format(ord(i), '08b') for i in test)
and res will contain your converted text.
If you are insisting on iterating through the string you can do the following:
string = input("enter string")
res = ''
for char in string:
res += format(ord(char), '08b')

How can I translate words with a python script?

So we have to translate numbers from English to German. I feel I am doing it all wrong because I get no
output when I test my code.
#!/usr/bin/env python3
import sys
english = sys.stdin.read().split()
num = {}
with open("translation.txt") as f:
data = f.read().split("\n")
i = 0
while len(data[i]) < 0:
n = data[i].split()
n1 = n[0]
n2 = n[1]
if n1 not in num:
num[n1] = n2
i = i + 1
i = 0
while i < len(english):
n = english[i]
if n in num:
print(num[n])
i = i + 1
Please help. Am I even getting the code to open the text file? the text file contains numbers translated from English to German
Example of translation.txt
one: eins
two: zwei
three: drei
four: vier
five: funf
six: sechs
seven: sieben
eight: acht
nine: neun
ten: zehn
Well, your code had some major logical errors. First of all, a comparison was wrong for the loops. You also split the line but you left : in the keys. Also checking if the word already exists is not necessary, but I left it as you wrote. I also added two side translation just in case you will need it.
Here is my implementation of the problem:
#!/usr/bin/env python3
import sys
english = sys.stdin.read().split()
num = {}
with open("translation.txt") as f:
data = f.read().split("\n")
i = 0
while i < len(data):
n = data[i].split()
print(n)
n1 = n[0].replace(':', '')
n2 = n[1]
if n1 not in num and n2 not in num:
num[n1] = n2
num[n2] = n1
i = i + 1
print(num['one'])
print(num['eins'])
You read inputs from standard input via sys.stdin.read(). This requires reading ALL characters until an EOF is met, which would happen only if:
An EOF is entered via the keyboard (Ctrl-D for Unix-based systems and Ctrl-Z for Windows);
The input is redirected from another stream that ends with an EOF, such as a file stream.
If the input is entered line by line via the keyboard, the output won't be seen until an EOF is seen. If it is desired that the output is shown immediately after one line of input, input() should be used instead of sys.stdin.read().
Other issues have been explained in #Raguel's answer.
Here we have a major issue with application logic, as were mentioned in previous answers:
First of all, we need to load dictionary - our resource to operate.
Second, we can start the translation, for example word-by-word from continues user input
The compact solution (require python 3.8):
#!/usr/bin/env python3
with open("translation.txt", "r") as f:
dictionary = { k: v.strip() for k, v in [line.split(":") for line in f.readlines()]}
while word:=input("Word to translate: "):
try:
print(dictionary[word])
except KeyError:
print(f"No translation found for the word: {word}")

How to send EOF indicator in console

For example, in C# Visual Studio if I input key combination Ctrl + Z it sends null to program and i use it in sentinel controlled loops for example in C#:
int total = 0;
string myInput = Console.ReadLine();
while (myInput != null)
{
total++;
myInput = Console.ReadLine();
}
Console.WriteLine(total);
Does this exist in python?
The easiest way of doing this in Python is to iterate over the input:
import sys
total = 0
for line in sys.stdin:
total += 1
print(total)
Or, if you really only want to count lines, you can write this shorter as
import sys
print(sum(1 for _ in sys.stdin))
This is using a so-called generator expression.
We can control it by EOF error exception, Simply type Ctrl + Z.
s = input()
i = 0
try:
while (True):
i += 1
s = input()
except EOFError:
print(i)

using raw_input in a while loop and assigning it to a variable?

is42= False
while(raw_input()):
d = _
if d == 42:
is42 = True
if not is42:
print d
for this python block of code I want to use outside of the interactive prompt mode. So I can't use _ as the last output. How do I assign raw_input to a variable? I'm doing an exercise off a site. about 5 values is the input and I'm suppose to spit some output out for each corresponding input value. What's the best way to take in this input to do that?
This appears to be very inefficient logic. Do you really need the is42 status flag as well? If not, you might want something like
stuff = raw_input()
while stuff:
if stuff != "42":
print stuff
stuff = raw_input()
Does that fix enough of your troubles?
Hi and welcome to Python!
The raw_input() function returns the input read as a string. So where you have d = _, you can replace that with d = raw_input(). A question I have for you is why you had it inside the while condition? If you wanted it to keep asking the user for a number over and over, then replace while(raw_input()): with while True:.
One more thing, raw_input() always returns a string. So if you run print '30' == 30, you'll see that a string representation of 30 is not equal to the number representation of 30. But that's not a problem! You can turn the return value of raw_input() into an integer type by replacing d = raw_input() with d = int(raw_input()).
Now there will be another problem when the user gives you an input that can't be converted to an integer, but handling that can be an exercise for you. :)
Final code:
is42= False
while True:
d = int(raw_input())
if d == 42:
is42 = True
if not is42:
print d
is42=False
while(!is42):
d = int(raw_input("Enter a number: "))
is42 = d==42
print "d = ", d
That should do it if I understand the requirements of your problem correctly.

if statement not executing in while loop

I have to write a program that gets multiple strings one after the other that is terminated by the sentinel DONE, and then print this list of strings right justified to the length of the biggest string. Here is my code:
user = input("Enter strings (end with DONE):\n")
totalString = ""
while True:
if user.lower() == 'done':
break
else:
totalString = totalString + user + " "
user = input("")
lst = totalString.split(" ")
max = 0
for i in range(len(lst)):
if len(lst[i]) > max:
max = len(lst[i])
for i in range(len(lst)):
print("{:>{derp}}".format(lst[i],derp=max))
The issue I'm having is that the if statement in the while loop never executes, so it just gets stuck in that loop.
NB: Assumes that code was for Python 2.x, which might not be a case.
Firstly with input(), you are expecting a numeric value and not a string.
Just changing your input() to raw_input() did the trick for me.
As pointed in the comment, maybe the OP is using Python 3.
This question on SO explains the differences in Python 2.x and 3.x wrt input() and raw_input().
As you're using cmd to run your code so the string returned by input contains a return character(\r) as well.
So when the user enters "done", input() actually returns "done\r".
A simple solution is to use str.strip here:
user = input("").strip("\r")

Categories