I'm trying to write a program that asks the user for 4 integers and prints the largest odd number that was entered. Here is the code:
a = raw_input("Enter an int: ")
b = raw_input("Enter an int: ")
c = raw_input("Enter an int: ")
d = raw_input("Enter an int: ")
numbers = [a, b, c, d]
odd_numbers = []
print numbers
for i in numbers:
if i%2!=0:
odd_numbers.append(i)
else:
print "This is not an odd number."
for nums in odd_numbers:
max_num = max(odd_numbers)
print max_num
And here is the error that I'm receiving:
line 10, in <module>
if i%2!=0:
TypeError: not all arguments converted during string formatting
What am I doing wrong ?
raw_input() returns a string. As a result, numbers list becomes a list of strings. % operation behavior depends on the variable type, in case of string it is a string formatting operation:
>>> s = "3"
>>> s % 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
In case of int, it gives you a division remainder:
>>> n = 3
>>> n % 2
1
You need to convert all the inputs to int:
a = int(raw_input("Enter an int: "))
b = int(raw_input("Enter an int: "))
c = int(raw_input("Enter an int: "))
d = int(raw_input("Enter an int: "))
To avoid having a redundant code, you can simplify filling the numbers list using list comprehension:
numbers = [int(raw_input("Enter an int: ")) for _ in xrange(4)]
Because You are input is string convert it into int
>>> a =raw_input("Enter an int: ")
Enter an int: 10
>>> type(a)
<type 'str'>
Try This :
a =int(raw_input("Enter an int: "))
b = int(raw_input("Enter an int: "))
c = int(raw_input("Enter an int: "))
d = int(raw_input("Enter an int: "))
OR
for i in numbers:
if int(i)%2!=0:
odd_numbers.append(i)
Your Output Should be look like this :
>>>
Enter an int: 10
Enter an int: 20
Enter an int: 20
Enter an int: 50
[10, 20, 20, 50]
This is not an odd number.
This is not an odd number.
This is not an odd number.
This is not an odd number.
raw_input will return you a string. So, each element in numbers are string like
numbers = ["1", "2", "3", "4"]
When you try i%2, python evaluates % as the string formatting operator but could not find any place-holder in the string for formatting and raise error. So you must parse your input to int
a = int(raw_input("Enter an int: "))
Or you can use input, which will evaluate your input to proper type (int in your case)
a = input("Enter an int: ")
But using input is not recommended if you are not experienced with it and eval as it states in the docs:
Equivalent to eval(raw_input(prompt)).
This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.
If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.
Consider using the raw_input() function for general input from users.
You input strings but you need to do calculations with ints.
I you do print type(a) for instance you will see that you actually got a string as input. The way to parse it to an int is to use the built in function int().
a = raw_input("Enter an int: ")
b = raw_input("Enter an int: ")
c = raw_input("Enter an int: ")
d = raw_input("Enter an int: ")
numbers = [a, b, c, d]
odd_numbers = []
print numbers
for i in numbers:
value = int(i)
if value%2!=0:
odd_numbers.append(value)
else:
print "This is not an odd number."
for nums in odd_numbers:
max_num = max(odd_numbers)
print max_num
Related
The purpose of my code is for the output to give the number and the type of the input. For instance:
If the input is: 10
The output should be: 10 is an integer
If the input is: 10.0
The output should be: 10.0 is a float
If the input is: Ten
The output should be: Ten is a string
I am quite a beginner with programming so I don't know any "advanced" functions yet. I shouldn't have to use it either because this is a starting school assignment. Normally I should be able to solve this with if, elif and else statements and maybe some int (), float () and type () functions.
x = input("Enter a number: ")
if type(int(x)) == int:
print( x, " is an integer")
elif type(float(x)) == float:
print( x, "is a float")
else:
print(x, "is a string")
However, I keep getting stuck because the input is always given as a string. So I think I should convert this to an integer / float only if I put this in an if, elif, else statements, then logically an error will come up. Does anyone know how I can fix this?
REMEMBER: Easy to ask forgiveness than to ask for permission (EAFP)
You can use try/except:
x = input("Enter a number: ")
try:
_ = float(x)
try:
_ = int(x)
print(f'{x} is integer')
except ValueError:
print(f'{x} is float')
except ValueError:
print(f'{x} is string')
SAMPLE RUN:
x = input("Enter a number: ")
Enter a number: >? 10
10 is ineger
x = input("Enter a number: ")
Enter a number: >? 10.0
10.0 is float
x = input("Enter a number: ")
Enter a number: >? Ten
Ten is string
Since it'll always be a string, what you can do is check the format of the string:
Case 1: All characters are numeric (it's int)
Case 2: All numeric characters but have exactly one '.' in between (it's a float)
Everything else: it's a string
You can use:
def get_type(x):
' Detects type '
if x.isnumeric():
return int # only digits
elif x.replace('.', '', 1).isnumeric():
return float # single decimal
else:
return None
# Using get_type in OP code
x = input("Enter a number: ")
x_type = get_type(x)
if x_type == int:
print( x, " is an integer")
elif x_type == float:
print( x, "is a float")
else:
print(x, "is a string")
Example Runs
Enter a number: 10
10 is an integer
Enter a number: 10.
10. is a float
Enter a number: 10.5.3
10.5.3 is a string
So, basically, as the title states "I'm trying to test if the input a is an integer and if not loop back to the top of the loop" when I do it the program only prints(a is not a number start over) even when a is a number and b is not or if a and b are numbers.
def multiply():
while True:
a = input("enter something: ", )
b = input("enter something: ", )
if(a != int(a)):
print("a was not a number start over")
multiply()
elif(b != int(b)):
print("b was not a number start over")
multiply()
else:
sum = a * b
print(sum)
break
multiply()
The input function always returns a string.
>>> x = input("enter a number: ")
enter a number: 123
>>> print(x)
123
>>> type(x)
str
You need to cast the user's input as an int first, and handle the case when the user's input is not a valid int value:
def get_integer_input(message):
value = input(message)
try:
return int(value)
except ValueError:
print("Invalid input! You must enter a valid integer.")
return None
# Invalid input "foobar"
>>> get_integer_input("Enter an integer: ")
Enter an integer: foobar
Invalid input! You must enter a valid integer.
# Valid input 101
>>> get_integer_input("Enter an integer: ")
Enter an integer: 101
101
Given that there are two inputs- a String and a number.
I wish to append the string with the same .
Eg:
Input:
a 10
Output:
add a to the String 'a' such that it appears 10 times.
aaaaaaaaaa
another example:
Input:
ab 5
OUTPUT:
ababababab
You can have a function like below:
In [1389]: def myfunc(string, number):
...: s = string * number
...: return s
In [1391]: string = input("Enter string:")
In [1392]: number = input("Enter number:")
In [1396]: myfunc(string, number)
Out[1396]: 'aaaaaaaaaa'
Python multiplies the string to number if given like 'a' * 2.
It will Help You
num = int(input()) #for how many times we want to print string
string = input() # String which we want to print
for i in range(num): # loop will run for num (User Input) times which come from input
print(string)
if you want to print in a single line
print(string , end = " ")
Think Twice , Code Once
Simply You can do with using * operator
n = int(input("Enter a number"))
string = input("Enter a String")
print(string*n) # it prints your string n times
With Function
def num_multi(n , s):
return n*s
number = int(input("Enter a number"))
string = input("Enter a String")
print(number*string)
Python 3.x:
def printstring(string,number):
print(string * number)
return
number1 = int(input("Enter here: "))
string1= input("enter a number")
print(printstring(string1,number1))
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
I am trying to create a python program that uses user input in an equation. When I run the program, it gives this error code, "answer = ((((A*10A)**2)(B*C))*D**E) TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'". My code is:
import cmath
A = input("Enter a number for A: ")
B = input("Enter a number for B: ")
C = input("Enter a number for C: ")
D = input("Enter a number for D: ")
E = input("Enter a number for E: ")
answer = ((((A*10**A)**2)**(B*C))*D**E)
print(answer)`
The input() function returns a string value: you need to convert to a number using Decimal:
from decimal import Decimal
A = Decimal(input("Enter a number for A: "))
# ... etc
But your user might enter something that isn't a decimal number, so you might want to do some checking:
from decimal import Decimal, InvalidOperation
def get_decimal_input(variableName):
x = None
while x is None:
try:
x = Decimal(input('Enter a number for ' + variableName + ': '))
except InvalidOperation:
print("That's not a number")
return x
A = get_decimal_input('A')
B = get_decimal_input('B')
C = get_decimal_input('C')
D = get_decimal_input('D')
E = get_decimal_input('E')
print((((A * 10 ** A) ** 2) ** (B * C)) * D ** E)
The compiler thinks your inputs are of string type. You can wrap each of A, B, C, D, E with float() to cast the input into float type, provided you're actually inputting numbers at the terminal. This way, you're taking powers of float numbers instead of strings, which python doesn't know how to handle.
A = float(input("Enter a number for A: "))
B = float(input("Enter a number for B: "))
C = float(input("Enter a number for C: "))
D = float(input("Enter a number for D: "))
E = float(input("Enter a number for E: "))
That code would run fine for python 2.7 I think you are using python 3.5+ so you have to cast the variable so this would become like this
import cmath
A = int(input("Enter a number for A: "))
B = int(input("Enter a number for B: "))
C = int(input("Enter a number for C: "))
D = int(input("Enter a number for D: "))
E = int(input("Enter a number for E: "))
answer = ((((A*10**A)**2)**(B*C))*D**E)
print(answer)
I tested it
Enter a number for A: 2
Enter a number for B: 2
Enter a number for C: 2
Enter a number for D: 2
Enter a number for E: 2
10240000000000000000
there are three ways to fix it, either
A = int(input("Enter a number for A: "))
B = int(input("Enter a number for B: "))
C = int(input("Enter a number for C: "))
D = int(input("Enter a number for D: "))
E = int(input("Enter a number for E: "))
which limits you to integers (whole numbers)
or:
A = float(input("Enter a number for A: "))
B = float(input("Enter a number for B: "))
C = float(input("Enter a number for C: "))
D = float(input("Enter a number for D: "))
E = float(input("Enter a number for E: "))
which limits you to float numbers (which have numbers on both sides of the decimal point, which can act a bit weird)
the third way is not as recommended as the other two, as I am not sure if it works in python 3.x but it is
A = num_input("Enter a number for A: ")
B = num_input("Enter a number for B: ")
C = num_input("Enter a number for C: ")
D = num_input("Enter a number for D: ")
E = num_input("Enter a number for E: ")
input() returns a string, you have to convert your inputs to integers (or floats, or decimals...) before you can use them in math equations. I'd suggest creating a separate function to wrap your inputs, e.g.:
def num_input(msg):
# you can also do some basic validation before returning the value
return int(input(msg)) # or float(...), or decimal.Decimal(...) ...
A = num_input("Enter a number for A: ")
B = num_input("Enter a number for B: ")
C = num_input("Enter a number for C: ")
D = num_input("Enter a number for D: ")
E = num_input("Enter a number for E: ")
I have the following simple python code, which checks the user input.
while True:
num = raw_input("Enter the number :")
if (num >= 1 and num <= 5):
break
else:
print "Error! Enter again :"
When I give as input 0 or numbers greater than 5 it works correctly, but then I try to give an input from 1 to 5 and the program still goes to the else part. Could you help me to find my error?
num is a string, not a number. You need to convert the return value of raw_input into a number first with int():
>>> n = raw_input('Type stuff: ')
Type stuff: 123
>>> type(n)
<type 'str'>
>>> n
'123'
>>> int(n)
123
>>> type(int(n))
<type 'int'>
You need to cast it to int -
num = int(raw_input("Enter the number :"))
As raw_input read line and converts it to string .