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:]
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
I want a percentage sign to display after the users enters their number. Thanks
percent_tip = float(input(" Please Enter the percent of the tip:")("%"))
For example, before the user types anything they should see:
Please Enter the percent of the tip:
Once they begin typing the number 20 they should see:
Please Enter the percent of the tip: 20
After they hit <Enter> they should see:
Please Enter the percent of the tip: 20%
Please try this if this is what you are asking for:
import sys
import time
percent_tip = ""
while percent_tip in "123456789": # This part checks with the "if" statement, if its not a integer then it returns
percent_tip = input("Please Enter the % of the tip: ")
if percent_tip in "123456789":
print(str(percent_tip) + " %") # Prints the number and the percentage symbol
sys.exit() #stops the shell
else:
time.sleep(.100) #Shell waits then goes back in the while loop (unless its controlled by the "while" and "if")
Please do not try to harden yourself with a code that you don't know how to do it.
If you are on Windows, you will have the msvcrt module available. It provides, among others, the getwche() function, giving you the key pressed. This allows you to act on individual characters, and then print the % at the end (if you play around a bit more, you can probably also get it to appear while typing).
Example:
def get_chars():
chars = []
new = msvcrt.getwche()
while new != '\r': # returns \r on <RETURN> press
# you probably want to do some input validation here
chars.append(new)
new = msvcrt.getwche() # get the next one
print(end='%', flush=True)
return ''.join(chars) # this returns a str, you might want to directly get an int
Also, you will probably want to add input validation inside to make sure the input is only numbers.
sorry about the heading I know it makes no sense. What I was trying to say was when I make an input in e.g.
choice = input ("you have 2 choices: 1)live or ") die")
how do I make each individual choice go onto a new line in my shell without it ending the input when I try to just put it onto a new line the input doesn't recognize the text as part of what I want the input to say. Thanks in advance.
Try this -
choice = input ("you have 2 choices: \n1)live or \n2)die\nChoose: ")
You see the \n? That's called a string literal. See this table for more string literals
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.
Update: My current question is how can I get my code to read to the EOF starting from the beginning with each new search phrase.
This is an assignment I am doing and currently stuck on. Mind you this is a beginner's programming class using Python.
jargon = open("jargonFile.txt","r")
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
result = jargon.readline().find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
searchPhrase = raw_input("Enter the search phrase: ")
jargon.close()
The assignment is to take a user's searchPhrase and find it in a file (jargonFile.txt) and then have it print the result (which is the line it occured and the character occurence). I will be using a counter to find the line number of the occurence but I will implement this later. For now my question is the error I am getting. I cann't find a way for it to search the entire file.
Sample run:
Enter the search phrase: dog
16
Enter the search phrase: hack
Cannot find this term.
Enter the search phrase:
"dog" is found in the first line however it is also found in other lines of the jargonFile (multiple times as a string) but it is only showing the first occurence in the first line. The string hack is found numerous times in the jargonFile but my code is setup to only search the first line. How may I go about solving this problem?
If this is not clear enough I can post up the assignment if need be.
First you open the file and read it into a string with readline(). Later on you try to readline() from the string you obtained in the first step.
You need to take care what object (thing) you're handling: open() gave you a file "jargon", readline on jargon gave you the string "jargonFile".
So jargonFile.readline does not make sense anymore
Update as answer to comment:
Okay, now that the str error problem is solved think about the program structure:
big loop
enter a search term
open file
inner loop
read a line
print result if string found
close file
You'd need to change your program so it follows that descripiton
Update II:
SD, if you want to avoid reopening the file you'd still need two loops, but this time one loop reads the file into memory, when that's done the second loop asks for the search term. So you would structure it like
create empty list
open file
read loop:
read a line from the file
append the file to the list
close file
query loop:
ask the user for input
for each line in the array:
print result if string found
For extra points from your professor add some comments to your solution that mention both possible solutions and say why you choose the one you did. Hint: In this case it is a classic tradeoff between execution time (memory is fast) and memory usage (what if your jargon file contains 100 million entries ... ok, you'd use something more complicated than a flat file in that case, bu you can't load it in memory either.)
Oh and one more hint to the second solution: Python supports tuples ("a","b","c") and lists ["a","b","c"]. You want to use the latter one, because list can be modified (a tuple can't.)
myList = ["Hello", "SD"]
myList.append("How are you?")
foreach line in myList:
print line
==>
Hello
SD
How are you?
Okay that last example contains all the new stuff (define list, append to list, loop over list) for the second solution of your program. Have fun putting it all together.
Hmm, I don't know anything at all about Python, but it looks to me like you are not iterating through all the lines of the file for the search string entered.
Typically, you need to do something like this:
enter search string
open file
if file has data
start loop
get next line of file
search the line for your string and do something
Exit loop if line was end of file
So for your code:
jargon = open("jargonFile.txt","r")
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
<<if file has data?>>
<<while>>
result = jargon.readline().find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
<<result is not end of file>>
searchPhrase = raw_input("Enter the search phrase: ")
jargon.close()
Cool, did a little research on the page DNS provided and Python happens to have the "with" keyword. Example:
with open("hello.txt") as f:
for line in f:
print line
So another form of your code could be:
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
with open("jargonFile.txt") as f:
for line in f:
result = line.find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
searchPhrase = raw_input("Enter the search phrase: ")
Note that "with" automatically closes the file when you're done.
Your file is jargon, not jargonFile (a string). That's probably what's causing your error message. You'll also need a second loop to read each line of the file from the beginning until you find the word you're looking for. Your code currently stops searching if the word is not found in the current line of the file.
How about trying to write code that only gives the user one chance to enter a string? Input that string, search the file until you find it (or not) and output a result. After you get that working you can go back and add the code that allows multiple searches and ends on an empty string.
Update:
To avoid iterating the file multiple times, you could start your program by slurping the entire file into a list of strings, one line at a time. Look up the readlines method of file objects. You can then search that list for each user input instead of re-reading the file.
you shouldn't try to re-invent the wheel. just use the
re module functions.
your program could work better if you used:
result = jargon.read() .
instead of:
result = jargon.readline() .
then you could use the re.findall() function
and join the strings (with the indexes) you searched for with str.join()
this could get a little messy but if take some time to work it out, this could fix your problem.
the python documentation has this perfectly documented
Everytime you enter a search phrase, it looks for it on the next line, not the first one. You need to re-open the file for every search phrase, if you want it behave like you describe.
Take a look at the documentation for File objects:
http://docs.python.org/library/stdtypes.html#file-objects
You might be interested in the readlines method. For a simple case where your file is not enormous, you could use that to read all the lines into a list. Then, whenever you get a new search string, you can run through the whole list to see whether it's there.