Print, input, and turning text into numbers
Python is the language most data scientists reach for first, and like any language you begin by learning to hold a conversation with it. A program is a dialogue: print(...) is how your code speaks to you, and input() is how it listens.
print("How many months of statistics have you taken?")
months = input() # input() always hands you back text
print("You typed:", months)
Run that and Python prints the question, waits for you to type, and echoes your answer back.
The one subtlety to fix in your mind right now is in that comment: input() always returns a string — text — even if you type 12. That matters because text and numbers behave differently: you cannot do arithmetic on text until you convert it, which is the very next step in this lesson.
Because input() gives you text, doing arithmetic means converting first, with int(...) for whole numbers or float(...) for decimals:
months = int(input()) # now it is really a number
print("Next year you'll have", months + 12, "months")
If the text isn't a valid whole number, the conversion fails: int('twelve') and int('3.5') both raise a ValueError (the string '3.5' is not a valid integer literal). This is about text. Applying int to the float 3.5 is different: int(3.5) is fine and returns 3, truncating toward zero. When the text really is a decimal, convert with float('3.5'). Converting at the boundary is exactly where bad input reveals itself.
An f-string is the clean way to build a sentence out of values. Put an f before the quote and drop variables inside {...}:
name = "Ada"
count = 3
print(f"{name} has {count} items") # Ada has 3 items
CSV”.*
Related cards
Tasks
Card Info
- Topic: Python for Data Science
- Difficulty: Beginner
- Completed: 0 users