Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Numbers and Arithmetic | Working with Data Types
Practice
Projects
Quizzes & Challenges
Visat
Challenges
/
Introduction to Python

bookNumbers and Arithmetic

Pyyhkäise näyttääksesi valikon

12345678910111213141516171819202122232425
# Basic arithmetic operations with integers and floats x = 10 # integer y = 3 # integer a = 5.5 # float b = 2.0 # float # Addition sum_result = x + a print('Addition:', sum_result) # 10 + 5.5 # Subtraction sub_result = y - b print('Subtraction:', sub_result) # 3 - 2.0 # Multiplication mul_result = x * y print('Multiplication:', mul_result) # 10 * 3 # Division div_result = x / y print('Division:', div_result) # 10 / 3 # Exponentiation exp_result = y ** 2 print('Exponentiation:', exp_result) # 3^2
copy

Integers vs. Floats in Python

In Python, integers and floats are two different types of numbers:

  • Integers (int): These are whole numbers without any decimal point. Examples include -3, 0, 42, and 100000. Integers can be positive, negative, or zero.

  • Floats (float): These are numbers that contain a decimal point. Examples include 3.14, 0.0, -2.5, and 1.0. Floats are used when you need to represent fractional values or perform calculations that require more precision.

Key differences:

  • Integers do not have a decimal part, while floats always have a decimal point (even if the number is a whole number, like 1.0).

  • Arithmetic operations involving an integer and a float will usually result in a float, to preserve any decimal information.

  • Example:

    a = 5      # integer
    b = 2.0    # float
    result = a / b
    print(result)  # Output: 2.5 (float)
    

Understanding the distinction between these two types is important for writing accurate and efficient Python code.

Note
Common Pitfalls with Division

In Python, using / always performs float division, even if both numbers are integers (e.g., 5 / 2 results in 2.5). If you need integer division (discarding the remainder), use the // operator (e.g., 5 // 2 results in 2). Forgetting this difference can cause unexpected results, especially when working with loops or indexes. Always choose the correct operator for your intended outcome!

question-icon

Fill in the blanks to complete the code so that it prints the result of multiplying 7 by 3, and then adds 2 to the result.

result = 7 _ _ _ 3
final = result _ _ _ 2
print(final)
23
Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 1

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 2. Luku 1
some-alt