I have a small file with a bunch of phrases on each line. I want the user to type a number and that number will print the selected line.
def printSpecLine(x):
print('started')
with open('c:/lab/save.txt') as f:
for i, line in enumerate(f, 1):
if i == x:
break
print (line)
print('done')
f.close()
s = int(input("Enter a number: "))
printSpecLine(s)
I've ran this with no errors, but the function isn't being called at all. Printing "started" (second line) didn't even occur. Am I missing a step here?
The only explanation for this is that you are not actually inputting to the prompt! There doesn't seem to be any other reason why at least the first print wouldn't be made.
Remember that input() is blocking, so until you enter your number and press enter, the program will be halted where it is (i.e. not call the function).
Apparently the ide i was using has a problem with raw input and integers being converted. Sublime Text 3 doesn't take python input very well. Thank you for your answer.
Related
I am new to coding. And I would like to know if there's a way for input function to not print newline character after the value is entered. Something like print function's argument end. Is there any way?
Well, you can't make input() trigger by anything besides 'Enter' hit (other way may be using sys.stdin and retrieving character one-by-one until you receive some stop marker, but it's difficult both for programmer and for user, I suppose). As a workaround I can the suggest the following: if you can know the length of line written before + length of user input, then you can use some system codes to move cursor back to the end of previous line, discarding the printed newline:
print("This is first line.")
prompt = "Enter second: "
ans = input(prompt)
print(f"\033[A\033[{len(prompt)+len(ans)}C And the third.")
\033[A moves cursor one line up and \033[<N>C moves cursor N symbols right. The example code produces the following output:
This is first line.
Enter second: USER INPUT HERE And the third.
Also note that the newline character is not printed by your program, it's entered by user.
name=input('Enter your name : ')
print('hello',name,end='')
I know about the end function which is abov
In this code I'm inputting as many integers as I want, and then pressing the enter key twice to end the program and get the Maximum Value of all the integers I just input. However, if my first input is the enter key, an error shows up. How do I fix this error (using while and if)so that the code will ignore it and let me keep inputting numbers? Thank you everyone.
print("Please put in some integers and hit the enter key twice to finish:")
s = input()
first = True
while s != "":
lst = s.split()
for x in lst:
if first:
maxV = int(x)
first = False
else:
if maxV < int(x):
maxV = int(x)
s = input()
print(maxV)
Before anything else, a word on input() and the Enter key! Pressing enter is just the way you tell input() that you’re done writing whatever text you want. When that happens, input() grabs the content of the line and sends it as a string to your program.
Therefore, saying that your program crashes if your first input is the enter key isn’t really accurate. The important part is that you wrote nothing before hitting enter, not the act of hitting enter itself. Since you wrote nothing the line is empty, which means input() returns a string containing nothing, an empty string. It’s the empty string, as I will show below, not the innocent enter key, which is at fault here.
Now, let’s take a look at what’s causing the error. You haven’t actually shared the exact error message, but I’m certain that it mentions something about maxV being undefined.
As we just saw, if you don’t write anything when first prompted for input then s is the empty string. As a result, you skip the while loop and land directly on the line print(maxV). Since you didn’t enter the while loop, however, your program has never heard of maxV at that point. When it goes looking for the variable maxV it finds nothing, and sensibly throws an error.
Here is how I would refactor your program:
import math
max_val = - math.inf
prompt_text = 'Enter one or more numbers, or enter nothing to quit: '
curr_line = input(prompt_text).strip()
while curr_line != '':
curr_line_vals = (int(curr_val) for curr_val in curr_line.split())
curr_line_max = max(curr_line_vals)
max_val = max(max_val, curr_line_max)
curr_line = input(prompt_text).strip()
print(f'maximum value: {max_val}')
Do note that the program above does not verify input at all, that's something to keep in mind. max_val has a default value of minus infinity, which means the code won't crash if the user quits without having entered any numbers.
Let me know if you have any questions!
I'm new to python and I've been trying to make a little function to call upon when I need to filter an input from everything except regular letters.
I've used SO for parts of the code, but I can't seem to understand why does it only print on every second try.
Here's my code:
import re
i=1
def inputFilterText():
inputRaw = input('input: ')
inputFiltered = re.sub('[^a-zA-Z]+', '', inputRaw)
return inputFiltered
while i > 0:
inputFilterText()
print(inputFilterText())
And here's my output:
I'm not really sure what's going on, but I presume it's a logical error. I've only just started using Python so any help is appreciated.
PSThe 'while' is only there so it's easier to test, it can be omitted.
You are calling inputFilterText twice. Once within the print() and once before. This is causing the code to prompt for input twice before printing the second response.
The problem is that you make a call to the inputFilterText function twice. The first time the output is discarded. Causing input to be taken twice, but only showing a result once.
To fix it, remove the inputFilterText() line. An example of working code.
import re
i=1
def inputFilterText():
inputRaw = input("input: ")
inputFiltered = re.sub(""[^a-zA-Z]+, "", inputRaw)
return inputFiltered
while i > 0:
print(inputFilterText())
Also, in future please send code as raw text, rather than screenshots.
Might I suggest using a variable here, you're not doing anything with the first filter call (this is why it's asking the first time) and the second one you're only printing.
while True:
txt = inputFilterText()
#do some stuff if needed
print(txt)
For my program I ask the user to input a command. If the user writes: Input filename (filename being any possible name of a file in the computer) I want my program to only read Input so it knows what if statement to use and then open the file that the user wrote.
There is also another part where I have to do a similar task, where the user inputs: score n goals.(n is the top number of players the program has to read from a list) I want the program to differentiate this from 2 other similar tasks (score n misses and score n passes).
I am not sure if I'm approaching this the correct way, but this was my try for the first case I talked about, but it doesn't work.
user_input = input ('File name:')
input_lowered = user_input.lower()
command = input_lowered[0:4]
if command == 'input' :
fp = open ("soccer.part.txt")
else :
user_upper = input ('Input name:')
Thanks in advance for any clue of how I should aim at fixing this!!!
You can do that as follows:
your_string[0:5]
This will get the first five characters of the string as a string.
If you would like to grab a part of the string from the start then you can use:
my_string[:number]
if you would like to grab a part of the string from the end:
my_string[-number:]
I'm a complete beginner in Python and I need some 'help' with something which is relatively simple (for a non-beginner).
What I'm trying to make is a quick 'program' which measures the length of a string which has been inputted. Maybe I have not looked hard enough, but I can't seem to find any specific information about this on the interwebs.
Ok, so here is what I have done so far:
print "Please enter a number or word and I will tell you the length of it."
NR = raw_input()
print len(NR)
*NR has no significant meaning, it's just a random variable name
Everything works as expected at first. For example, I enter the word "Hello" and it then replies with "5" or I enter the number 100 and it replies with "3" which is great, but when I attempt to enter another word I get this error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
hello
NameError: name 'hello' is not defined
However, when I enter another number (after I have already entered one), it just repeats the number which I have entered. For example, when I first enter the number "50" it replies with "2", but when I enter "50" a second time it just repeats the integer to me.
Note:
I think I understand the problem for the first part: It doesn't work more than once because the variable "NR" only counts as the first string which has been inputted. Even if I'm correct, I still don't know a solution to this.
Your program collects exactly one line of input and then finishes. After your program is finished, you are back in whatever environment you used to start your program. If that environment is a python shell, then you should expect that typing 50 will print a 50, and typing hello will print a no-such-variable-name error message.
To get your code to run more than once, put it in a while loop:
while True:
print "Please enter a number or word and I will tell you the length of it."
NR = raw_input()
print len(NR)
Note that raw_input() can print a prompt, so you don't need the print statement:
while True:
NR = raw_input("Please enter a number or word and I will tell you the length of it: ")
print len(NR)
This program fragment will run forever (or, at least until you interrupt it with Control-C).
If you'd like to be able to stop without interrupting the program, try this:
NR = None
while NR != '':
NR = raw_input("Please enter a number or word (or a blank line to exit): ")
print len(NR)
If you'd like to print the prompt once and then the use can enter many strings, try this:
print "Please enter a number or word and I will tell you the length of it."
while True:
NR = raw_input()
print len(NR)