Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
Consider the following code:
code = input()
eval(code)
If I run it and type
> print(10)
It will get executed and print "10"
My question is when the code needs an indent, such as:
> for i in range(10):
> print(i)
How can I receive this code with input() (notice that I have to keep the indent) so that I can use eval() to run it?
If i understand correctly you want to be able to get python code using input() with tabs included.
the post
How to read multiple lines of raw input? tells us that we can get multiline input with
code = '\n'.join(iter(input, ''))
But after trying that myself I noticed that exec(code) didn't work because tabs were omitted from the input.
So here's a function that reads character directly and stops when it reads a given string
(here it's 2 newlines so you have to press ENTER twice to stop)
import sys
def input_until(sentinel):
text = ""
while not text.endswith(sentinel):
text += sys.stdin.read(1) # read 1 character from stdin
# remove the stop string from the result
return text[:-len(sentinel)]
code = input_until("\n\n")
exec(code)
I've tested it on https://replit.com/languages/python3 and it seems to work !
What's your use case here?
If you want to run the string in eval(), do you consider this?
new_string_name = "for i in range(10):\n eval(a)"
or
new_string_name = " eval()"
But if you don't want to follow the indentation rules (4 characters, no tabs), you can use
new_string_name = "for i in range(10):\n\teval(a)"
or
new_string_name = "\teval(a)"
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
It seems that both print and return can display the output.
The only difference I found between is that return displays even quotation marks, whereas print doesn't.
How about using together?:
return print("Hello")
What is the most common and efficient way to display the output in a function(maybe the last line)?
Are there any changes to the flowchart between return and print?
return certainly does not display output. It returns output from a function. If you happen to call a function in a python shell, you will get the output printed to the terminal, but this is incidental---it is because the python shell is a REPL: a Read Eval Print Loop. So it reads what you type, evaluates it (i.e. runs it), and then prints whatever is left.
Thus print is for printing to stdout. return is for getting values back from functions.
But I can see how one might get confused playing about in a REPL.
(Try just typing return 7 in a python REPL to see why you can't use return as a print replacement, even in a REPL.)
return - Returns a value so that it can be stored in a variable.
print - prints values to the stdout.
fu():
x = 1
print(x)
y = fu()
y is None
fu():
x = 1
return x
y = fu()
y is 1
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Currently I am learning Python from the book 'The Coders Apprentice' and I have stumbled upon an exercise which I have the feeling that I have nearly solved, but I get an error when I execute the program.
This is the exercise:
Write a program that takes a string and produces a new string that contains the exact characters that the first string contains, but in order of their ASCII-codes.
For instance, the string "Hello, world!" should be turned into " !,Hdellloorw". This is
relatively easy to do with list functions, which will be introduced in a future chapter, but for now try to do it with string manipulation functions alone.
I have added the code below and the error message as a picture.
from pcinput import getString
entString=getString("Enter your string here: ")
yourString=entString.strip()
def positioner(oldPosition):
newPosition=0
x=0
while x<len(yourString):
if ord(yourString[oldPosition])>ord(yourString[x]):
newPosition+=1
x+=1
return newPosition
i=0
y=0
newString=""
while y<len(yourString):
if positioner(i)==y:
newString+=yourString[i]
y+=1
elif positioner(i)<y:
newString+=yourString[i]
if i<len(yourString):
i+=1
else:
i=0
print(newString)
What have I done wrong? I am new to programming.
You are getting an index error because the line if positioner(i)==y: is being called with a value of i equal to the length of yourString. yourString[oldPosition] is then accessing an index which doesn't exist.
This is happening because the loop condition (y<len(yourString)) isn't doing any checking on the value of i, which is the one causing problems.
Some other quick comments:
You can use yourString = input("Enter your string here: ") to replace the first four lines, as I'm not sure what pcinput is - and couldn't find any packages of the same name.
Instead of using the while/x+=1 construct, you could instead use a for x in range(len(yourString)), which is a little neater.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I understand that \n in Python 3.x begins a newline in a string.
But in this exemplar case:
answer = int(input("What's 7 x 3?\n"))
if answer == 21:
print("That's correct.")
else:
print("That's incorrect.")
should it be used and why? Also, in what other situations would \n be used?
\n is the standard newline character across most operating systems. In python, as well as most other programming languages, \n is used to start a newline whether you are aware of it or not. In python for example
print "hello world"
actually appends a newline character to the string in question and prints it.
print "hello world\n",
will yield the same exact output as the "," prevents the newline character from being added. In python there are very few reasons to use \n as it is generally added for you. The two main cases where one is explicitly interesting in the newline character is:
Writing to files
Removing newlines when reading from files
When writing to a file, one needs to explicitly use \n to generate newlines in the file. For example:
with open("example.txt","w") as fout:
fout.write("hello world\n")
and when reading in from a file:
with open("example.txt","r") as fin:
for line in fin:
print line.rstrip("\n")
If you want your terminal session with the program to look like:
What's 7 x 3?
21
That's correct.
then you should put the newline as you have. If you want it to look like:
What's 7 x 3? 21
That's correct.
then you should put a space at the end of the prompt instead of newline:
answer = int(input("What's 7 x 3? "))
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Suppose that I would like my python program to accept 2 positional arguments:
1. The path to an input file
2.The path to a word dictionary, which is also a txt file.
Can anyone teach me how to go about doing that?
import sys
print('Name of the script: {0}'.format(sys.argv[0]))
if len(sys.argv) == 3:
inputfile_path = sys.argv[1]
dictionary_path = sys.argv[2]
print('First parameter: {0}'.format(inputfile_path))
print('Second parameter: {0}'.format(dictionary_path))
https://docs.python.org/2/library/sys.html
Your question is a bit vague so I'm just going to answer what I think you meant.
I'll assume that you have a function as such:
def function(string1, string2):
''' string 1 and string2 are paths to an input file and a dictionary respectively'''
Now in general to read a file you use:
file1 = open(string1,'r')
# After opening the file you loop over lines to do what you need to.
for line in file:
# Do what you need to
I'm not sure what you want to do with the input file so I'm going to leave it at that.
To load a dictionary from a string we use the eval() function. It actually runs a string. Now each line in the dictionary stored as a text file is a string so all you have to do is loop through the entire file (using the for line in file method from before) and run eval to get back a dictionary.
For example try this simple code:
#assume string2 is what you get back from the looping
string2 = str({'jack': 4098, 'sape': 4139})
dic = eval(string2)
print dic
Hopefully I've pointed you in the right direction. Since I'm not sure what exactly you need to do, I can't really help you more.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm working in a program that needs to compare strings that have about 900 digits.
But whenever I enter them as
a = '01111111111111100000000000111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111010101000000000000000000000000000000011111111111111111111111111111111111111100000000000000000000000000000000000000000000111111111111111111111111111100001010101000010100'
Python only takes the first line as the string, and it says error.
In which way can I enter it so that Python takes the complete string?
Thanks
You mean you need to enter a multi-line string with newlines?
Use triple quoting:
a = '''This is the first line
and a second one too
hello world!
'''
Newlines are preserved, as is all whitespace.
If you didn't want to include newlines, use parenthesis around multiple strings:
a = (
'This is one string, '
'entirely without newlines, but it is one long '
'string nonetheless')
The Python compiler makes such consecutive strings (without anything but whitespace in between) into one long string object.
However, a 900 digit string is perhaps best stored in a separate file, not in your source code:
with open('digitsfile.txt', 'r') as infh:
a = infh.read().strip() # read all data, remove newline at the end
The Python compiler concatenates adjacent string literals. You just need to tell the compiler that the literals are adjacent.
a = (
'123'
'456'
'789'
)
print a
you can skip new line by \:
>>> num = '12345' \
... '67890'
>>> num
'1234567890'
Are you sure there is no carriage return in the string somewhere, that would cause an error.
Try enclosing the string in triple quotes
s = """really long strrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrring"""
and then echo it back
print s