top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Issue converting to string to integer in python

0 votes
433 views

I was following an exercise in a book when I edited the code and came across something I did not get. Here is the relevant part of the code that works:

start=None #initialise 
while start !="": 
 start=input("nStart: ")

 if start:
 start=int(start)
 finish=int(input("Finish: ")) 

 print("word[",start,":",finish,"] is", word[start:finish])

I then changed the code to this:

start=None #initialise 
while start !="": 
 start=int(input("nStart: "))

 if start:

 finish=int(input("Finish: "))

 print("word[",start,":",finish,"] is", word[start:finish])

I combined the int conversion and the input on the same line, rather than to have two different statements. But got an error message:

Traceback (most recent call last):
 File "C:UsersFaisalDocumentspythonpizza_slicer.py", line 23, in 
 start=int(input("nStart: "))
ValueError: invalid literal for int() with base 10: ''

Could someone tell me why I got this error message?

posted Jun 3, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

Converting an empty string to base 10 doesnt fly, so if you hit a blank line on the input(), you get a bad conversion. In the first version, youre only converting to base 10 if the string is non-empty. In the second, you are attempting to convert irrespective.

answer Jun 3, 2013 by anonymous
+1 vote

When you were presented the 'Start' prompt, you hit Enter, which causes input to return an empty string. As it's passed directl into int, which requires a valid string-representing-a-number, you get the ValueError traceback, which shows you the failing input it received: '' This doesn't happen in your original code, because your condition if start: will fail on an empty string, and not try to turn it into an int.

You don't want to wrap your input with an int. You want to test the return result from input to ensure it can be coerced:

 start = input("nStart: "))
 if start and start.isdigit():
 start=int(start)
 ...
 else:
 start='' # set start to empty string so the while loop repeats

Here we check that all of the characters in the string start are actually numbers before coercing. This is known as the "Look Before You Leap" (LBYL) approach. Another approach is to catch the ValueError
exception:

 start = input("nStart: "))
 try:
 start = int(start)
 except ValueError:
 start = ''
 if start:
 ....

This is known as "Easier to for Ask Forgiveness than Permission" (EAFP). They both have their advantages. try/excepts tends to be quicker if few exceptions are called, while an if/else will test
every time, although at this point it's not something you need to overly concern yourself with. Go with whichever is easiest for you to understand & extend.

answer Jun 3, 2013 by anonymous
Similar Questions
0 votes

I want to convert audio in MP3 format to other formats including uncompressed raw format, WAV etc. and I am using python 2.7. Is there any built-in module I can use or any third party modules available ?

Please help me on this. I would be very grateful.

+2 votes

I am using the Linux system with python, i am running the following script

#!/usr/bin/python

import threading

import time

import sys
import subprocess
import datetime
import os
import time
import logging

proc1=subprocess.Popen("/root/Desktop/abc.py","64","abc",shell=True,stdout=subprocess.PIPE,
stderr=subprocess.PIPE)

In this script i am calling the other script named abc.py which is located on the desktop with 64 and abc as its arguments I am getting the following error

File "/usr/lib64/python2.6/subprocess.py", line 589, in __init__
 raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer

Can someone help me?

+1 vote

The change in integer division seems to be the most insidious source of silent errors in porting code from python2 - since it changes the behavior or valid code silently.

I wish the interpreter had an instrumented mode to detect and report such problems.

+1 vote

I read the online help about string. It lists string constants, string formatting, template strings and string functions. After reading these, I am still puzzled about how to use the string module.

Could you show me a few example about this module?

...