Invalid Syntax: adding 10 to input - python

I've been doing some python(using spyder) and being completely new to all of this, I'm pretty confused. My friend typed this code:
elif x== '3' :
number = input('Enter an integer \n')
try:
the sum = int(float(number)+(float(10))
print(number + 'plus 10 equals'+ the sum)
And it works for her, but not me, when I type the exact same thing, and same indents and all. There is a cross on the side(code analysis) that appears on the line that starts with 'the sum'. Apparently, there's invalid syntax. Thanks.

Let's look at this line by line..
elif x== '3' :
Should be:
if x == '3':
You should start if statements with if instead of elif. Also, make sure x has a value earlier in your code.
If you're brand new, I would wait just a little longer to add try: statements. But I'll include it in the final answer.
the sum = int(float(number)+(float(10))
Should be:
the_sum = float(number) + 10
Use a float if you expect number to have a decimal. Based on the info you provided, there isn't a need to convert the float back to an int which is what you're doing when you call int(float(...
Note that a space in a variable name is not valid syntax. Adding an underscore makes the_sum valid.
print(number + 'plus 10 equals'+ the sum)
Python2 and Python3 have different options for formatting output. More info here. I'll use Python2, so your code should be:
print ('%f plus 10 equals %f' % (number, the_sum))
%f means format a variable as a float. The first %f will be replaced with number and the second with the_sum.
All together you have:
if x == '3':
number = input('Enter an integer \n')
try:
the_sum = float(number) + 10
print ('%f plus 10 equals %f' % (number, the_sum))
except:
pass
Bonus: Does your script break when you enter a character? How could you use the try: statement to improve?

Related

Infinite loop in python from user input

I am writing Python code counting up to the number the user provides, but I get into an infinite loop when running the code. Please note I tried commenting out lines 3 and 4 and replaced "userChoice" with a number, let's say for example 5, and it works fine.
import time
print "So what number do you want me to count up to?"
userChoice = raw_input("> ")
i = 0
numbers = []
while i < userChoice:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
time.sleep(1)
print "The numbers: "
for num in numbers:
print num
time.sleep(1)
raw_input returns a string, not int. You can fix the issue by converting user response to int:
userChoice = int(raw_input("> "))
In Python 2.x objects of different types are compared by the type name so that explains the original behavior since 'int' < 'string':
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
You are comparing a number with a string in:
while i < userChoice:
The string will always be greater than the number. At least in Python 2 where these are comparable.
You need to turn userChoice into a number:
userChoice = int(raw_input("> "))

Behaviour of raw_input()

I wanted to understand the behaviour of raw_input in the below code.
I know num will be string.
Irrespective of whatever number i enter it always enter the elif part i.e. if num is 5, which should go to if num<check: part or if num is 10 which should go to else part. Every single time it is going to elif. I thought comparing STRING and INT might throw exception( I dont think so) but just in case, so I had included try except but as expected it did not throw any exception. But what puzzles me is why it is ALWAYS hitting elif even when the input given was 10, atleast in that case i was expecting output Equal
num = raw_input('enter a number')
check = 10
try:
if num<check:
print 'number entered %s is less'%num
elif num>check:
print 'number entered %s is greater'%num
else:
print 'Equal!!!'
print 'END'
except Exception,e:
print Exception,e
Please, PYTHON gurus, solve the Mystery :)
raw_input returns a string. So use int(raw_input()).
And for how string and int comparsions work, look here.
See the answer here.
Basically you're comparing apples and oranges.
>>> type(0) < type('10')
True
>>> 0 < '10'
True
>>> type(0) ; type('10')
<type 'int'>
<type 'str'>
Python 2.7:
num = int(raw_input('enter a number:'))
Variable "num" will be of type str if raw_input is used.
type(num)>>str
or
num = input("Enter a Number:")# only accept int values
type(num)>>int
Python 3.4 :
num = input("Enter a Number:") will work ...
type(num)>>str
convert the variable "num" to int type(conversion can be done at time of getting the user "input") :
num1 = int(num)

Python: I'm making a simple calculator for class. What's wrong with this code?

My teacher requests me to make a calculator that can calculate a 15% tip on a submitted price. I followed an online tutorial for this python application. I made a simple addition, subtraction, multiplication, and division calculator for practice before I make what my teacher requires. In the YouTube video I followed the python application ran on his computer. I get a a "Invalid Syntax" error in the Python Shell. I'm using Python 3.3.0. Thank you.
EDIT: I followed a different tutorial figured out how to finish my project. The only problem I'm having is using both regular integers (1, 2, 3, 4, etc.) and float integers (4.36, 5.45, etc.).
print("Welcome to the calculator!")
mealPrice = int(input("Enter your meal price:"))
asw = mealPrice * 0.15
print("The tip you owe is: ", asw)
because y is string
y = int(raw_input("Input second integer: "))
I see a couple problems with your code.
Your use of print on the first line will give you troubles, because print is a function in Python 3. You should call it like print("hello").
On line 8, you have an extra colon:
calc():
Get rid of that.
Last, you don't need the semicolons when you call calc()
This has a lot of changes to do.
First, the first line of code should be:
print ("Hello")
Then, the raw_input() should become input().
Next, there should not be a colon or semicolon after calc() except on the second line when you are defining a function.
The code should look something like this. Try it.
print ("Hello")
def calc():
x = int(input("Input first integer: "))
y = int(input("Input second integer: "))
type = str.lower(input("(A)dd, (S)ubstract, (M)ultiply, (D)ivide \n"))
if type != "a" and type != "s" and type != "m" and type != "d":
print ("Sorry, the command you entered is not valid.")
calc()
else:
if type =="a":
print ("The result is '" + str(x+y) + "'")
elif type == "s":
print ("The result is '" + str(x-y) + "'")
elif type =="m":
print ("The result is '" + str(x*y) + "'")
elif type == "d":
print ("The result is '" + str(float(x)/float(y)) + "'")
if int(input("Enter 1 if you would like to perform another calculation? \n")) == 1:
calc()
else:
exit()
calc()
Hope this helps.
Instead of converting to int (thus flooring whatever your value is -- 2.99 becomes 2, for instance) converting to float should do the trick nicely; the tip calculation should work even if you're doing 2.0*0.15 instead of 2*0.15.
This will obviously only work when you know what input you can expect. It will fail pretty badly if someone enters anything that isn't valid.
If you want to use integer:
mealprice = int(input("Enter your meal price:"))
If you want to use float:
mealprice = float(input("Enter your meal price:"))
Float is recommended because You can also use a single number like 1,2,3 etc and also float numbers.
I also created my own calculator that has 6 functions:
1 = Add
2 = Subtract
3 = Multiply
4 = Divide
5 = Round Off
6 = Get Remainder
It is so simple.
I have Not Used Round Off yet.
If You want That code Ask me I will give you.
If you want more Info, I am ready to Provide To you.
I figured it out. I was supposed to use:
int(float(input("Enter your meal price:")))
Thank you, everyone!

Basic decrement loop - PYTHON

Newbie to python and hit a snag in my latest program. Simply put, I'm trying to code up a decrement loop for a user input variable if possible. Essentially I have a global constant set to value e.g. 13, each time the program loops it prompts the user to input a value then that user value is shaved off 13 until it reaches 0. Problem is that it does shave it off but when it reiterates it resets the value to 13 and only removes the current iterate value entered. So if you enter 2 each iteration it just takes it down to 11... But I'm aiming for a result using 2 as an example again, 11, 8, 5, etc etc or using 3 as an example 10, 7, 4.... Any help guys will be much appreciated, cheers :)
a = 13
def main():
runLoop()
def runLoop():
while other_input_var > 0: # guys this is my main score accumulator
# variable and works fine just the one below
b=int(input('Please enter a number to remove from 13: '))
if b != 0:
shave(a, b)
def shave(a, b):
a -= b
print 'score is %d ' % a
if a == 0:
print "Win"
main()
In my humble opinion with such a small snippet the addtional functions end up over complicating things. However good to see you are getting the concept. I have not tested this but this should do the same thing you are looking for. Notice line 5 I insure that the number entered does not exceed the current value of a. This should help if they/you accidentally type something higher. Next step would be to put error handling if you haven't tried that yet see Python Error Handling . hope this helps!
def main():
a = 13
while a:
b = int(input("Please enter a number to remove from " + str(a) + " : "))
if b > 0 and b <= a:
a -= b
print "Score is ", str(a)
print "Win"
main()
Not an answer to your question, but rather a demonstration of string formatting. This is the old style, using the % "string interpolation operator".
a = 100
while a:
shave = int(raw_input("Input a number to subtract from %i:" % a))
if ( shave > 0 ) and ( shave <= a ):
a -= shave
else:
print ("Number needs to be positive and less than %i." % a)
A session with this program:
Input a number to subtract from 100:50
Input a number to subtract from 50:100
Number needs to be positive and less than 50.
Input a number to subtract from 50:30
Input a number to subtract from 20:20
The %i in the original string is a placeholder for an integer (i for integer) which is filled in later by the % operator on the string.
There's also %f for floating-point numbers, %s for strings, and so on. You can do nifty things like specify how many decimal points numbers should print with - %.3f for three decimal places - and so on.
Another example:
>>> "My name is %s and I'm %.2f metres tall." % ('Li-aung',1.83211)
"My name is Li-aung and I'm 1.83 metres tall."
This is a lot easier to read than:
"My name is " + name + " and I'm " + str(round(age,2)) + " metres tall"
Read up more about string formatting the old way or the new way.

Python ISBN program

I'm trying to calculate the check digit for an ISBN input on python. so far I have...
def ISBN():
numlist = []
request = raw_input("Please enter the 10 digit number: ")
if len(request) == 10:
**numlist == request
print numlist**
if len(request) != 10:
print "Invalid Input"
ISBN()
ISBN()
The bold bit is where im having trouble, I cant seem to split the 10 digit input into individual numbers in the list (numlist) and then multiply the seperated individual numbers by 11 then the next by 10 then the next by 9 etc...
For the next part of the program, I will need to add these new multiplied numbers in the list together, then i will use the mod(%) function to get the remainder then subtract the number from 11, any assistance with any of my coding or incorrect statements on how to calculate the ISBN would be greatly appreciated.
Thank you.
This code should get you on your way:
listofnums = [int(digit) for digit in '1234567890']
multipliers = reversed(range(2,12))
multipliednums = [a*b for a,b in zip(listofnums, multipliers)]
Strings are iterable, so if you iterate them, each element is returned as a single-character string.
int builds an int from a (valid) string.
The notation [a*b for a,b in zip(listofnums, multipliers)] is a list comprehension, a convenient syntax for mapping sequences to new lists.
As to the rest, explore them in your repl. Note that reversed returns a generator: if you want to see what is "in" it, you will need to use tuple or list to force its evaluation. This can be dangerous for infinite generators, for obvious reasons.
I believe list() is what you are looking for.
numlist=list(request)
Here is how I would write the code. I hope I'm interpreting the code correctly.
def ISBN():
request = raw_input("Please enter the 10 digit number: ")
if len(request) == 10:
numlist = list(request)
print numlist
else:
print "Invalid Input"
ISBN()
import itertools
if sum(x * int(d) for x, d in zip(nums, itertools.count(10, -1))) % 11 != 0:
print "no good"

Categories