Trouble using exponents in python 3.6 [duplicate] - python-3.x

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I'm trying to create a script that allows users to input numbers and then the numbers are used for to create an exponent. Here's what i'm writing. I'm in python 3.6 and using anaconda/spyder.
print ("Enter number x: ")
x = input()
print ("Enter number y: ")
y = input()
import numpy
numpy.exp2([x,y])
so what I want is for the user to enter a value for x. for example 2. then enter a value for y. for example 3. then i'd like (with the help of numpy) create the exponent 2**3 which equals 8. instead i get this.
Enter number x:
2
Enter number y:
3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
execfile(filename, namespace)
File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/Ameen/Desktop/assignment1.py", line 16, in <module>
numpy.exp2([x,y])
TypeError: ufunc 'exp2' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
I tried print ('xy') but that printed xy. so i came across this site https://docs.scipy.org/doc/numpy/reference/generated/numpy.exp2.html#numpy.exp2 they suggested np.exp2. when I tried np.exp2([x**y]) it says np is not defined and an error message saying the numpy library is not imported. so now i'm trying numpy.exp2 and got the error above.

Convert strings to integers:
import numpy
print('Enter number x:')
x = int(input())
print('Enter number y:')
y = int(input())
print(numpy.exp2([x, y])) #=> [ 4. 8.]

Related

I am getting a raise key error in my python script. How can I resolve this?

I am hoping someone can help me with this. After having a nightmare installing numpy on a raspberry pi, I am stuck again!
The gist of what I am trying to do is I have an arduino, that sends numbers (bib race numbers entered by hand) over lora, to the rx of the raspberry pi.
This script is supposed to read the incoming data, - it prints so I can see it in the terminal. Pandas is then supposed to compare the number against a txt/csv file, and if it matches in the bib number column it is supposed to append the matched row to a new file.
Now, The first bit works (capturing the data and printing) and on my windows PC, the 2nd bit works when I was testing with a fixed number rather than incoming data.
I have basically tried my best to mash them together to get the incoming number to compare instead.
I should also state that the error happened after I pressed 3 on the arduino (which then printed on the terminal of the raspberry pi before erroring), so probably why it is keyerror 3
My code is here
#!/usr/bin/env python3
import serial
import csv
import pandas as pd
#import numpy as np
if __name__ == '__main__':
ser = serial.Serial('/dev/ttyS0', 9600, timeout=1)
ser.flush()
while True:
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8').rstrip()
print(line)
with open ("test_data.csv","a") as f:
writer = csv.writer(f,delimiter=",")
writer.writerow([line])
df = pd.read_csv("data.txt")
#out = (line)
filtered_df = df[line]
print('Original Dataframe\n---------------\n',df)
print('\nFiltered Dataframe\n------------------\n',filtered_df)
filtered_df.to_csv("data_amended.txt", mode='a', index=False, header=False)
#print(df.to_string())
And my error is here:
Python 3.7.3 (/usr/bin/python3)
>>> %Run piserialmashupv1.py
3
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 3361, in get_loc
return self._engine.get_loc(casted_key)
File "pandas/_libs/index.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: '3'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/pi/piserialmashupv1.py", line 20, in <module>
filtered_df = df[line]
File "/home/pi/.local/lib/python3.7/site-packages/pandas/core/frame.py", line 3455, in __getitem__
indexer = self.columns.get_loc(key)
File "/home/pi/.local/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 3363, in get_loc
raise KeyError(key) from err
KeyError: '3'
>>>
I had been asked to put the first few lines of data.txt
_id,firstname,surname,team,info
1, Peter,Smith,,Red Walk (70 miles- 14 mile walk/run + 56 mile cycle)
2, Samantha,Grey,Team Grey,Blue walk (14 mile walk/run)
3, Gary,Parker,,Red Walk (70 miles- 14 mile walk/run + 56 mile cycle)
I think it must be the way I am referencing the incoming rx number?
Any help very much appreciated!
Dave
I have it working, see the final code below
I know that Pandas just didnt like the way the data was inputting originally.
This fixes it. I also had to ensure it knew it was dealing with an integer when filtering, as the first attempt I didn't, and it couldn't filter the data properly.
``
import serial
import csv
import time
import pandas as pd
if __name__ == '__main__':
ser = serial.Serial('/dev/ttyS0', 9600, timeout=1)
ser.flush()
while True:
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8').rstrip()
print(line)
with open ("test_data.txt","w") as f:
writer = csv.writer(f,delimiter=",")
writer.writerow([line])
time.sleep(0.1)
ser.write("Y".encode())
df = pd.read_csv("data.txt")
out = df['_id'] == int(line)
filtered_df = df[out]
print('Original Dataframe\n---------------\n',df)
print('\nFiltered Dataframe\n---------\n',filtered_df)
filtered_df.to_csv("data_amended.txt", mode='a',
index=False, header=False)
time.sleep(0.1)
``

How do I fix this EOF error on python 3 version

I am working on a very basic problem on Hackerrank.
Input format:
First line contains integer N.
Second line contains string S.
Output format:
First line should contain N x 2.
Second line should contain the same string S.
sample test case
5
helloworld
my code is as: (on PYTHON 3)
n=int(input())
s=input()
print(2*n)
print(s)
I am getting error:
Execution failed.
EOFError : EOF when reading a line
Stack Trace:
Traceback (most recent call last):
File "/tmp/143981299/user_code.py", line 1, in <module>
N = int(input())
EOFError: EOF when reading a line
I tried this method to take input many times and this is the first time I am having this error. Can anyone please explain why?
use a try/except block to handle the error
while True:
try:
n=int(input())
s=input()
print(2*n)
print(s)
except:
break

how to make a greater than or lower than with tkinter StringVar

My code keeps giving this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "d:/Python Code stuff I did/print.py", line 209, in <lambda>
button = Button(root,text="Change Config", width=20, height=3, bg="#0f0f0f",fg="#ffffff", command=lambda:[do_it(), do_it1(), do_it2(), do_it3(),do_the_it(),do_the_it1()])
File "d:/Python Code stuff I did/print.py", line 149, in do_the_it
if str(number_1) > 4:
TypeError: '>' not supported between instances of 'str' and 'int'
I want it to check if that specific number is greater than 4 for example i input a number for example lets say its 7 I want it to print and that number is too high here is my code:
def do_the_it():
a = updater['Trading Settings']['minimum_offer'].value
updater.read('settings.ini')
updater['Trading Settings']['minimum_offer'].value = number_1.get()
updater.update_file()
updater.read('settings.ini')
updater['Trading Settings']['maximum_offer'].value = number_2.get()
updater.update_file()
if str(number_1) > 4:
print("Number can only exceed to 4")
updater.read('settings.ini')
updater['Trading Settings']['minimum_offer'].value = 4
updater.update_file()
You can't compare a string to a number. Use:
if float(number_1.get()) > 4:
You can also use int(), but if some joker enters a decimal point, this will prevent errors.

invalid literal for int() with base 10 Keras pad sequence

Traceback (most recent call last):
File "C:/Users/Lenovo/PycharmProjects/ProjetFinal/venv/turkish.py", line 45, in <module>
sequences_matrix = sequence.pad_sequences(sequences,maxlen=max_len)
File "C:\Users\Lenovo\PycharmProjects\ProjetFinal\venv\lib\site-packages\keras_preprocessing\sequence.py", line 96, in pad_sequences
trunc = np.asarray(trunc, dtype=dtype)
File "C:\Users\Lenovo\PycharmProjects\ProjetFinal\venv\lib\site-packages\numpy\core\_asarray.py", line 85, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: invalid literal for int() with base 10:
windows loading yapıo sonra mavi ekran iste. simdi repair yapıyo bkalım olmazsa
gelirim size.
X = dft.text
your straight using text with pad_sequence. this is how pad_sequence doesn't work
Generally, every text is converted into numbers within a given vocab which can be of characters or words depend upon task.
then it can be padded.
please refer some tutorial through you can understand how to process text first.
Tensorflow tutorials - text part are good to start.
https://www.tensorflow.org/guide/keras/masking_and_padding

Python 3.5.3 KeyError: 0 returned from random.choice()

here's my code:
fList = {7:7, 9:9}
def checkList():
if not None in fList:
print(fList)
fL = random.choice(fList)
ttt[fL] = computerLetter
del fList[fL]
print(fL)
print(ttt)
print(fList)
Python throws me this error:
{9: 9, 7: 7}
Traceback (most recent call last):
File "/home/jason/Desktop/Programming/Python3_5/TestCode.py", line 35, in <module>
checkList()
File "/home/jason/Desktop/Programming/Python3_5/TestCode.py", line 22, in checkList
fL = random.choice(fList)
File "/usr/lib/python3.5/random.py", line 265, in choice
return seq[i]
KeyError: 0
This was working fine when there were move key:value pairs in the dictionary. I'm having trouble understanding whats wrong. Thank you in advance for your time and attention.
From looking at your code it seems you expect random.choice to choose a key from you dictionary, so what you need to do is:
random.choice(list(fList.keys()))
BTW, I don't think you are using you conditional (if) properly. Currently it means that it will be executed only if fList doesn't have a key None (i.e. if your list was fList = {7:7, 9:9, None:5} it wouldn't execute). What I think you meant is if fList is not None, this means that it will only execute if it is defined

Resources