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

Understanding Python

Can someone explain in English what this means? I don't understand what we have done and what our_num represents:

user_string = input("What is your word?")
user_num = input("What is your number?")

try:
  our_num = int(user_num)
except:
  our_num = float(user_num)

if not '.' in user_num:
  print(user_string[our_num])
else:
  ratio = round(len(user_string)*our_num)
  print(user_string[ratio])

Additionally, what does this mean logically in terms of the language?

  print(user_string[ratio])

Thank you a ton !

3 Answers

Sure! My comments will be under #s like in python

user_string = input("What is your word?")
#This is setting the variable user_string to whatever the user inputs from the keyboard. 
#The string "What is your word?" will displayed before the user can input a string.

user_num = input("What is your number?")
# Basically the same thing as user_num just with a different variable and different string 
# to prompt the user before they enter their string.

try:
# try will attempt to execute the code indented below it. 
# if it fails it goes to the exception  below it

  our_num = int(user_num)
  # this sets the variable our_num to the integer value equivalent of what was in in user_num. 
  # REMEMBER: the input() function always returns whatever is entered as a string so the int()      
  # function converts that string to an integer value instead for proper numerical operations. 
  # Example: if you have '1' + '1' it would equal '11' because you're combing the separate strings 
  # '1' and '1' together but if you had them as integer values 1 + 1 (with no quotes) it would 
  # equal 2 because they're being used as actual numerical values.

except:
# the code indented below runs if the code under try fails. In other words it's there to catch 
# the program in case something messes up.

  our_num = float(user_num)
  # does a similar thing as the code under try but converts it to a float type 
  # (float variables are integers with numbers following a decimal point)

if not '.' in user_num:
# this checks user_num to see if a . is in user_num and returns a boolean (True or False).
# In other words it checks to see if user_num is a float or int. If it has a '.' then it's  
# a float and statement is False thus the code indented below it doesn't execute. 
# Otherwise it's True and executes the following code

  print(user_string[our_num])
  #this statement prints what's in user_string at index our_num.
  # REMEMBER: indexes start at 0 so for example the string Hello would have the following 
  # characters at these indexes:
  # H  e  l  l  o
  # 0  1  2  3  4
  # so for example if user_string was "Hello" and our_num was 4 the print statement would print 'o'

else:
#else executes if the previous statement if not '.' in user_num evaluates to False.

  ratio = round(len(user_string)*our_num)
  # this sets the variable ratio to the rounded int of the length of user_string: len(user_string)
  # multiplied by our_num which is a float if this executes because it didn't pass our previous test: 
  # if not '.' in user_num
  # REMEMBER: round rounds to the closest int. anything .5 and above rounds up and anything
  #  below that rounds down

  print(user_string[ratio])
  # prints the user_string character similar to the if case but uses the ratio variable 
  # we determined instead of our_num

Hope this helps! I tried my best to make it not so confusing and throw in some reminders!

Wow you are incredible and awesome. Made it extremely easy to read and understand. If you have Bitcoin, I will happily tip you for this. I plan to print it out. Just a couple last questions to wrap my head around it all: In

  our_num = int(user_num)
  # this sets the variable our_num to the integer value equivalent of what was in in user_num. 
  # REMEMBER: the input() function always returns whatever is entered as a string so the int()      
  # function converts that string to an integer value instead for proper numerical operations. 
  # Example: if you have '1' + '1' it would equal '11' because you're combing the separate strings 
  # '1' and '1' together but if you had them as integer values 1 + 1 (with no quotes) it would 
  # equal 2 because they're being used as actual numerical values.

I tried to put in both of those values for "What is your number?"(

1 + 1 
#and
"1"+"1"

) both of which returned an error. Why is this the case? Technically it should be able to at least use / change 1+1 as an int ?

I understand now what our_num does, however, not entirely what its purpose is in the code. What is it doing on the grand scale? Why can't I simply take it out? I tried taking it out and changing our_num to user_num and of course it failed, however I do not quite understand why.

Lastly, what is a variable ratio?

Thanks a ton. Post for BTC address if you interested ! I can't thank you enough !

Hi There! So basically this exercise is designed to show you 2 things: 1) integers and floats behave differently, 2) to avoid exceptions, we can make our code treat integers and floats differently.

I'm going to assign numbers to your code (blank lines get a number too), so there are 13 lines in your example.

In lines 1 and 2, we're getting user inputs.

Lines 4-7 exist because we can't just use "user_num" in the code because we don't know if it's an integer or a float. Line 4 is trying to turn user_num into an integer, which will work just fine if there isn't a decimal in the number. However, if that fails, the code proceeds to line 6 and turns it into a float. So in practical purposes, user_num becomes our_num after line 7; it doesn't LOOK different to us, but now the script knows whether it's working with a float or integer.

Lines 9-10 are working with our_num only if it is an integer (integers don't have decimals). If you do trial and error using the word "Magic", you will find there are only 5 integers that work with this script: 0-4. Python uses 0-based indexing for strings, so 0 gives you M, and 4 gives you C. BOTTOM LINE FOR INTEGERS: this code will use the integer you provide, and then count that many letters in within the word you provide. It's based on counting, not percentage.

Lines 11-13 are working with our_num only if it is a float (think percentage). Line 12 is where the action is happening, and will return "Ratio" for you. It counts how many letters are in user_string, then multiplies that by your percentage (our_num), then it will round to the nearest integer. Once you have Ratio, Line 13 is printing the letter that appears that far into user_string. BOTTOM LINE FOR FLOATS: this code will treat the user input number like a percentage, then find the letter that is approximately that percent of the way through the word.

Good luck!

Thank you so much for the extremely helpful response !

May I ask for some clarification on a couple things ? You said that this code will treat the user input number like a percentage; what do you mean by that ? Do you mean that because it is 0 - 4, 4.0 would be 100% and 2.5 50%? I am a little confused.

I also don't quite understand what the fundamental purpose is for creating our_num ? Why not use the user_num and use that number to pull out specific letters?

Your and Asa's responses have been tremendously helpful and I feel I understand the different parts of the code as a language, however perhaps it is the problem itself, but something is not completing my understanding...

In any case, thank you again.

I tried to put in both of those values for "What is your number?"(

1 + 1 
and
"1"+"1"

both of which returned an error. Why is this the case? Technically it should be able to at least use / change 1+1 as an int?

The "1"+"1" example was only an example! If you input that into a program not expecting a + it will return an error. If you want to test what I was talking about literally just enter "1"+"1" in the python console and it'll return "11" and then enter 1+1 in the console and it'll return 2.

I understand now what our_num does, however, not entirely what its purpose is in the code. What is it doing on the grand scale? Why can't I simply take it out? I tried taking it out and changing our_num to user_num and of course it failed, however I do not quite understand why.

the entire purpose of this exercise seems to be teaching you how to use the int() and float() functions and stuff like it as well as a review on arrays/lists. our_num was used as a way to compartmentalize the process of turning the string to an int step by step.

In the future (or maybe now if you can understand it tbh) the way you would initialize a variable to an int would be:

#foo is only an example variable
foo = int(input())

this way you both take the user input AND convert it to an int in one line rather than making multiple variables (unless it's needed for the specific program you're working on).

This program requires that you check if the string entered in user_num is a float or int first before it does the conversion though:

try:
# try will attempt to execute the code indented below it. 
# if it fails it goes to the exception  below it

  our_num = int(user_num)
  # this sets the variable our_num to the integer value equivalent of what was in in user_num. 
  # REMEMBER: the input() function always returns whatever is entered as a string so the int()      
  # function converts that string to an integer value instead for proper numerical operations. 
  # Example: if you have '1' + '1' it would equal '11' because you're combing the separate strings 
  # '1' and '1' together but if you had them as integer values 1 + 1 (with no quotes) it would 
  # equal 2 because they're being used as actual numerical values.

except:
# the code indented below runs if the code under try fails. In other words it's there to catch 
# the program in case something messes up.

  our_num = float(user_num)
  # does a similar thing as the code under try but converts it to a float type 
  # (float variables are integers with numbers following a decimal point)

when the try/except statement is done our_num will either be a int or float depending on how the string was formatted. If it has no period the conversion to an int :

our_num = int(user_num)

will set our_num to int and the rest of the program runs smoothly. Otherwise it turns it to a float.

Some other questions you may have about that part

Why a float?

Because the test data we're getting is a string formatted like an int or a float.

Why is it set up that way?

The way teamtreehouse has set the data for this problem only gives strings set up like ints and floats. This is something we call the constraint in programming and it basically means the limitations the program should have based on the data it's supposed to be processing.

Now note how I said the test data only gives strings formatted like ints and floats. If you take out the converted our_num from the program and replace it with the string user_num it won't process the same way because certain parts need real numbers (ints, floats, ect) to work with and not strings and thus the program won't run.

Lastly, what is a variable ratio?

ratio is the name of the variable! A variable in python is basically an easy way to refer to a set of data you processed or initialized (initialized basically means setting the value of something).

#So these are variables
var1 = 1
var2 = 2
var3 = 3
foo = 4
# and so on. You can literally name your variable anything
#that isn't already pre assigned like if, try, for, while,len ect

#Like I could literally make a variable name doggy and initialize it to 5
doggy = 5

#and whenever the variable named doggy is entered anywhere in the scope of the program it's in
#it will return the value 5 unless it's changed. variables can hold pretty much any value you
# choose btw. Not just numbers

#So if I make a variable named ratio (as was done in the code you posted)
ratio = round(len(user_string)*our_num)

#when ratio is mentioned anywhere in its scope it will return the rounded value of the length of 
#user_string multiplied by our_num 

Lastly I don't have a BTC address but thanks for the offer! The experience is enough for me!

I cannot thank you enough. Beyond helpful, Asa.