Python Forum

Full Version: Newbie to Python - input and branching issue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I'm newbie to Python.

I have a question on this coding, why I cant run this code?
Can anyone guide me what's problem to this.

Thanks

age = input ("How old are you? ")
height = input ("What is your height? (cm)")
if (age > 8) and (height > 130):
    print ("Welcome to our Roller Coaster!")
else:
    print ("Come again next time!")
Output:
How old are you? 9 What is your height? (cm)140
Error:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-46-0851fb80a35f> in <module> 1 age = input ("How old are you? ") 2 height = input ("What is your height? (cm)") ----> 3 if (age > 8) and (height > 130): 4 print ("Welcome to our Roller Coaster!") 5 else: TypeError: '>' not supported between instances of 'str' and 'int'
input returns a string, not an int. So, as the error says, it doesn't make sense to compare a string and a number. Use the int function to convert the value you get from input to an int.
(Jul-30-2021, 06:27 AM)ndc85430 Wrote: [ -> ]input returns a string, not an int. So, as the error says, it doesn't make sense to compare a string and a number. Use the int function to convert the value you get from input to an int.

Thank you for your guide.
I got the solution.
YEAH! Smile
thanks so much

age = input ("How old are you? ")
height = input ("What is your height? (cm)")
if (int(age) >= 8) and (int(height) >= 150):
    print ("Welcome to our Roller Coaster!")
else:
    print ("Come again next time!")
Output:
How old are you? 9 What is your height? (cm)155 Welcome to our Roller Coaster!
Python is cool. It can do many things in 1 line.

split() is a built in function to split strings and return a list. By default it splits a string on a space character .

So, if

mystring = 'Hi my name is Tom.'

mystring.split() returns a list: ['Hi', 'my', 'name', 'is', 'Tom.']

If you wanted to split on say, m, just write

mystring.split('m')

This baby is called a list comprehension, a quick way of making a list:

mylist = [x for x in range(1, 10)]

You can combine list comprehension, input and split, take 2 (or more) variables which are numbers and do everything in 1 line:

From my Idle shell:

Quote:>>> var1, var2 = [int(x) for x in input("Enter your age in years and your height in centimetres here, separated by a space: ").split()]
Enter your age in years and your height in centimetres here, separated by a space: 8 130
>>> var1
8
>>> var2
130
>>>