ok so I a trying to make a calculator in python and it comes up with ParseError: Bad Input on line 7 and ParseError: Bad Input on line 6 etc. all the way down to ParseError: Bad Input on line 1, can anyone spot the error and how to fix it.
1:) n = input(" select first number: ")
2:) d = raw_input("What operation: ")
3:) print " What operation: " + str(d)
4:) n1 = input(" select second number ")
6:) if d == "+":
7:) print "Did you know that " + str(n) + " plus " + str(n1) + " is "
7:) + str(n+n1)+ "?"
8:)
9:)print " "
10:)print "Goodbye"
The line:
print "Did you know that " + str(n) + " plus " + str(n1) + " is "
will happily print something. Then the interpreter sees this:
+ str(n+n1)+ "?"
and has no idea what you mean, because it doesn't know you're continuing the previous line's print statement. You can fix this by adding parentheses:
>>> print ("Did you know that " + str(1) + " plus " + str(1) + " is "
... + str(2)+ "?")
Did you know that 1 plus 1 is 2?
Now the interpreter knows that, when you finish that first line, you're not done entering the expression. It will wait for you to finish a valid statement before processing it. See also logical lines and physical lines in Python.
Related
while True:
time.sleep(SLEEP_BETWEEN_ACTIONS)
input_1 = input("\n" + player1_name + ": " + random.choice(player_turn_text) + " Hit the enter to roll dice: ")
print("\nRolling dice...")
dice_value = get_dice_value()
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(player1_name + " moving....")
player1_current_position = snake_ladder(player1_name, player1_current_position, dice_value)
check_win(player1_name, player1_current_position)
if __name__ == "__main__":
start()
My error log says
TypeError: can only concatenate str (not "tuple") to str
input_1 = input("\n" + player1_name + ": " + random.choice(player_turn_text) + " Hit the enter to roll dice: ")
I don't know the signatures of the function you use, and that are not present in the attached code. But it seems, one of the elements here:
+ player1_name + ": " + random.choice(player_turn_text) +
Returns tuple.
The simplest solution to that, would be to call it like str(player1_name) - and the same with the other one.
I keep editing my text but I keep on getting the same error!
My code:
import random
Female_Characters = ["Emily", "Ariel", "Jade", "Summer"]
Male_Characters = ["Blake", "Max", "Jack", "Cole", "Daniel"]
PlacesToMeet = ["Beach", "Park", "Train Station", "Cave"]
SheSaid = ["Lets go explore!", "I'm tired", "I saw a purple frog", "My tounge hurts"]
HeSaid = ["I didnt get much sleep", "I wanna go inside that cave!", "Oh, ok"]
Outcomes = ["They never got to", "They were never found again.", "They enjoyed their day and went to
get Ice Cream!"]
ChosenFemale = random.choice(Female_Characters)
ChosenMale = random.choice(Male_Characters)
ChosenMeet = random.choice(PlacesToMeet)
ChosenShesaid = random.choice(SheSaid)
ChosenHeSaid = random.choice(HeSaid)
print ("There were two friends, their names are ") + (ChosenMale) + (", and ") + (ChosenFemale) + (".") + ("One day when they were at the") + (ChosenMeet) + (", ") + (ChosenFemale) + (" Said, ") + (ChosenShesaid) + (". Then") + (ChosenMale) + (" Said ") + (ChosenHeSaid) + (". After that, ") + random.choice(Outcomes)
Still new to python
You have incorrect parentheses on the print line.
print("There were two friends, their names are " + ChosenMale + ", and " + ChosenFemale + "." + "One day when they were at the" + ChosenMeet + ", " + ChosenFemale + " Said, " + ChosenShesaid + ". Then" + ChosenMale + " Said " + ChosenHeSaid + ". After that, " + random.choiceOutcomes)
Your code was calling
print("There were two friends, their names are ")
which returns None, and then trying to concatenate that with all the other strings.
Maybe you were following Python 2.x instructions. In Python 2, print is a statement so it didn't take an argument in parentheses, but in Python 3 it's an ordinary function.
remove the parenthesis at the end of this string
print("There were two friends, their names are "
and add it at the end of
random.choice(Outcomes)
so it should be:
print ("There were two friends, their names are " + (ChosenMale) + (", and ") + (ChosenFemale) + (".") + ("One day when they were at the") + (ChosenMeet) + (", ") + (ChosenFemale) + (" Said, ") + (ChosenShesaid) + (". Then") + (ChosenMale) + (" Said ") + (ChosenHeSaid) + (". After that, ") + random.choice(Outcomes))
I want a space on the Farhan Sadik and Snigdho
I tried this many times on spacing Name, Name2, Welcome but there is no result.
Actually you concatenante your strings with no space between them.
You can do:
print("Hi", name1, name2, welcome)
or:
print("Hi " + name1 + " " + name2 + " " + welcome)
You can simply solve this, adding a space:
Name + " " + Name2 + " " + third_variable
print(Name + " " + Name2 + " " + "WELCOME")
OUTPUT:
Value of Name value of name2 WELCOME
If comma(,) is used in the place of " " it will also give the same output (as above)
The above code prints the value of name and a space (" ") and again name2 and a space (" ") and the string "WELCOME".
In the same way if you use \n in the space of " " you will get the output of the string or variable next to the \n in a new line. For example:
print(Name + "\n" + Name2 + "\n" + "WELCOME")
Output:
Value of Name
Value of Name2
WELCOME
In the same way if \t is used in the place of \n it will print the variable or string next to it after a tab space, like:
Output:
Value of Name Value of Name2 WELCOME
This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 6 years ago.
i'm trying to print the operation however the first statement is working but second statement has error.
conSwitch = raw_input("Enter cycle of context switch: ")
cycleOpr = raw_input("Enter cycle operation: ")
totalCycle = float(conSwitch) + float(cycleOpr) + float(conSwitch)
print "Context =", conSwitch
print "Cycle operation =", cycleOpr
print "Context switch back =", conSwitch
print("\n")
print (conSwitch + " + " + cycleOpr + " + " + conSwitch)
print ("Total number of cycle is: " + format(totalCycle))
print("===================================================")
reqSecond = raw_input("Enter cycle request second:")
print "Total cycle request =", totalCycle
print "Cycle request per second =", reqSecond
print("\n")
totalSpent = float(totalCycle) * float(reqSecond)
print (totalCycle + " * " + reqSecond)
print ("Total number of spent = " + format(totalSpent))
==============================================================
First statement
Work===>> print (conSwitch + " + " + cycleOpr + " + " + conSwitch)
Second statement
Error===>> print (totalCycle + " * " + reqSecond)
The problem here is that the variable totalCycle is of type float. Python does not know what it means to do + between a type float and string (because " * " is a string).
To do it the way you showed you have to convert totalCycle to string first, like this:
print (str(totalCycle) + " * " + reqSecond)
FORMAT Syntax
"First, thou shalt count to {0}" # References first positional argument
"Bring me a {}" # Implicitly references the first positional argument
"From {} to {}" # Same as "From {0} to {1}"
"My quest is {name}" # References keyword argument 'name'
"Weight in tons {0.weight}" # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}" # First element of keyword argument 'players'.
I'm making a program that scrapes local bus times from a real time information server and prints them. In order to return all the bus times, it does this:
while i < len(info["results"]):
print "Route Number:" + " " + info['results'][i]['route']
print "Due in" + " " + info["results"][i]["duetime"] + " " + "minutes." + "\n"
i = i + 1
This works fine, and returns all of the results, one by one like so:
Route Number: 83
Due in 12 minutes.
Route Number: 83
Due in 25 minutes.
Route Number: 83A
Due in 39 minutes.
Route Number: 83
Due in 55 minutes.
However, as I'm using this feature within another script, I turned the code to fetch times and return them into a function:
def fetchtime(stopnum):
data = "?stopid={}".format(stopnum)+"&format=json"
content = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation"
req = urllib2.urlopen(content + data + "?")
i = 0
info = json.load(req)
if len(info["results"]) == 0:
return "Sorry, there's no real time info for this stop!"
while i < len(info["results"]):
return "Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n"
i = i + 1
This works, however it only returns the first bus from the list given by the server, instead of however many buses there may be. How do I get the printed result of the function to return the info supplied in each iteration of the loop?
Can you not just make a list and return the list?
businfo = list()
while i < len(info["results"]):
businfo.append("Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
i = i + 1
return businfo
You will have to edit the printing commands that this function returns to.
I would suggest you to use the yield statement instead return in fetchtime function.
Something like:
def fetchtime(stopnum):
data = "?stopid={}".format(stopnum)+"&format=json"
content = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation"
req = urllib2.urlopen(content + data + "?")
i = 0
info = json.load(req)
if len(info["results"]) == 0:
yield "Sorry, there's no real time info for this stop!"
while i < len(info["results"]):
yield "Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n"
i = i + 1
It would allow you to pick one data at a time and proceed.
Lets say that info["results"] is a list of length 2, then you could do:
>> a = fetchtime(data)
>> next(a)
Route Number: 83 Due in 25 minutes.
>> next(a)
Route Number: 42 Due in 33 minutes.
>> next(a)
StopIteration Error
or simple do:
>> for each in a:
print(each)
Route Number: 83 Due in 25 minutes.
Route Number: 42 Due in 33 minutes.
# In case if there would be no results (list would be empty), iterating
# over "a" would result in:
>> for each in a:
print(each)
Sorry, there's no real time info for this stop!