Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (Retired) Things That Count Exceptions

Please check my code. I made other version than Kenneth.

I was trying to not look and reproduce his example in video, to learn it stronger.

I used 2 different variables in try:, except:, in contrary to his code AND used if string not in, in contrary to his: if not string in.

But I'm getting an error: line 26, in <module> print(user_word[ratio]) IndexError: string index out of range

user_word = input('What is your word ? ')
user_num = input('What is your number ? ')

try:
    number_int = int(user_num)
except:
    number_float = float(user_num)

if '.' not in user_num:
    print(user_word[number_int])

else:
    ratio = round(len(user_word) * number_float)
    print(user_word[ratio])

Please help

P.s.: How may I format code to be better readable ? [code] [/code] does not work !

7 Answers

Melih Mucuk
Melih Mucuk
2,118 Points

Check Markdown Cheatsheet :

Code Wrap your code with 3 backticks (```) on the line before and after. If you specify the language after the first set of backticks, that'll help us with syntax highlighting.

        ```html
        <p>This is code!</p>
        ```

For your question, please check your indent. Be sure print(user_word[ratio]) is under the else statement.

It should be:

if '.' not in user_num: 
  print(user_word[number_int])
else: 
  ratio = round(len(user_word)*number_float)
  print(user_word[ratio])

Not like this:

if '.' not in user_num: 
  print(user_word[number_int])
else: 
  ratio = round(len(user_word)*number_float)
print(user_word[ratio])

I have it correct, so why don't work ? I did it in my python IDLE because workspace doesn't work for me

Melih Mucuk
Melih Mucuk
2,118 Points

Whats your number ? If I enter "Melih" and 2, it works. And If I enter "Melih" and .75, it also works. I think you write wrong type of float number. For example, If you write 3.2 and "Melih", len(user_word) equals to 5 and number_float equals to 3.2. So your ratio is 5 * 3.2 = 16. user_word hasn't 16 chars, so you can't print user_word[ratio]. Try with .75 or something like this. I tried in workspace and It works.

Sang Han
Sang Han
1,257 Points

There are a couple issues with the code for me.

First of all, I'm glad that you tried to use a try/catch your user input. But you haven't used to check if the user is inputting a numeric value, which is what you should be using try/catch to be doing.

user_word = input('What is your word ? ')
user_num  = input('What is your number ? ')

if not user_num.isnumeric():
    try:
        # Strings that are floats  are not "numeric"
        user_num = float(user_num)
    except ValueError:
        print('Give me a integer or float')
        raise ValueError
else:
    user_num = int(user_num)

This version correctly catches user input and has correct behavior with integers/floats values.

The important part is the correct behavior. If your user input is invalid, it will raise an error. It will only turn floats into floats and ints into ints using type introspection rather than checking for a dot inside a string.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

You're covering concepts that we don't bring up in Python Basics. Thank you for explaining some very useful code, but it's likely to confuse people further.

Sang Han your code is too much advanced for me as beginner. Even Kenneth's learning stuff is too fast for virgin coder too ! I don't like it to be honest. Many things omitted, not explained in detail. Best course I have found so far, was by Charles Severance on Cousera, but I had to give up, because it was in python2, which is too much annoying to me. I had to code stuff for myself in py3, then somehow convert to py2 to make assignments eligible.

I tried to make that code in other way, but it didn't work. Why please ?

user_string = input('Write word ')
user_number = input('Write number ')

try:
    num_integer = int(user_number)
except:
    num_float = float(user_number)

if user_number == int:
    print ('Int part worked')
if user_number == float:
    print ('Float part worked')

I was trying use is instead of ==. And Type(Float), Type(int) instead of Float , Int

Thanks for help

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Unless you're comparing against None, don't use is. It (probably) doesn't do what you (probably) think it does (it doesn't check equality, it checks location in memory).

Alright Kenneth, but I did use == and those stuff: int or type(int). Why it didn't work please ?

Thanks

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Why didn't user_number == int word? Because int is a class and you can't compare a class to a string instance. Well, you can but you'll just get False. You'll get False no matter what you try to compare to int other than int itself.

If you want to see if user_number is an int (it won't be, because user_number is the result of input() which is always a string), you'd use isinstance(user_number, int).

Ok, I modified it, but it still doesn't work. Why ?

user_string = input('Write word ')
user_number = input('Write number ')

try:
    num_ = int(user_number)
except:
    num_ = float(user_number)


if num_ == int:
    print ('Int part worked')
if num_ == float:
    print ('Float part worked')

Then I modified it again, to see if conversion was ok:

user_string = input('Write word ')
user_number = input('Write number ')

try:
    num_ = int(user_number)
except:
    num_ = float(user_number)

if isinstance(num_, int) == True:
    print ('Is INT')

if isinstance(num_, float) == True:
    print ('Is FLOAT')


if num_ == int:
    print ('Int part worked')
if num_ == float:
    print ('Float part worked')

It was, but still no output. So I guess there is something wrong with check lines:

if num_ == int:

if num_ == float:

Classname int or float, cannot be compared with == ? Or it must be like: Type(int), or Type(float) ?

  • this I was asking from beginning. Kenneth, when you saw those lines were wrong, why didn't you notice me at that time ?

Thank you

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

int is the class for all integers. You're asking "is this variable equal to the class of all numbers?" so, no, it can't be compared like that. Same for comparing against str or dict or any class you create yourself.

Why didn't I point that out at first? I'm not sure. I probably just didn't see it or remember it after I saw your paragraph about using is. Using is is a much bigger rabbit hole/potential road block than comparing against a class/type is, so that's what I commented on.

Alright Kenneth

I know from somewhere that == operator is Equallity check and is operator is Object identity check. Checks for same memory box where the value is stored. Right ?

About that code snippet. I have tried this, any of those didn't work. Why ? It said syntax error.

is 5 in int
5 is in int

is 5 in type(int)
5 is in type(int)

5 in int
5 in type(int)

P.s.: How make text in bold, italic ?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Again, int is a class. 5 is an instance of the int class. You can't compare them to each other.

is doesn't start a statement, it's used in the middle (it's an infix operator) to do identity comparisons instead of equality comparisons.

type() returns the type/class of a variable/instance. You wouldn't check for membership in this, which you're doing with in, because classes don't (usually) have members.

None of this is anything you need to worry about at this point in your Python education.

But I don't like your code solution. if '.' in variable

Really is not possible somehow in genereal identify int and float to be comparable ?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Ha, I'm sorry you don't like my solution! Honestly, checking if there's a . in the string is the fastest way to see if you got a float or an int, since input() is always going to give you a string. It's much faster and more obvious than having to check a variable twice to see which class it's an instance of.

If you have to check the instances (and we don't cover this in Python Basics on purpose), you'd do it like this:

user_string = input('Write word ')
user_number = input('Write number ')

try:
    num_ = int(user_number)
except:
    num_ = float(user_number)

if isinstance(num_, int):
    print ('Is INT')

if isinstance(num_, float):
    print ('Is FLOAT')

Notice that that is exactly what you had before, minus the completely impossible checks against class literals. I also took of the == True because that's implied with an if already.

Also, notice that we know have two branches for our code to take, both of which could have else:s of their own, so our code's complexity doubled, as opposed to the fairly simple approach of checking for . in user_number.

This approach isn't bad but it's overkill for where we are in learning Python at this point in time.

I have finished his code. All correct ?

user_string = input('Write word ')
user_number = input('Write number ')

try:
    num_ = int(user_number)
except:
    num_ = float(user_number)

if isinstance(num_, int):
    print (user_string [num_])

if isinstance(num_, float):
    ratio = round(len(user_string) * num_)
    print(user_string[ratio])
Kenneth Love
Kenneth Love
Treehouse Guest Teacher

silashunter other than unnecessary spaces between print and its parentheses, and user_string and its brackets, that's a fine solution.