times table generator python - syntax error - syntax-error

the error is on line 10. no clue why it crashes. the equals sign is highlighted red once it is run.
code as follows:
import random
question = 1
correct = 0
while question < 10:
a = random.randint(1, 12)
b = random.randint(1, 12)
answer = input(a, 'x', b, '=')
if 'answer' = 'a*b':
print ('correct!')
correct = correct+1
else:
print ('Incorrect\nthe correct answer was', a*b)
print ('You got', correct, 'out of 10 correct')

Change your if statement to this:
if answer == a*b:
Using = assigns the value where == tests equality.
The other issue is that you have too many arguments for the input function. Input takes one argument, that is a string to output to the command line to show the user. Then the input comes in as a string and you cannot directly compare string's to integers so you need to convert the string to an integer.
answer = input("Enter in the answer for {} * {}".format(a,b))
answer = int(answer)

Related

break parameter not ending loop until second input

def county_quiz():
correct = 0
incorrect = 0
print ("End quiz by pressing 0")
while len(seat)>0:
pick = random.choice(list(seat))
correct_answer=seat.get(pick)
print("What is the County seat of",pick,"?")
answer = input(("Your answer: "))
if answer == "0":
incorrect -=1
break
else:
continue
if answer.lower()==correct_answer.lower():
print("That's correct !")
correct+=1
else:
print("That's incorrect.")
print("The correct answer is",correct_answer)
incorrect+=1
print(f"You answered correctly {correct} times")
print(f"You had {incorrect} incorrect answers")
return (correct, incorrect)
This function has a while loop that should be broken after the user inputs "0", but the loop isn't broken until the second time the user inputs "0". I'm not sure why, and don't know how to resolve this.

Converting string element into float problem

Firstly, I have written a code to append data from www.coinmarketcap.com and I did it though. I repeatedly receive data. But it comes with str type. Then I tried to convert it into float but it did not work. The data I received has the form 2,179.87 How can I solve this problem? Thanks in advance!
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome()
values = []
counter = 0
website = driver.get("https://www.binance.com/en/trade/ETH_USDT?theme=dark&type=spot")
while True:
currency = driver.find_element_by_xpath('//*[#id="__APP"]/div/div/div[4]/div/div[1]/div[1]/div/div[2]/div[1]')
print(currency.text)
values.append(float(currency.text))
time.sleep(0.1)
counter += 1
if counter == 300:
break
time.sleep(1)
In the part values.append(float(currency.text)) I got an error called:
could not convert string to float: '2,184.65'
As I mentioned above I cannot convert this string.
See this string 2,179.87 has , in it. So you have to first replace that like this replace(',' , '') and then simply convert to float using float()
a = "2,184.65"
print(type(a))
b = a.replace(',' , '')
c = float(b)
print(type(c))
print(c)
for you specific issue, I think :
values.append(float(currency.text.replace(',' , '')))

ValueError: invalid literal for int() with base 10: 'O'

I am relatively new to python, and as such I don't always understand why I get errors. I keep getting this error:
Traceback (most recent call last):
File "python", line 43, in <module>
ValueError: invalid literal for int() with base 10: 'O'
This is the line it's referring to:
np.insert(arr, [i,num], "O")
I'm trying to change a value in a numpy array.
Some code around this line for context:
hOne = [one,two,three]
hTwo = [four,five,six]
hThree = [seven, eight, nine]
arr = np.array([hOne, hTwo, hThree])
test = "O"
while a != Answer :
Answer = input("Please Enter Ready to Start")
if a == Answer:
while win == 0:
for lists in arr:
print(lists)
place = int(input("Choose a number(Use arabic numerals 1,5 etc.)"))
for i in range(0,len(arr)):
for num in range(0, len(arr[i])):
print(arr[i,num], "test")
print(arr)
if place == arr[i,num]:
if arr[i,num]:
np.delete(arr, [i,num])
np.insert(arr, [i,num], "O")
aiTurn = 1
else:
print(space_taken)
The number variables in the lists just hold the int version of themselves, so one = 1, two = 2 three = 3, etc
I've also tried holding "O" as a variable and changing it that way as well.
Can anyone tell me why I'm getting this error?

Retrieve indices for rows of a PyTables table matching a condition using `Table.where()`

I need the indices (as numpy array) of the rows matching a given condition in a table (with billions of rows) and this is the line I currently use in my code, which works, but is quite ugly:
indices = np.array([row.nrow for row in the_table.where("foo == 42")])
It also takes half a minute, and I'm sure that the list creation is one of the reasons why.
I could not find an elegant solution yet and I'm still struggling with the pytables docs, so does anybody know any magical way to do this more beautifully and maybe also a bit faster? Maybe there is special query keyword I am missing, since I have the feeling that pytables should be able to return the matched rows indices as numpy array.
tables.Table.get_where_list() gives indices of the rows matching a given condition
I read the source of pytables, where() is implemented in Cython, but it seems not fast enough. Here is a complex method that can speedup:
Create some data first:
from tables import *
import numpy as np
class Particle(IsDescription):
name = StringCol(16) # 16-character String
idnumber = Int64Col() # Signed 64-bit integer
ADCcount = UInt16Col() # Unsigned short integer
TDCcount = UInt8Col() # unsigned byte
grid_i = Int32Col() # 32-bit integer
grid_j = Int32Col() # 32-bit integer
pressure = Float32Col() # float (single-precision)
energy = Float64Col() # double (double-precision)
h5file = open_file("tutorial1.h5", mode = "w", title = "Test file")
group = h5file.create_group("/", 'detector', 'Detector information')
table = h5file.create_table(group, 'readout', Particle, "Readout example")
particle = table.row
for i in range(1001000):
particle['name'] = 'Particle: %6d' % (i)
particle['TDCcount'] = i % 256
particle['ADCcount'] = (i * 256) % (1 << 16)
particle['grid_i'] = i
particle['grid_j'] = 10 - i
particle['pressure'] = float(i*i)
particle['energy'] = float(particle['pressure'] ** 4)
particle['idnumber'] = i * (2 ** 34)
# Insert a new particle record
particle.append()
table.flush()
h5file.close()
Read the column in chunks and append the indices into a list and concatenate the list to array finally. You can change the chunk size according to your memory size:
h5file = open_file("tutorial1.h5")
table = h5file.get_node("/detector/readout")
size = 10000
col = "energy"
buf = np.zeros(batch, dtype=table.coldtypes[col])
res = []
for start in range(0, table.nrows, size):
length = min(size, table.nrows - start)
data = table.read(start, start + batch, field=col, out=buf[:length])
tmp = np.where(data > 10000)[0]
tmp += start
res.append(tmp)
res = np.concatenate(res)

structure of while loop

I am trying to use a while loop in Python to provide an error message while there is a backslash character in the user input. The code provides the error message when a fraction is input and requests a second input. The problem occurs when the second input differs in length from the original input and I do not know how to fix this since my knowledge of Python is limited. Any help is appreciated!
size = getInput('Size(in): ')
charcount = len(size)
for i in range(0,charcount):
if size[i] == '/':
while size[i] == '/':
getWarningReply('Please enter size as a decimal', 'OKAY')
size = getInput('Size(in): ')
elif size[i] == '.':
#Convert size input from string to list, then back to string because strings are immutable whereas lists are not
sizechars = list(size)
sizechars[i] = 'P'
size = "".join(sizechars)
That is not a good way to go about doing what you want because if the length of the new size is shorter than the original length, charcount, then you can easily go out of range.
I'm by no means a Python master, but an easily better way to do this is to wrap the entire thing in a while loop instead of nesting a while loop within the for loop:
not_decimal = True
while not_decimal:
found_slash = False
size = getInput('Size(in): ')
charcount = len(size)
for i in range(0, charcount):
if size[i] == '/':
print 'Please enter size as a decimal.'
found_slash = True
break
elif size[i] == '.':
#Convert size input from string to list, then back to string because strings are immutable whereas lists are not
sizechars = list(size)
sizechars[i] = 'P'
size = "".join(sizechars)
if not found_slash:
not_decimal = False