• 1
    数据输入输出
    • 任务
  • 2
    条件语句
    • 任务
  • 3
    for循环
    • 任务
  • 4
    字符串
    • 任务
  • 5
    while循环
    • 任务
  • 6
    列表
    • 任务
  • 7
    二维数组
    • 任务
  • 8
    字典
    • 任务
  • 9
    集合
    • 任务
  • 10
    函数与递归
    • 任务
  • к

课程 1. Entering and output of data

难度:

任务«VAT 计算器»

💻 Python

你需要帮助朋友计算包含增值税的商品成本。编写一个程序,允许用户输入商品金额和增值税百分比,然后输出增值税金额以及包含增值税的总金额。

输入格式

程序接收两行输入:

  • 第一行:数字(整数或浮点数)—— 商品金额。

  • 第二行:数字(整数或浮点数)—— 增值税百分比

输出格式

程序必须输出两个数字,每个数字占一行:

rn

  1. rn
  2. 第一行:计算出的增值税金额。
  3. rn
  4. 第二行:含增值税的总金额。

示例

输入

100
20

输出

增值税金额:20.0 卢布。
含增值税的总金额:120.0 卢布。

提示

Basics of working with data input and output in Python

Function input(): Receiving data from the user

The input() function is used to receive data from the user. When this function is called, the program stops running, and it waits for the user to enter any data and press the Enter key.

The key point to remember is that the entered data is always returned as a string (data type str), even if the user entered only numbers.

If you need to get an integer (int) or a decimal fraction (float) for your task, you need to perform an explicit type conversion. This is easily done by wrapping the input() function in the appropriate function: int() or float().

# input() always returns a string
name = input() 

# Converting the entered string to an integer
age = int(input())  

# Converting an entered string to a fractional number
sqr = float(input())

A useful tip: In order for the user to understand what data is required from him, you can pass a hint string to the input() function. This prompt will be displayed on the screen before the program starts waiting for input.

name = input("Enter your name:")
age =int(input("Enter your age:"))
print("Hello,", name, "! You", age, "years.")

Functions for type conversion

Converting one data type to another is one of the most common operations in programming.

float() function

It is used to convert data to a floating-point number (decimal). This can be useful when working with prices, measurements, or division results.

price_str = "99.99"
count_int = 5

# Convert string and integer to float
price_float = float(price_str)
count_float = float(count_int)

print(price_float) # Outputs: 99.99
print(count_float) # Outputs: 5.0

Function int()

It is used to convert data to an integer.

It is important to remember: When converting a fractional number to an integer using int(), the fractional part is simply discarded, and not rounded according to mathematical rules.

price_str = "123"
pi_float = 3.14159

price_int = int(price_str)
pi_int = int(pi_float)

print(price_int) # Outputs: 123
print(pi_int) # Outputs: 3 (the fractional part .14159 has been discarded)

Function str()

Is used to convert data to a string. This is necessary when you want to "glue" (concatenate) a string with a number.

price = 123
pi = 3.14

price_str = str(price)
pi_str = str(pi)

# Now we can safely "glue" the strings
print("Product price: " + price_str) # Outputs: "Product price: 123"
print("The number of Pi is approximately equal to " + pi_str) # It will display: "The number of Pi is approximately 3.14"

A useful tip: If you try to convert a string that is not a number (for example, "hello") to int() or float(), the program returns the error ValueError. Always be sure about the format of the data you are converting.


Function print(): Data output to the screen

The print() function is required to display data on the screen. This is a very versatile feature.

1. Output of multiple values You can pass multiple values separated by commas to print(). By default, they will be separated by a space.

name = "Vladimir"
age = 20

print(name) # Outputs: Vladimir
print(name, age)          # Will output: Vladimir 20
print("Name:", name, "Age:", age) # Outputs: Name: Vladimir Age: 20

2. Performing calculations inside print() You can perform mathematical operations right inside the function.

count = 5
price = 20
print(count * price) # Outputs: 100

3. Output control using sep and end

  • The sep (separator) argument allows you to change the separator between the elements.
  • The end argument allows you to change the character that is placed at the end of the output (by default, it switches to a new line \n).
print("apple", "banana", "cherry", sep=", ") # Outputs: apple, banana, cherry
print("The first part of the string...", end="")     # There will be no transition to a new line
print("...the second part on the same line.")

4. Modern formatting method: f-strings This is the most convenient and recommended way to format strings in modern Python. It allows you to embed variables and even expressions directly into a string.

  • The string must start with the letter f before the quotation marks.
  • Variables or expressions are placed in curly braces {}.

Compare the old and new approaches:

count = 5
price = 20

# The old way (adding strings)
print(str(count) + " * " + str(price) + " = " + str(count * price))

# A new, convenient way (f-string)
print(f"{count} * {price} = {count * price}")

Both examples will display: 5 * 20 = 100, but the f-string is much cleaner and easier to read.

main.py
测试 1
测试 2
测试 3
测试 4
测试 5
测试 6
测试 7
测试 8
测试 9
测试 10
开发者解答
# Считываем исходную сумму товара
summa_tovara = float(input())
# Считываем процент НДС
procent_nds = float(input())
# Рассчитываем сумму НДС
# Для этого умножаем сумму товара на процент и делим на 100
summa_nds = summa_tovara * (procent_nds / 100)
# Рассчитываем итоговую сумму
# Складываем исходную сумму товара и рассчитанный НДС
itogovaya_summa = summa_tovara + summa_nds
formatted_summa_nds = f"{summa_nds:.2f}"
formatted_itogovaya_summa = f"{itogovaya_summa:.2f}"
# Выводим результат
print(f'Сумма НДС: {formatted_summa_nds} руб.')
print(f'Итоговая сумма с учетом НДС: {formatted_itogovaya_summa} руб.')

🎉 恭喜! 🎉

你出色地完成了任务!这是一个不小的挑战,但你找到了正确答案。你离编程大师又近了一步!继续保持,每一步都让你更强大。

AD

广告

red-snake blue-snake green-snake

正在运行代码...

AI助手

你好!我是你的编程助手。随时向我提问关于 Python 的问题——我可以解释函数、方法,并帮助你完成当前任务!