Sum of two numbers Python - python-3.x

This is my code, but the Spyder keeps saying there is an indexError of list index out of range for a = int(tokens[0]). Please advise.
import sys
input_ = sys.stdin.read()
tokens = input_.split()
a = int(tokens[0])
b = int(tokens[1])
print(a+b)
The below also works, but I see someone running the above code in Linux and worked, and I am on windows, wondering what is the cause of the above not running properly. Thanks all!
def sum_of_two_digits(first_digit, second_digit):
return first_digit + second_digit
if __name__ == '__main__':
a, b = map(int, input().split())
print(sum_of_two_digits(a, b))

To prove you're getting the input you expect, you can print(len(tokens)) or simply print(input_). But suffice to say this is not a Linux/Windows issue. Rather, your tokens variable is empty by the time you index into it (tokens[0]).
You're not getting anything into the input_ value. This may be because you're using read() and are inputing the values in an unexpected way (I am guessing?). input() will probably serve you better - note that the 'Linux' version you refer to uses input(). read() will block until you send an escape sequence, though that probably has happened if you get to the list index error.

Related

I'm not getting expected result , I want to know what's wrong with the code

I want to know whether I can use Input function under for loops and Lists?
I'm using the latest version of python 3.7.4.
List=['apple','Pomegranate','orange']
K=print(input('Enter the Value:'))
if (K in List):
print("yes it's in the list")
else:
print("It's not in the list")
If I entered apple I'm getting the result as it's not on the list. I want to know whether we can use Input function under for loops and lists with if-else conditions.
Your issue is with the line
K=print(input('Enter the Value:'))
You do not need print here. Print is a function that takes a value, prints it to your screen and returns None. You passed the input to print, but you want to store the value in K, not print it to the screen (the user is entering the value so they probably do not need to see it again). So change this to:
K=input('Enter the Value:')
Here you can check your error with print function.
List=['apple','Pomegranate','orange']
K=print(input('Enter the Value:'))
print(K)
.....
K is None in this case.

Constructing a hex array from binary data from serial port

I have an external device, serially connected to a PC.
Data is binary, not characters, meaning that I should not interpret data as ASCII characters.
In the PC, I have Python 3.7 that reads the serial device with the use of pyserial.
I want to fill a int8 array with the incoming data.
I am working with threads, here is where I am so far, but this is not my first piece of code, I have tried several things, none of which worked.
def get_data(sent, m_serport)
constr_resp = np.int8([0])
resp = np.int8([0])
resp_index = 0
while (1):
if (m_serport.in_waiting > 0):
resp = master_ser.read(1)
constr_resp = np.concatenate(constr_resp, resp)
resp_index = resp_index + 1
parse(constr_resp, resp_index)
This one generates the following error:
TypeError: 'bytes' object cannot be interpreted as an integer
I have a somewhat strong C background, and Python is very confusing to me when it comes to data types.
I hope my question is easily understood.
Thanks.
I think getting data should start with building a list of bytes:
def get_data(sent, m_serport)
alist = []
resp_index = 0
while (1):
if (m_serport.in_waiting > 0):
resp = master_ser.read(1)
alist.append(resp)
resp_index += resp_index
# parse(alist, resp_index)
return alist
You may not need resp_index since it should just be len(alist). Also I don't think you want the parse in this loop, but I don't know what it's supposed to be doing.
Kostbil, using python to access external data can be a little tricky but trust me, it's no big deal. In this case, debugging might be easier if you know what line the error is...
You could also use print() to debug.
In my opinion, you could call the decode method i.e .decode() on the data you're getting externally before performing any integer operation. say, externalData.decode()
Hope this works.

Indexes and ranges in python

I have this code:
def main():
if (len(sys.argv) > 2) :
P=list()
f= open('Trace.txt' , 'w+')
Seed = int(sys.argv[1])
for i in range(2, len(sys.argv)):
P[i-2] = int(sys.argv[i])
for j in range(0, len(sys.argv)-1) :
Probability=P[j]
for Iteration in (K*j, K*(j+1)):
Instruction= generateInstruction(Seed, Probability)
f.write(Instruction)
f.close()
else:
print('Params Error')
if __name__ == "__main__":
main()
The idea is that I am passing some parameters through the command line. the first is seed and the rest I want to have them in a list that I am parsing later and doing treatments according to that parameter.
I keep receiving this error:
P[i-2] = int(sys.argv[i])
IndexError: list assignment index out of range
what am I doing wrong
PS: K, generateSegment() are defined in a previous part of the code.
The error you see is related to a list being indexed with an invalid index.
Specifically, the problem is that P is an empty list at the time is being called in that line so P[0] is indeed not accessible. Perhaps what you want is to actually add the element to the list, this can be achieved, for example, by replacing:
P[i-2] = int(sys.argv[i])
with:
P.append(int(sys.argv[i]))
Note also that argument parsing is typically achieved way more efficiently in Python by using the standard module argparse, rather than parsing sys.argv manually.
It looks like you might be referencing a list item that does not exist.
I haven't used Python in quite a while but I'm pretty sure that if you want to add a value to the end of a list you can use someList.append(foo)
The problem is that you are assigning a value to an index which does not yet exist.
You need to replace
P[i-2] = int(sys.argv[I])
with
P.append(int(sys.argv[i]))
Furthermore, len(sys.argv) will return the number of items in sys.argv however indexing starts at 0 so you need to change:
for i in range(2, len(sys.argv)):
with
for i in range(2, len(sys.argv)-1):
As you will run into a list index out of range error otherwise

Can I read multiline input() during list comprehension?

This is just for my own curiosity about the language.
I have this working code:
for i in range(n):
name, grade = input(), int(input())
students += [[name, grade]]
Usually with a for loop that's constructing a list, I'm able to write a list comprehension, so I'm curious whether I can in this case.
I've tried a couple of experiments already, both were unsuccessful.
students = [[[name, grade]] for name in input() for grade in input() for i in range(n)]
but I get EOFerror. So maybe it is possible and there's some other error in my code, or maybe it's not at that error is caused by whatever strangeness occurs when I try this.
I also tried:
students = [[[name, grade]] for name, grade in zip(input(), int(input())) for i in range(n)]
Which raises an error informing me the second argument of zip must be iterable.
Yes, you can,
students=[[input(), input()] for i in range(3)]

split a string into a list and use in If Statement

I have a problem with this code. It splits a string into a list and parses through it .I want to do something when I identify a word in the list. I have looked at IF statements and although it makes logical sense the code only produces the statement "screen problem advice" regardless of the sentence inputted. I am a bit stumped as to why i cant use current_word in a conditional statement. Is there something obviously wrong with this?
text=str(input("enter your problem"))
words = text.split()
for current_word in words:
print(current_word)
if current_word=="screen":
print("screen problem advice")
elif current_word=="power":
print("power_problem advice ")
elif current_word=="wifi":
print("connection_problems advice")
Any advice would be much appreciated.
If I run your code on my machine, it works like it should.
Some short pattern for if elif elif elif else is to use some dict() and use the .get()-method for lookups.
Some code like this ...
if word == "one":
variable = "11111"
elif word == "two":
variable = "22222"
elif word == "three":
variable = "33333"
else:
variable = "00000"
... can be written in some much shorter form:
variable = dict(
one="11111",
two="22222",
three="33333"
).get(word, "00000")
Back to your problem. Here is some sample.
I created a detect function which yields all detected advices.
In the main function, the advices are just printed out.
Please note the .lower() inside ISSUES.get(word.lower()), so it catches all variation of "wifi", "Wifi", "WiFi", ...
def detect(message):
ISSUES = dict(
wifi="network problem_advice",
power="power problem_advice",
screen="screen problem_advice"
)
for word in message.split():
issue = ISSUES.get(word.lower())
if issue:
yield issue
def main(message):
[print(issue) for issue in detect(message)]
if __name__ == '__main__':
main("The screen is very big!")
main("My power supply is working fine, thanks!")
main("Wifi reception is very good today!")
Further, I deliberately chose some weird examples to point you to some basic problem with your attempt to solve the problem.
A simple string matching won't be enough, as is produces false-positives in this case.
Try to think of some other approach.

Resources