Python Programming

Variables, Types and Operators

30 分

Variables

A variable is a name pointing to a value. You do not declare types; Python works them out.

price = 19.99        # float
quantity = 3         # int
product = "Hoodie"   # str
in_stock = True      # bool
discount = None      # "no value"

Names use snake_case. They are case-sensitive: total and Total are different.

Numbers

7 / 2     # 3.5   true division
7 // 2    # 3     floor division
7 % 2     # 1     remainder
2 ** 8    # 256   power
round(19.995, 2)

Floats are approximate: 0.1 + 0.2 is 0.30000000000000004. For money use decimal.Decimal:

from decimal import Decimal
Decimal("19.99") * 3    # Decimal('59.97')

Strings

title = "Learn Python"
title.lower()            # 'learn python'
title.replace("Python", "Flask")
title.split()            # ['Learn', 'Python']
len(title)               # 12
title[0], title[-1]      # 'L', 'n'
title[0:5]               # 'Learn'  (slicing)
f"{product} x{quantity} = {price * quantity:.2f}"   # f-string formatting
"py" in title.lower()    # True

Strings are immutable: methods return new strings.

Booleans and comparisons

age = 20
age >= 18 and age < 65     # True
not in_stock               # False
x == y   x != y            # equality

Values that count as false: False, None, 0, "", [], {}. Everything else is true, so if name: checks a string is not empty.

Converting types

int("42")       # 42
float("3.5")    # 3.5
str(99)         # '99'
bool("")        # False

int("abc") raises ValueError; you will handle that with try in the errors module.

Checking types

type(3.0)                 # <class 'float'>
isinstance(price, float)  # True

Exercise

Ask for a price and a quantity, then print the subtotal, 20% tax and total, each formatted to two decimal places with an f-string. Then redo it with Decimal and compare.

Check yourself

  • What is the difference between / and //?
  • Why should money not use floats?
  • Which values are "falsy"?

進捗はこのブラウザーにのみ保存されます。

レビューに提出(10 ポイント)