I get this error "TypeError: Can't convert 'int' object to str implicitly"
when I try to run this code. it's on the x += 1 line.
The goal of this program is to receive input such as "RA1" or "R04" and add 1 to the value, which always starts at 0. I then want it to "print" the results when I type END. This is proving to be quite the challenge. Python 3.5.1
x = 0
y = 0
z = 0
print("Enter 3 digit code.")
x = str(input())
while x != "END":
if x == "RA1":
x += 1
continue
elif x == "R04":
y += 1
continue
elif x == "etc":
z += 1
continue
else:
print('Please enter a 3 digit value or END')
There were multiple problems in your code.
The cause of the TypeError was that you unintentionally made x a string by writing x = str(input()) and when you wanted to add 1 to it, Python tried to convert 1 to a string to concatenate it to x.
The infinite loop was unrelated to the TypeError you received. It occurred because of the misplacement of the str(input()) call.
This is the working code with the fixed while loop:
x = 0
y = 0
z = 0
i = ""
print("Enter 3 digit code.")
while i != "END":
i = input()
if i == "RA1":
x += 1
elif i == "R04":
y += 1
elif i == "etc":
z += 1
else:
print('Please enter a 3 digit value or END')
print(str(x) + " " + str(y) + " " + str(z))
You need to cast your integers into strings by wrapping each with str().
Afterwards, use x = raw_input() for your inputs. When you first enter the loop, you need to take an input, but also when you loop back around. So, therefore, you need a way to stop your infinite loop. Hence, x = raw_input() needs to be added at the start of the loop.
You can actually just get your input at the start of the loop, there's no need for 2.
Additionally, your x, y and z should also just be empty strings or null, not 0.
x = ""
y = ""
z = ""
while x != "END":
print("Enter 3 digit code.")
x = raw_input()
if x == "RA1":
x += str(1)
continue
if x == "R04":
y += str(1)
continue
elif x == "etc":
z += str(1)
continue
else:
print('Please enter a 3 digit value or END')
Related
I'm here with my code, here you can see it:
def generate_integer(level):
score = 0
i = 0
false = 0
level = int(level)
while i != 10:
# Choosing the numbers of digit if 1 >> 1-9 / if 2 >> 11-99 / if 3 >> 100-999
end = 10**level-1
# Define x and y
x = random.randint(0,end)
y = random.randint(0,end)
answer = x + y
# Users cal
user = int(input(f'{x} + {y} = '))
if user == answer:
score = score + 1
while user != answer:
false + 1
print('EEE')
user = int(input(f'{x} + {y} = '))
if false == 3:
print(f'{x} + {y} = {answer}')
i = i + 1
print(f'score: {score}/10')
Let me explain: I defined false for, if user inputs the answer 3 times and all of them for that question are false, show user the answer and continue asking
Actually this code asks 10 different math questions, this is a part of my code, I'm checking if answer is not true print('EEE') and re ask it again, but if user tries 3 time and all incorrect, then I show the answer, pass that question and keep asking other questions.
If you have any ideas for re asking question, when users input was non-numerical, I'll be thankful.
You just have an indentation wrong
def generate_integer(level):
score = 0
i = 0
false = 0
level = int(level)
while i != 10:
# Choosing the numbers of digit if 1 >> 1-9 / if 2 >> 11-99 / if 3 >> 100-999
end = 10**level-1
# Define x and y
x = random.randint(0,end)
y = random.randint(0,end)
answer = x + y
# Users cal
user = int(input(f'{x} + {y} = '))
if user == answer:
score = score + 1
while user != answer:
false + 1
print('EEE')
user = int(input(f'{x} + {y} = '))
if false == 3:
print(f'{x} + {y} = {answer}')
break
i = i + 1
print(f'score: {score}/10')
Would probably work, because you want to be checking for how many times they messed up within the while loop.
OTHER PIECES OF ADVICE
I would also rename false to num_incorrect_tries, and replace 10**level-1 with 10**(level-1)
You can also just for for i in range(11), instead of doing a while loop, and incrementing i
What you can do is ask for the input in a separate function inside of a while True loop that only exits when it detects the input to be an integer. In my example below the getint function does just that.
I made a few other minor adjustments to your function to simplify it a little as well. I have tested and can confirm it does work the way you describe.
I left some inline notes to explain where I made changes
import random
def getint(x,y):
while 1:
user = input(f'{x} + {y} = ') # get user input
if user.isdigit(): # check if it is an integer
return int(user) # return integer value
print("Non-Integer Input Detected: Try Again") # print Error
def generate_integer(level):
score = false = i = 0 # all three are zero
level = int(level)
while i != 10:
end = 10**level-1
x = random.randint(0,end)
y = random.randint(0,end)
answer = x + y
while getint(x, y) != answer: # while the user input != answer
false += 1 # increment false number
if false == 3: # if 3 wrong answers
print(f'{x} + {y} = {answer}') # print the answer
false = 0 # reset false
break # end while loop
print('EEE') # show error
else:
score = score + 1 # increase score for correct answer
i = i + 1
print(f'score: {score}/10')
def check(user_answer,correct_answer):
for a chance in range(2):
print("Wrong answer, try again")
user_answer=input('User please type your answer for the question')
if user_answer == correct_answer:
return 'True' # Given the Right answer
else:
print('Again wrong answer')
return 'False' #Given all wrongs answers
user_answer=input('User please type your answer for the question')
correct_answer=10
if user_answer != correct_answer:
result=check(user_answer,correct_answer)
if result:
print("your answer is correct")
else:
print("your all answers were wrong, the right answer is: ",correct_answer)
else:
print("Perfect your answer was right in the first guess")
So I am writing a python tiktaktoe game as a project. I am required to use multidimensional arrays and have no errors. In the function p_turn() (Which manages the player move), I was going to implement an if statement to check whether the move is valid (between 1 and 3). But now, no matter what number I put in, it still says that the move is invalid.
The desired outcome is for the game not to allow numbers that aren't between 1 and 3.
def p_turn():
system(command='cls')
print_board()
p_play_1 = int(input("Choose a position for the Y between 1 and 3 --> "))
p_play_2 = int(input("Choose a position for the X between 1 and 3 --> "))
if p_play_1 != 1 or p_play_1 != 2 or p_play_1 != 3 or p_play_2 != 1 or p_play_2 != 2 or p_play_2 != 3: # This is whats not working correctly
print("This is not a valid move. The values must be betweeen 1 and 3! ")
time.sleep(3)
p_turn()
if board[p_play_1 - 1][p_play_2 -1] == " ":
board[p_play_1 - 1][p_play_2 - 1] = "X"
system(command='cls')
print_board()
c_turn() # Computer play
elif board[p_play_1 - 1][p_play_2 - 1] == "X" or [p_play_1 - 1][p_play_2 - 1] == "O":
print("Someone already went there! ")
time.sleep(3)
p_turn()
Also, if it's important, this is how I store my board.
board = [[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "]]
def print_board():
print()
print(f"{board[0][0]} | {board[0][1]} | {board[0][2]}")
print("---------")
print(f"{board[1][0]} | {board[1][1]} | {board[1][2]}")
print("---------")
print(f"{board[2][0]} | {board[2][1]} | {board[2][2]}")
print()
Rename p_turn to player_turn. That way you give your function much more meaning. The same applies to c_turn - cumputer_turn is far more clear. In your small example, it doesn't make that big a difference but in larger projects, naming is really important!
p_play_1 and p_play_2 would make much more sense if they were simply named x and y.
Your boundary check is essentially:
if x != 1 or x != 2 or x != 3 or # ... repeat for y
That can't work. The above if condition is evaluated from left to right and terminates as soon as something is True. Take for example x = 2 (which is a valid coordinate). x != 1 evaluates to True and your move is considered invalid.
There are many ways to check whether a variable is within a certain range in Python.
Using comparison operators:
if lower_bound <= value <= upper_bound:
# value is between lower and upper bound
Using range():
if value in range(lower_bound, upper_bound + 1):
# value is between lower and upper bound
You could try something like this:
while not 1 <= (p_play_1 := int(input("Choose a position for the Y between 1 and 3 --> "))) <= 3:
print(f"Invalid Y position: {p_play_1}")
while not 1 <= (p_play_2 := int(input("Choose a position for the X between 1 and 3 --> "))) <= 3:
print(f"Invalid X position: {p_play_2}")
I'm trying to make a program that simply adds or subtracts 2 numbers. I have the code below:
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
print("Would you like to add or subtract?")
txt = input("Type 'a' for add or 's' for subtract")
if txt == "a" or "A":
x + y == z
if txt == "s" or "S":
x - y == z
else:
return
else:
return
print (z)
I know the return isn't right but not sure how I should work this out.
first of all when you write:
x + y == z
you are not defining a new z variable, but just making the logical operation "is x + y equal to z?" where z is not even defined. If you want to define z as the sum or difference of x and y you should use:
z = x + y or z = x - y
Also, when you want to make a structure of the kind "if condition is equal to something, else if condition is equal to something else" you can use if, else and elif (which is both else and if togheter), but you have to be sure that they have the same indentation.
The following code should do the job: (Edited)
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
print("Would you like to add or subtract?")
txt = input("Type 'a' for add or 's' for subtract")
if txt == "a" or txt=="A":
z = x + y
elif txt == "s" or txt=="S":
z = x - y
print (z)
Edit: you did not define a function, therefore you don't need to use "return". Return is used to give the result of a function, for example:
def sum(x, y):
z = x + y
return(z)
Edit #2: Thank you for making me note that txt == 'a' or 'A' would always be true, i've now repaired the code.
First: x + y == z is a test for equality. It checks if x + y and z are equal. To assign the result of x + y to z, you need to do z = x + y.
For such problems, it really helps to draw a flowchart or at least write out the steps you are going to implement in your code, especially when you're beginning programming. Here's an example. Pay attention to the indentation of my numbered list. This is similar to the indentation that you will expect to see in your Python code.
Take two numbers
input() returns a string, so convert to integers
Ask for the operator
input() to take a string.
If the operator is "a" or "A" (See note 1)
do addition
Instead, if the operator is "s" or "S"
do subtraction
If the operator is none of the above
do nothing? Show an error?
In the end, print the output
The code for the algorithm we discussed above would be:
x = int(input("Enter a number: ")) # 1.
y = int(input("Enter a number: ")) # 1.
print("Would you like to add or subtract?") # 2.
txt = input("Type 'a' for add or 's' for subtract")
if txt == "a" or txt == "A": # 3.
z = x + y
elif txt == "s" or txt == "S": # 4.
z = x - y
else: # 5.
z = 0
print("Invalid choice!")
print (z) # 6.
Your code goes wrong here:
If the operator is "a" or "A"
do addition
Now, if the operator is "s" or "S" (Can it be "s" or "S"? No, because we already established that it's "a" or "A" in 3. above )
do subtraction
Note 1: In human languages, we say
Check if txt is "a" or "A"
But Python works with booleans for the if condition. If we did if txt == "a" or "A", this would evaluate to if [[(txt == "a") is true] or ["A" is true]]. Because non-empty strings are truthy in Python, ["A" is true] would always be correct and so [[(txt == "a") is true] or ["A" is true]] would always be true, so we'd always go into the if statement. Not what we wanted to happen!
We have to compare each one separately like so:
if txt == "a" or txt == "A":
Alternatively, we can convert txt to lower or upper case and have a single check
if txt.lower() == "a":
Or,
if txt.upper() == "A":
Alternatively, we could check whether txt is one of the elements in a list.
if txt in ["a", "A"]:
You need to do z = x + y and z = x - y instead of x + y == z and x - y == z. Double equals to is a comparison operator.
The below code should work:
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
z = 0
print("Would you like to add or subtract?")
txt = input("Type 'a' for add or 's' for subtract")
if txt == "a" or "A":
z = x + y
elif txt == "s" or "S":
z = x - y
//you can use return if it's a function
return z;
print (z)
I'm a beginner programmer and chose python[3.8] as my choice to learn. I don't even know what to ask or how to search this site. My program counts 30 to 40 and prints 'Go' for multiples of 3 and strings of 3 and remainders of 3. It counts Go's. Output should be 10 but it's 3. It's not counting the strings. There is no error msgs.
`enter code here`
s = '3'
x = 40
y = 30
num = 0
while y < x :
y=y+1
if y % 3 == 0 or y % 10 == 3 or s in 'y' :
print('Go',y)
num = num + 1
print(num, 'Go\'s')
I think the problem here is to understand how python works.
When you write s in 'y' it will always return false because y here is a character that composes the string which value is ythe character.
So what you'll need to do is use the function str(param) to convert your integer to a string with the same value.
This is a code that works the way you want to.
s = '3'
x = 40
y = 30
num = 0
while y < x :
if y % 3 == 0 or y % 10 == 3 or s in str(y) :
print('Go',y)
num = num + 1
y=y+1
print(num, 'Go\'s')
I already solved this with list.append() function however my instructor told me to just use the basic python functions. Here is my code:
a = 0
b = 0
s = 0
x = str(s)
print ('Enter the first number: ', end = '')
c = input()
a = int(c)
finished = False
while not finished:
print ('Enter the next number (0 to finish): ', end ='')
n = input()
b = int(n)
if b != 0:
if b == a:
x = ('Same')
elif b > a:
x = ('Up')
elif b < a:
x = ('Down')
a = b
s = x
else:
finished = True
print (str(x))
I am aiming to print (e.g. Up Down Up Down Same in comparing the input integers) in one line at the end of the while loop. Let me know how can I improve my code. Thank you very much
Use string concatenation to get the result you want without using a list:
http://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python
I'll give you two hints on how to do this for your program:
Initialize x as an empty string by replacing
x=str(s)
with
x=""
There is no need for it to begin as the string "0", which str(s) does since s is 0.
Instead of saying
x=('SAME')
x=('UP')
x=('DOWN')
try saying
x=x+'SAME'
x=x+'UP'
x=x+'DOWN'
I removed the parentheses because they are not necessary.
As for style, it is good practice to name your variables as useful things instead of just letters. Last staement in an if/else chain that covers all bases should just be else. Best of luck to you sir
Not sure what result you're looking for, but perhaps this works:
a = 0
b = 99
result = ""
a = int(input('Enter the first number: '))
while b != 0:
b = int(input('Enter the next number (0 to finish): '))
if b == a:
result += ' Same'
elif b > a:
result += ' Up'
elif b < a:
result += ' Down'
a = b
print(result.strip())
Output:
Enter the first number: 12
Enter the next number (0 to finish): 12
Enter the next number (0 to finish): 12
Enter the next number (0 to finish): 1
Enter the next number (0 to finish): 1
Enter the next number (0 to finish): 5
Enter the next number (0 to finish): 0
Same Same Down Same Up Down
You can simply initialize x with an empty string and keep concatenating to it.
a = 0
b = 0
s = 0
x = ''
print('Enter the first number: ', end='')
c = input()
a = int(c)
finished = False
while not finished:
print('Enter the next number (0 to finish): ', end='')
n = input()
b = int(n)
if b != 0:
if b == a:
x += 'Same\n'
elif b > a:
x += 'Up\n'
elif b < a:
x += 'Down\n'
a = b
s = x
else:
finished = True
print(str(x))