Taking Mutiple line input in python using basic python - python

I am trying to solve some problems in CodeAbbey using Python.I have run into a wall trying to take input for these programs.I have spent so much time analyzing how to take the input data without even solving the question.Hope someone explains how to take input.
Problem:I have to input the following numbers in One go. I have tried using 'input()' but it takes only one line. Is there any work around to do it in a simple way? i wasted so much time trying to analyse various options
632765 235464
985085 255238
621913 476248
312397 751031
894568 239825
702556 754421
474681 144592
You can find the exact question here: http://www.codeabbey.com/index/task_view/sums-in-loop

You can just repeat input() until you get all your data, e.g.:
try:
input = raw_input # fix for Python 2.x compatibility
except NameError:
pass
def input_pairs(count):
pairs = [] # list to populate with user input
print("Please input {} number pairs separated by space on each new line:".format(count))
while count > 0: # repeat until we get the `count` number of pairs
success = True # marks if the input was successful or not
try:
candidate = input() # get the input from user
if candidate: # if there was some input...
# split the input by whitespace (default for `split()`) and convert
# the pairs to integers. If you need floats you can use float(x) instead
current_pair = [int(x) for x in candidate.split()]
if len(current_pair) == 2: # if the input is a valid pair
pairs.append(current_pair) # add the pair to our `pairs` list
else:
success = False # input wasn't a pair, mark it as unsuccessful
else:
success = False # there wasn't any input, mark it as unsuccessful
except (EOFError, ValueError, TypeError): # if any of the conversions above fail
success = False # mark the input as unsuccessful
if success: # if the input was successful...
count -= 1 # reduce the count of inputs by one
else: # otherwise...
print("Invalid input, try again.") # print error
return pairs # return our populated list of pairs
Then you can call it whenever you need number pairs like:
my_pairs = input_pairs(7) # gets you a list of pairs (lists) entered by user

My first attempt would be to try a typing like "632765 235464\n985085 255238[...]" so you could read it as one line. This would be pretty hacky and not a good idea if its real userinput.
The other idea: Why not taking the input line by line and putting these lines in a list / appending them to a string?
EDIT:
I found some Code on SO, but its python2.7 i guess. ->Here
The Python3.X style would be:
#!/usr/bin/python
input_list = []
while True: # Infinite loop, left by userinput
input_str = input(">") #The beginning of each line.
if input_str == ".": #Userinput ends with the . as input
break # Leave the infinite loop
else:
input_list.append(input_str) #userinput added to list
for line in input_list: #print the input to stdout
print(line)
Hope this will help :)

Related

Querying a dictionary user input infinite loop python

Newbie trying to learn some basic python, I've imported a json file containing a dictionary of terms. I'm trying to create a script that lets users look up definitions from my dictionary. I'm getting stuck on lines 14-15. I don't want the script to stop after just two attempts. I can work out how to set it to a max # of attempts but not how to make it infinite allowing unlimited tries. Each new query should be followed by a close match result using the get_close_matches method in difflib if the attempt is not an exact match, with the user prompted to accept or reject the closest match. My script, however, will stop after two attempts and if the 2nd query is not an exact match error out instead of presenting the 3 (the default for the method) closest matches to the word. Any ideas?
import json
from difflib import get_close_matches
data=json.load(open('data.json'))
def translate(w):
w=w.lower()
if w in data:
return data[w]
elif len(get_close_matches(w,data.keys()))>0:
yn=input("Did you mean %s? Enter Y or N: " % get_close_matches(w,data.keys())[0]).upper()
while yn =="N":
i=input("Enter Word: ")
return data[get_close_matches(i,data.keys())]
else:
return data[get_close_matches(w,data.keys())[0]]
word=input("Enter Word: ")
print(translate(word))
Your current approach isn't working because of the return statement inside the while yn == "N" loop. That return immediately takes you out of the function, regardless of whether the loop has completed, so there's no way for this loop to run more than once.
You could edit the loop to prevent it from always returning, but it's easier to move the loop outside the function. That way you don't have to worry about whether you're working with the initial input or a subsequent input, and you can cut down on duplicate code:
def translate():
w = input("Enter Word: ").lower()
if w in data:
return data[w]
close_matches = get_close_matches(w, data.keys()) # This only runs if w was NOT in data
if len(close_matches) > 0:
yn = input("Did you mean %s? Enter Y or N: " % close_matches[0]).upper()
if yn == 'Y':
return data[close_matches[0]]
return None # This is optional. Reaching the end of a function will return None by default
translated_word = None # Force at least one iteration of the loop
while translated_word is None: # Keep going until there's a match or the user types "Y"
translated_word = translate()
print(translated_word) # This will only run once the loop condition is False

Pulling from a list

My question is about getting a user to pull and item from a list. If the item from the list isn't pulled from the list I want to tell the user that he is incorrect. So my code looks like this:
Body_Type = ['Large', 'Medium', 'Small']
print('Create a Character-')
print('Body Type Choices: ' + str(Body_Type))
bt = input('Enter your Body Type: ')
while bt != Body_Type:
if bt == Body_Type[0:]:
print('Your Body Type is: ' + bt)
else:
print('Invalid Body Type')
What I'm trying to do is make my user create a character. This is just the first part of my first simple project. I want to have him pull from one of the items on the list, being "Large, Medium, Small" respectively. I want it to repeat until the user chooses one of the three. I tried to use or but it seems to feel unorganized and I'd have to break up the list and assign each individual variable.
Thanks in advance!
Several errors here like comparing a string to a list, or random slicing hoping that it would work. And the fact that your input statement is before the loop creates an infinite loop because you're comparing 2 variables of a different type again and again (bt != Body_Type is always True regardless of the content of bt since left hand is a string, right hand is a list).
But it shouldn't be so complex to write some working code.
I would create an infinite loop and break only if choice is in the list:
while True:
bt = input('Enter your Body Type: ')
if bt in Body_Type:
print('Your Body Type is: ' + bt)
break
else:
print('Invalid Body Type')
simpler and clearer (and repeats input if fails). The infinite loop (with an always true condition) allows to avoid double input call & test. Just loop, input the string, and break from the loop if matches.
The key statement you were looking for was bt in Body_Type which tests if the string is within the list.

How to remove element from a list in matrix?

I'm trying to build Nim "mathematical game of strategy" in Python, I have problem with removing element from specific list from the matrix, I started with getting game mode from user and then start removing elements.
def RemoveMatches(Stacks,StackNum,Matches):
if not_empty(Stacks[StackNum]):
lenStack=len(Stacks[StackNum])
try:
val=int(Matches)
except ValueError:
print ("Wrong input,try only with numbers")
return False
if val>lenStack:
print "try again with smaller number"
return False
else :
for i in range(Matches):
Stacks[StackNum].pop()
return True
else:
print "Stack that you have chose is already empty,try other satck"
return False
Stacks is the matrix that i build in main.
StackNumnumber of list that i want to remove from it elements.
Matches number of elements that i want to remove.
There is another function called ManageGame which control user's input "if it's 2 players or 1, getting StackNum/Matches":
def ManageGame(Stack,gameMode):
if gameMode=='2':
while(lastDot(Stack)):
stackNum,matchesNum=raw_input('select number of the Stack and number of Matches between 1-10. keep a space between two numbers:').split(' ')
check=RemoveMatches(Stack,int(stackNum),int(matchesNum))
if check:
DrawStacks(Stack)
else:
print "try again."
lastDot(Stack) is a function which checks if the matrix has more then 1 Dot.
The problem is when I'm trying to remove number of elements from StackNum I get somthing like this:
from:
When I type StackNum=1,Matches=2 I get:
Somehow I remove 2 Dots from each matrix line, I cannot see the problem in my code.
The return in the line:
for i in range(Matches):
Stacks[StackNum].pop()
return True
is situated in the wrong location. you have to move it after the for.
Otherwise, after the first iteration it will exit and not run all the iterations:
for i in range(Matches):
Stacks[StackNum].pop()
return True
the problem here with the list l=[],here how I build my matrix:
l=[]
tmp=[]
for i in range(10):
l.append('*')
for i in range(5):
tmp.append(l)
python works with pointers so I'm appending same pointer for tmp, when I make a change to one of them the rest going to be the same .
Here how I did solve it :
for i in range(5):
tmp.append(10)
When I want to pop an element I subtract Matches number.

How do I create an array with infinite elements or something, in python?

I am trying to create a python array that can hold as many strings as the user enters. I am trying to implement it in a loop, like this :
(Loop:)
Enter the string:
array[1] = (string entered by user)
Enter the next string:
array[2] = (second string entered by user)
....
Enter the nth string:
array[n] = (nth string entered by user)
How can I achieve this? I have heard of dynamic arrays and lists and stuff, but I can't figure them out.
Thank you in advance.
The default lists in Python are dynamic arrays. You can simply initialize it with:
data = []
and use:
data.append(item)
to add an element at the end.
For example:
data = []
while True:
print('Enter the string:')
data.append(input())
This will go on until all the memory of your machine is exhausted.
You can also for instance specify a way to stop asking the user for more data. For instance if the user enters '-1', you can say the loop should stop:
data = []
while True:
print('Enter the string:')
the_input = input()
if the_input == '-1':
break
data.append(the_input)
#do something with the collected data
Now if you for instance run this code: the code will query for input until you enter -1 (I think it is rather obvious how you can change the stopword). Then data contains all data entered before and you can process it somehow.
Try this:
all_the_things = list()
for x in items:
all_the_things.append(x)
For more reading: Python Data Structures
If you want to add to a list, use append
data = []
data.append('whatever')
You haven't asked about how to get the input, so I assume you can do that.
Do bear in mind your computer will not have infinite storage - at some point you will run out of memory if you do this in a loop for ever.

Can't get my loop & match to append to correct list

I´m experiencing problems with my code.
I can´t get it to append to the list not_found as well as it loops twice for some reason.
Can anyone point me in the right direction? The match works for my_track, but it doesn't when it doesn't match.
# coding: utf-8
#!/usr/bin/env python
import spotimeta
import sys
import time
my_tracks = raw_input("Please enter a sentence: ").title().split()
playlist = []
real_playlist = []
not_found = []
def check_track(track_name, my_track, track_href):
if track_name == my_track:
playlist.append(track_href)
return 1
# make sure the user does not input a single word as input
if (len(my_tracks) > 1):
path = my_tracks[1]
else:
sys.exit("Invalid input, please enter a sentence.")
# let's search
for my_track in my_tracks:
match = 0
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if not match == 1:
try:
match = check_track(result["name"],my_track,result["href"])
except Exception, e:
error = "not available"
else:
if data['total_results'] > 0:
not_found.append(my_track)
You should try debugging it. One of the simplest ways of debugging is add the lines:
import pdb
pdb.set_trace()
Then when you run the script it will stop at the set_trace line in the debugger.
Check out http://docs.python.org/library/pdb.html for more information.
From my understanding you're trying to do something like:
for my_track in my_tracks:
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if result['name'] == my_track:
playlist.append(result['href'])
elif data['total_results'] > 0:
not_found.append(my_track)
Will this more or less work for you?
Please help me to understand.
Right off the bat, I'm noticing two things.
First, you're checking data['total_results'] a bit late; if the total results value is greater than zero (wait, what?), then you want to add it to the list immediately and move on without parsing the data. I would, after the call from spotimeta.search_track(), check to see if this is the data you don't want (then subsequently add it into the list).
Second, I'm confused about the intention of your for loop. If you're going through it to only find one item, then you can use the in statement (my_track in result).

Categories

Resources