About Python syntax [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 years ago.
def get_input():
'''
Continually prompt the user for a number, 1,2 or 3 until
the user provides a good input. You will need a type conversion.
:return: The users chosen number as an integer
'''
#pass # REPLACE THIS WITH YOUR CODE
n = input ("Enter the number 1,2 and 3? ")
while n > 0 and n < 4:
print("Invalid Input, give the number between 1 to 3")
n = input ("Enter the number 1,2 or 3? ")
return (n)
get_input()
I am not getting the answer and it's just not working, I am looking for answer like this,
Give me one of 1,2 or 3: sid
Invalid input!
Give me one of 1,2 or 3: 34
Invalid input!
Give me one of 1,2 or 3: -7
Invalid input!
Give me one of 1,2 or 3: 0
Invalid input!
Give me one of 1,2 or 3: 2
Process finished with exit code 0

The input() built-in function returns a value of type str.
As is specified in the (doc)string right after the declaration of function get_input():
You will need a type conversion.
So, you must wrap it in an int() to convert it to an integer int.
n = int(input("Enter the number 1,2 or 3? "))
Then you can use comparison operators to evaluate if it is in the qualified range of accepted values :
# Your comparisons are mixed.
# You can use the in operator which is intuitive and expressive
while n not in [1, 2, 3]:
print("Invalid Input, give the number between 1 to 3")
# remember to wrap it in an int() call again
n = int(input ("Enter the number 1,2 or 3? "))
return (n)
If you supply numbers this works perfectly:
Enter the number 1,2 and 3? 10
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? -1
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? 15
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? 104
Invalid Input, give the number between 1 to 3
But if you supply a single character or a string (type str), you'll get an error:
Enter the number 1,2 and 3? a
ValueError: invalid literal for int() with base 10: 'a'
This is beyond the scope of the question but you might want to look into it.
Anyway, your while condition is setting me off..
It seems that you might be using Python 2 with the print_function imported through __future__. (or else the comparison between different types would raise a TypeError in the while statement).
Check your version of python python -V [in the command line] and:
If using python 2 instead of input() use raw_input():
n = int(raw_input("Enter the number 1, 2, 3: ")
If I am wrong and you are indeed using Python 3.x, use int(input()) as explained.

Related

reason for not taking input of x in the loop in the test case, showing "invalid literal for int() with base 10: '5 4 2 1' " [duplicate]

This question already has answers here:
How to input the number of input in python
(2 answers)
Closed 3 years ago.
I am inserting values in an array but the x = int(input()) is showing eithr EOF error or invalid literal for int() with base 10: '5 4 2 1'
arr = array('i',[])
n = int(input("enter the length of array"))
print(n)
for i in range(n):
x = int(input())
arr.append(x)
Given the error message, you are entering all the numbers on one single line, separated by spaces, then hitting the 'enter' key, so input() returns the string "5 4 2 1", which is indeed not a valid representation of an integer.
Given how your code is written, the simple solution is to just enter one value, hit the 'enter' key, enter the second value, hit the 'enter' key, lather, rinse, repeat... You can make this expectation clearer by passing a prompt string to input(), ie:
for i in range(n):
x = int(input("enter value #{} and hit enter".format(i+1)))
arr.append(x)
Now if you expect your code to be reasonably robust, you want to properly handle wrong user inputs:
def get_integer_input(prompt):
while True:
value = input(prompt).strip()
try:
return int(value)
except ValueError:
print("sorry, '{}' is not a valid integer".format(value))
and then in your code snippet replace all the int(input(...)) calls by a call to this function.
arr=list(map(int,input().split()))
you will get array like this
import array as arr
arr = arr.array('i',[])
n = int(input("enter the length of array"))
print(n)
listt=(list(map(int,input().split())))
for i in listt:
arr.append(i)
print(arr)
input.split() will convert '5 6 7 8' to ['5','6','7','8'] and mapping to int will convert it to [5,6,7,8]

Python Function returing 12 instances of 1 number rather timesing my input my 12

So I'm trying to create a function that allows me to times a users input by 12. However, for example instead of doing 12 x 4 = 64 its gives me 4 12s' e.g. 444444444444
Ive already tried using the return function on its own and Ive tried creating a variable.
Options Ive tried are:
def cube(num):
print("answer =")
return num*12
num1 = input("Enter a number to times by 12: ")
print(cube(num1))
and:
def cube(num):
print("answer =")
answer = num*12
return answer
num1 = input("Enter a number to times by 12: ")
print(cube(num1))
I would expect if input number is 4 i would get 64 but the output is shown as 444444444444
It is because the input is read as a string. If you create string s = 'foo' and do something like this s2 = s*4 then s2 will be equal to foofoofoofoo. To fix your problem convert input to int. So answer = int(num)*12)
When you take in input, you get it as a string first. When you multiply a string, you’ll get repetitions of that string, which is why you’re getting twelve 4s.
You need to convert that input into a number before multiplying it.
Try:
cube(int(num1))
instead.
The function input returns a string, not a number. Multiplying a string by a number repeats the string that many times.
You'll want to convert that string to a number early:
num1 = int(input("Enter a number to times by 12: "))
print(cube(num1))
input("Enter a number to times by 12: ") gets input as string. Python strings allows you to multiply them to a number. The result is a number times repeated string (as you see, 444444444444). If you want to treat input as number, you should convert it to an integer:
num1 = int(input("Enter a number to times by 12: "))
You need to cast the input value to a float or int. input always returns a string.
num1 = float(input('Enter a number to multiply by 12: '))
This will cause a ValueError if you enter something that can’t be converted to a number.
If you need to keep asking for a valid input, I always tend to create a function that does this for me:
def float_input(prompt=''):
while True:
try:
return float(input(prompt))
except ValueError:
print('Invalid Input')
Now replace the input in your code with float_input

How to write a range so that one of the values is left open to user input

I would like to write a function for range where you enter a value when you are calling the function.
def randomRange():
for num in range(0, ())
print num
I would like the user to call the function like this "randomizeRange()"
And then I would like them to enter an integer to represent the maximum value in the range. I'm trying to get a better understanding of how to use the range function.
You need to prompt the user for input using the input() or raw_input() methods and then convert this to an int()
Python 2:
def randomRange():
for it in range(int(raw_input("How many loops?: "))):
print it
Python 3:
def randomRange():
for it in range(int(input("How many loops?: "))):
print(it)
Example >input and >>output:
>>How many loops?:
> 2
>> 0
>> 1

python string and integer comparison

I want to print all the numbers until the given user input using while loop. Example:Enter:5 ==> 1 2 3 4 5 But the below program loops for ever.
user = str(input("Enter : "))
i = 1
while i < user:
print(i)
i = i + 1
ummm while i < int(user):?
Try this instead:
try:
user = int(raw_input('Enter: ')) # Cannot compare a string with an integer.
except ValueError:
print('Input should be an integer!')
i = 1
while True:
i += 1
if i > user:
break
print(i)
Note: In your code, even if we were to explicitly declare the input as an integer it would still not quite work the way you want it to. This is because in your code the while loop stops once i is equal to user (as the condition is while less than... and will thus not print out the final value, user. I therefore modified it so it breaks at the point where i is greater than user, meaning that the last printed value will be equal to user.
Example previous output where user = 5:
1
2
3
4
And with the new code:
1
2
3
4
5
It is however better to use a for loop here, if you are not set on using a while loop:
for i in range(1, user+1):
print(i)
input in Python 2.x will try to evaluate what the user enters, it is equivalent to
user = eval(raw_input(...))
In this case, you are explicitly converting whatever is supplied to a string (with str()). In Python 2.x, strings always compare larger than numbers, so i < user is always True.
It is wiser to use raw_input and convert to int. You can also simplify your code with a for loop:
user = int(raw_input("Enter : "))
for i in range(user):
print(i)
You are comparing an int to a str and that is why you are getting an infinite loop. You should compare the same type of variables
user = int(input("Enter: "))
should work

python while loop unexpected behavior

I'm relatively new to Python, and I don't understand the following code produces the subsequently unexpected output:
x = input("6 divided by 2 is")
while x != 3:
print("Incorrect. Please try again.")
x = input("6 divided by 2 is")
print(x)
the output of which is:
6 divided by 2 is 3
Incorrect. Please try again.
6 divided by 2 is 3
3
Incorrect. Please try again.
6 divided by 2 is
Why is the while loop still being executed even though x is equal to 3?
input() returns a string, which you are comparing to an integer. This will always return false.
You'll have to wrap input() in a call to int() for a valid comparison.
x = int(input("6 divided by 2 is"))
while x != 3:
print("Incorrect. Please try again.")
x = int(input("6 divided by 2 is"))
print(x)
Read more on int() here.
You are getting this error is because you are not parsing the input like so:
x = int(input("6 divided by 2 is"))
If you replace your inputer statement with that, it'll work.
input method gives the string. So you need to typecast to int as:
x = int(input("6 divided by 2 is"))
Here is my answer to your question
Guesses = 0
while(Guesses < 101):
try:
x = int(input("6 divided by 2 is: "))
if(x == 3):
print("Correct! 6 divide by 2 is", x)
break
else:
print("Incorrect. try again")
Guesses += 1
except ValueError:
print("That is not a number. Try again.")
Guesses += 1
else:
print("Out of guesses.")
I am assuming you wanted the user to input a number so i put your code into a while\else loop containing a try\except loop. The try\except loop ensures that if the users inputs a number, a ValueError will appear and it will inform them that what they inputted was not a number. The while\else loop ensures that the user will be inputted the question if the Guesses limit is no higher than 100. This code will ensure that if the user guesses the answer which is 3, the user will be prompted that they got the answer right and the loop will end; if the users guesses anything besides 3 (Number wise) the answer will be incorrect and the user will be prompted the question again; if the user guesses a string it will be classified as a ValueError and they will be notified that their answer wasn't a number and that the user has to try again.
Considering this was asked a long time ago, I'm assuming your probably forgot about this or you figured out the answer but if not try this and tell me if you like this answer. Thank :)
I actually tried this myself now with python 2.6, and did get an int without converting to int. For example, when I try the following:
x = input("6 divided by 2 is")
print "Your input is %s, %s" % (x, type(x))
I get the following:
6 divided by 2 is 2
Your input is 2, <type 'int'>
So is this a version issue? Or maybe an environment issue (I'm using OS X)?
What I do conclude is that it should be a good practice using previous recommendations using int().

Categories