my input is something like this
23 + 45 = astart
for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this
SyntaxError: invalid syntax
the code is this
k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i) for i in b.split(' = '))
its always number + number = astar
its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error
Testing with Python 2.5.2, your code ran OK as long as I only had the same spacing
on either side of the + and = in the code and input.
You appear to have two spaces on either side of them in the code, but only one on either
side in the input. Also - you do not have to use the str(i) in a generator. You can do
it like a,b=k.split(' + ')
My cut and pastes:
My test script:
print 'Enter input #1:'
k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i) for i in b.split(' = '))
print 'Here are the resulting values:'
print a
print b
print c
print 'Enter input #2:'
k=raw_input()
a,b=k.split(' + ')
b,c=b.split(' = ')
print 'Here are the resulting values:'
print a
print b
print c
From the interpreter:
>>>
Enter input #1:
23 + 45 = astart
Here are the resulting values:
23
45
astart
Enter input #2:
23 + 45 = astart
Here are the resulting values:
23
45
astart
>>>
Edit: as pointed out by Triptych, the generator object isn't the problem. The partition solution is still good and holds even for invalid inputs
calling (... for ...) only returns a generator object, not a tuple
try one of the following:
a,b=[str(i) for i in k.split(' + ')]
a,b=list(str(i) for i in k.split(' + '))
they return a list which can be unpacked (assuming one split)
or use str.partition assuming 2.5 or greater:
a, serperator, b = k.partition('+')
which will always return a 3 tuple even if the string isn't found
Edit: and if you don't want the spaces in your input use the strip function
a = a.strip()
b = b.strip()
Edit: fixed str.partition method, had wrong function name for some reason
I think I'd just use a simple regular expression:
# Set up a few regular expressions
parser = re.compile("(\d+)\+(\d+)=(.+)")
spaces = re.compile("\s+")
# Grab input
input = raw_input()
# Remove all whitespace
input = spaces.sub('',input)
# Parse away
num1, num2, result = m.match(input)
You could just use:
a, b, c = raw_input().replace('+',' ').replace('=', ' ').split()
Or [Edited to add] - here's another one that avoids creating the extra intermediate strings:
a, b, c = raw_input().split()[::2]
Hrm - just realized that second one requires spaces, though, so not as good.
Rather than trying to solve your problem, I thought I'd point out a basic step you could take to try to understand why you're getting a syntax error: print your intermediate products.
k=raw_input()
print k.split(' + ')
a,b=(str(i) for i in k.split(' + '))
print b.split(' = ')
b,c=(str(i) for i in b.split(' = '))
This will show you the actual list elements produced by the split, which might shed some light on the problem you're having.
I'm not normally a fan of debugging by print statement, but one of the advantages that Python has is that it's so easy to fire up the interpreter and just mess around interactively, one statement at a time, to see what's going on.
Related
I am pretty new to python and would like to know how to write a program that asks the user to enter a string that contains the letter "a". Then, on the first line, the program should print the part of the string up to and including the certain letter, and on the second line should be the rest of the string.
For example...
Enter a word: Buffalo
Buffa
lo
This is what I have so far :
text = raw_input("Type something: ")
left_text = text.partition("a")[0]
print left_text
So, I have figured out the first part of printing the string all the way up to the certain letter but then don't know how to print the remaining part of the string.
Any help would be appreciated
If what you want is the first occurrence of a certain character, you can use str.find for that. Then, just cur the string into two pieces based on that index!
In python 3:
split_char = 'a'
text = input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print(left, '\n', right)
I don't have a python2 on hand to make sure, but I assume this should work on python 2:
split_char = 'a'
text = raw_input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print left + '\n' + right)
Another option that is far more concise is to use
left_text, sep, right_text = text.partition("a")
print (left_text + sep, '\n', right_text)
and then as suggested in the comments, thanks #AChampion !
You should have some knowledge about slicing and concatenating string or list. You can learn them here Slicing and Concatenating
word = raw_input('Enter word:') # raw_input in python 2.x and input in python 3.x
split_word = raw_input('Split at: ')
splitting = word.partition(split_word)
'''Here lets assume,
word = 'buffalo'
split_word = 'a'
Then, splitting variable returns list, storing three value,
['buff', 'a', 'lo']
To get your desire output you need to do some slicing and concatenate some value .
'''
output = '{}\n{}'.join(splitting[0] + splitting[1], splitting[2])
print(output)
First find the indices of the character in the given string, then print the string accordingly using the indices.
Python 3
string=input("Enter string")
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
indices=find(string, "a")
for index in indices[::-1]:
print(string[:index+1])
print(string[indices[-1]+1:])
I need help with my python program. I'm doing a calculator.
The numbers must be formed, but for some reason they do not add up.
It seems that I did everything right, but the program does not work.
Please help me. Picture
Code:
a = input('Enter number A \n');
d = input('Enter sign operations \n')
b = input('Enter number B \n')
c = a + b
if str(d) == "+":
int(c) == "a + b"
print('Answer: ' + c)
Please don't post screenshots. Copy and paste text and use the {} CODE markdown.
What data type is returned by input()? It's always a string. It doesn't matter what you type.
Where is the variable c actually calculated in this program? Line 4.
What types of data are used to compute c? Two strings.
What happens when you use the "+" operation on two strings instead of two numbers? Try running your program and when it prompts you to "enter number A", type "Joe". When it prompts you to "enter number B", type "Bob". What does your program do?
You need to create numerical objects from each of the strings you entered if you want to do arithmetic.
I think that you tried what you thought would do that on line 7. It doesn't work though. "==" is used to test for equality, not to assign a value. The single "=" is used to bind values to variable names. You do that correctly on lines 1 through 4. Notice that the plain variable name is always by itself on the left of the "=" sign. You do all the fancy stuff on the right side of the "=".
You can actually delete lines 6 and 7 and the output of the program will not change.
a and b are strings.
a + b concatenates strings a and b.
You need to convert the strings to int:
c = int(a) + int(b)
And remove the lines:
if str(d) == "+":
int(c) == "a + b"
Here is the complete code, that should to what you want:
a = input('Enter number A \n');
operation = input('Enter sign operations \n')
b = input('Enter number B \n')
c = a + b
if operation == "+":
c= int(a) + int(b)
print('Answer:', c)
Since it looks like you also want to enter an operation sign you might also try eval
a = input('Enter number A \n');
d = raw_input('Enter sign operations \n')
b = input('Enter number B \n')
eval_string = str(a) + d + str(b)
print ( eval(eval_string) )
You should know input accepts only integers and raw_input even if given an integer saves it as a string so it saves only strings.
I'm a beginner programmer. I want to write a program that gives me the maximum product of all the products of 4-adjacent digits in an input number.
So, if the input is "12345678"
Possible selections are 1234, 2345,3456,4567,5678 and the largest product is 5*6*7*8.
My code:
number = str(input("Enter a number:"))
i = 0
L = []
while (i!=len(number)-3):
a = int(number[i])
b = int(number[i+1])
c = int(number[i+2])
d = int(number[i+3])
product = a*b*c*d
L.append(product)
i = i+1
print(L)
print(number)
print(max(L))
I need to apply this to a 1000-digited number. My code works for 8-digited input number and gave an answer for a 500-digited number.
But I tried it with a 600-digited number and it throws this error.
I understand ValueError is an error that appears when the argument given to a function call has correct type, but inappropriate value. There are also examples of when the user gives a string "Alexander" as input in code Eg: int(input("Enter a number"))
the error is for '' an empty string that cannot be converted to an integer. But I cannot understand where/why the empty string was formed.
I have read a few other answers of this Error type, but all involve code that use features of Python I am NOT familiar with and hence cannot understand. I'm just a beginner! So, please help!
And apologies for breaking any rules laid out with regards to question formation!
You've got a space there, not an empty string. Most likely, you just hit the space bar at the end of your input, and Python can't convert that to an integer. You can either just ensure that you don't leave a space at the end, or do some checking of your input (e.g., add a line number = number.strip() to remove any trailing whitespace).
Validate your input as numeric, and strip any whitespace:
number ='123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'
def foo(number):
number = number.strip()
if number.isdigit():
i = 0
L = []
while (i in range(len(number)-3)):
a = int(number[i])
b = int(number[i+1])
c = int(number[i+2])
d = int(number[i+3])
product = a*b*c*d
L.append(product)
i = i+1
return max(L)
This functions should return a None if user has provided invalid input (e.g., "Alexander"), this should avoid the error you describe:
There are also examples of when the user gives a string "Alexander" as input in code Eg: int(input("Enter a number"))
You can also simplify this using a generator statement for a set of only the unique results:
def foo2(number):
number = number.strip()
if number.isdigit():
return max({int(number[i]) * int(number[i+1]) * int(number[i+2]) * int(number[i+3]) for i in range(len(number)-3)})
I'm using Grok Learning and the task it give you is 'to select every third letter out of a sentence (starting from the first letter), and print out those letters with spaces in between them.'
This is my code:
text = input("Message? ")
length = len(text)
for i in range (0, length, 3):
decoded = text[i]
print(decoded, end=" ")
Although I it says it isn't correct, it say this is the desired out-put:
Message? cxohawalkldflghemwnsegfaeap
c h a l l e n g e
And my output is the same expect, in my output, I have a space after the last 'e' in challenge. Can anyone think of a way to fix this?
To have spaces only between the characters, you could use a slice to create the string "challenge" then use str.join to add the spaces:
" ".join(text[::3])
Here's Grok's explanation to your question: "So, this question is asking you to loop over a string, and print out every third letter. The easiest way to do this is to use for and range, letting range do all the heavy lifting and hard work! We know that range creates a list of numbers, - we can use these numbers as indexes for the message!"
So if you are going to include functions like print, len, end, range, input, for and in functions, your code should look somewhat similar to this:
line = input('Message? ')
result = line[0]
for i in range(3, len(line), 3):
result += ' ' + line[i]
print(result)
Or this:
line = input('Message? ')
print(line[0], end='')
for i in range(3, len(line), 3):
print(' ' + line[i], end='')
print()
Or maybe this:
code = input ('Message? ') [0::3]
msg = ""
for i in code: msg += " " + i
print (msg [1:])
All of these should work, and I hope this answers your question.
I think Grok is just really picky about the details. (It's also case sensitive)
Maybe try this for an alternative because this one worked for me:
message = input('Message? ')
last_index = len(message) -1
decoded = ''
for i in range(0, last_index, 3):
decoded += message[i] + ' '
print(decoded.rstrip())
You should take another look at the notes on this page about building up a string, and then printing it out all at once, in this case perhaps using rstrip() or output[:-1] to leave off the space on the far right.
Here's an example printing out the numbers 0 to 9 in the same fashion, using both rstrip and slicing.
output = ""
for i in range(10):
output = output + str(i) + ' '
print(output[:-1])
print(output.rstrip())
If you look through the Grok course, there is one page called ‘Step by step, side by side’ (link here at https://groklearning.com/learn/intro-python-1/repeating-things/8/) where it introduces the rstrip function. If you write print(output.rstrip()) it will get rid of whitespace to the right of the string.
So i had to write a program that asks for a user input (which should be a 3 letter string) and it outputs the six permutations of the variations of the placements of the letters inside the string. However, my professor wants the output to be surrounded by curly brackets whereas mine is a list (so it is square brackets). How do i fix this? Also, how do I check if none of the letters in the input repeat so that the main program keeps asking the user to enter input and check it for error?
Thank you
The only datatype im aware of that 'natively' outputs with { } is a dictionary, which doesnt seem to apply here. I would just write a small function to output your lists in the desired fashion
>>> def curlyBracketOutput(l):
x = ''
for i in l: x += i
return '{' + x + '}'
>>> curlyBracketOutput(['a','b','c'])
'{abc}'
ok, for one thing, as everyone here has said, print '{'. other than that, you can use the following code in your script to check for repeated words,
letterlist = []
def takeInput(string):
for x in string:
if x not in letterlist:
letterlist.append(x)
else:
return 0
return 1
then as for your asking for input and checking for errors, you can do that by,
while(True): #or any other condition
string = input("Enter 3 letter string")
if len(string)!=3:
print("String size inadequate")
continue
if takeInput(string):
arraylist = permutation(string) #--call permutation method here
#then iterate the permutations and print them in {}
for x in arraylist: print("{" + x + "}")
else:
print("At least one of the letters already used")
The answer to both question is to use a loop.
Print the "{" and then loop through all the elements printing them.
But the input inside a loop and keep looping until you get what you want.
Curly brackets refers to a dict?
I think a
list(set(the_input))
should give you a list of unique letters. to check if they occur more than once
and
theinput.count(one_letter) > 1
should tell you if there is mor than one.
>>> chars = ['a','b','c']
>>> def Output(chars):
... return "{%s}" % ''.join(chars)
...
>>> print Output(chars)
{abc}
>>>
Or just do something tremendously kludgy:
print repr(YourExistingOutput).replace("[", "{").replace("]", "}")