isinstance() not working the way I think it should [duplicate] - python

This question already has answers here:
Read an integer list from single line input along with a range using list comprehension in Python 3
(2 answers)
Closed 3 years ago.
My program requires a user input of a list of two elements, so to check if those conditions are satisfied I used the following code:
start = input('Enter you start location.\nE.g. Enter "[2,5]" for x-coordinate 2 and y-coordinate
5.')
while isinstance(start, list) == False or len(start) != 2:
start = input('Try again.')
This will never exit the while loop no matter what I input. Why?

Because your start variable turns out to be a string:start = "[2,5]", which is not a list. You can ask the user to input e.g 2,3,
then you get "2,3". You then can split it to a list using start.split(',')

Absolutely not recommanded for obvious security risk, but you can use eval.
start = eval(input('Enter you start location.\nE.g. Enter "[2,5]" for x-coordinate 2 and y-coordinate 5.'))
A prefered way is by using split, but in this case ask the user to enter coordinate separated by a coma.
start = input('Enter you start location.\nE.g. Enter "2,5" for x-coordinate 2 and y-coordinate 5.')
start = start.split(",")
Edit as recommanded by #soyapencil comments
inp_str = input('Enter you start location.\nE.g. Enter "[2,5]" for x-coordinate 2 and y-coordinate 5.')
start = [int(i) for i in iter(eval(inp_str,{}))]

Related

Basic math in python [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
The code below is giving me a return of 25 with inputs of 3 & 4. Obviously it should be 7. This is a problem for school and I can't edit the first 3 lines or the last one. What am I missing here?
total_owls = 0
num_owls_A = input()
num_owls_B = input()
num_owls_A = int(input())
num_owls_B = int(input())
total_owls = (num_owls_A + num_owls_B)
print('Number of owls:', total_owls)
input() returns input value as a string. So, you are basically concatenating strings not integers.
If you want to add them as numbers you need to convert them to numbers first like below
num_owls_A = int(input())
num_owls_B = int(input())
Again, this will create an error, if you input a non-numerical value, so you need to handle the exceptions in such case.

How to check a part of an input | Python [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
Closed 1 year ago.
I want to check a specific part of an input but I don't know "where" it is
I tried with this:
a = input('Enter command')
if a[0:5] == '(Command name)':
if a[7:?] == '(Subject)':
if a[?:len(a)] == '(Choice)':
To be continued
So, the input is divided into three parts; The command, the subject, and which type of the command it will run.
But which index should the ? be? I don't know the length of the word. Is it impossible?
No, I know that I can make it, just not how.
I suppose your input should go something like this:
command subject choice
So there are basically three parts(might be more). I suggest you break the input in list as:
a = [str(x) for x in input().split()]
To get the length of each entities:
len(entity)
And for index you can use index():
list.index(entity)
If they are always one word, maybe something like this will work:
terms = a.strip().split(" ")
command_name = terms[0]
subject = terms[1]
choice = terms[2]
if there is a possibility of double spaces, it needs to be more clever
the above is the same as
command_name, subject, choice = a.strip().split(" ")

How to use do/while? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Python: How to keep repeating a program until a specific input is obtained? [duplicate]
(4 answers)
Closed 3 years ago.
I want to get a user input which is bigger than zero. If user enters anything else than a positive integer prompt him the message again until he does.
x = input("Enter a number:")
y= int(x)
while y<0:
input("Enter a number:")
if not y<0:
break
If I add a bad value first then a good one it just keeps asking for a new one. Like Try -2 it asks again but then I give 2 and its still asking. Why?
The first time you assign the result of input to x, and convert x to a number (int(x)) but after the second call to input you don't. That is your bug.
That you have a chance to get this bug is because your code has to repeat the same thing twice (call input and convert the result to a number). This is caused by the fact that Python unfortunately does not have the do/while construct, as you mentioned (because there was no good way to use define it using indentation and Python's simple parser, and now it's too late).
The usual way is to use while True with break:
while True:
x = input("Enter a number:")
y = int(x)
if not y<0:
break
You assign a value to y before the while loop, then you enter the loop without assigning a value to y from the input.
Just change your code:
x = input("Enter a number:")
y= int(x)
while y<0:
y = int(input("Enter a number:"))
print('out?')

Accepting an unknown number of variables using input() [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
I am trying to create a bounded rectangle using a random number of points that are provided by the user. The reason this is difficult for me is because all the numbers must be accepted on only one line, I don't know how many variables the user will provide, and since I am accepting points, I must have the right amount (evens).
Here is a sample run:
Enter the points:
``>>>4 1 3 5 1 5 9 0 2 5
My primary question is how do I unpack a random number of points? And also, how do I pair the even points together?
In Python 2:
points = map(int, raw_input().split())
In Python 3:
points = list(map(int, input().split()))
Another method - list comprehension:
points = [int(p) for p in input().split()]
To pair x and y of the points together you can use something like pairwise() on the points list: see https://stackoverflow.com/a/5389547/220700 for details.
If they are read as a string, you can use the split() method, which will return a list, then use map() to convert the items of the list to integers:
points_input = raw_input("Enter the points:")
points = map(int, points_input.split())
print points
Notes
The result (points) will be a list of integers.
If you are using Python 3.x, you have to use the method input() instead of raw_input().

How to keep increasing variable number in loop inpython [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 months ago.
I need to create a code where the user can input a certain number of courses, and then it will take the gpa of them, but how can I change the variable name in the loop?
I have this so far
number_courses= float(input ("Insert the number of courses here:"))
while number_courses>0:
mark_1= input("Insert the letter grade for the first course here: ")
if mark_1=="A+" :
mark_1=4.0
number_courses= number_courses-1
If I want to change the variable name of mark_one to something different each time I go through the loop, what is the simplest way I can do this? And also is it possible to change it in my input statement to ask for first, second, third... as I go through the loop? I have tried searching on google, but none of the answers I can understand as their code is far behind my level or they didn't seem to answer what I needed either. Thanks.
You want to use a list or something similar to gather the input values:
number_courses=input("Insert the number of courses here: ")
marks = []
while number_courses>0:
mark = input("Insert the letter grade for the first course here: ")
if mark == "A+":
mark = 4.0
marks.append(mark)
number_courses -= 1
print marks
Use a dictionary:
number_courses= float(input ("Insert the number of courses here:"))
marks = {'A+':4, 'A':3.5, 'B+':3}
total_marks = 0
while number_courses:
mark_1= input("Insert the letter grade for the first course here: ")
if mark_1 in marks:
total_marks += marks[mark_1] #either sum them, or append them to a list
number_courses -= 1 #decrease this only if `mark_1` was found in `marks` dict

Categories