The Story That Explains Python Syntax 🗾Python Syntax समझाने वाली कहानी 🗾一个解释 Python 语法的故事 🗾
Programming is the same. Every language has a syntax — strict grammar rules that the computer checks. Follow them and the computer does exactly what you asked. Break one — a missing colon, a wrong indent — and Python stops and shows an error message instead of guessing what you meant.
The good news: Python's grammar is small and close to plain English, which is why it is a popular first language.
Programming भी ऐसी ही है। हर भाषा का एक syntax होता है — व्याकरण के सख़्त नियम जिन्हें computer जाँचता है। नियम मानें तो computer ठीक वही करता है जो आपने कहा। एक भी तोड़ें — colon छूटा, indent ग़लत — तो Python अंदाज़ा लगाने की जगह रुककर error message दिखाता है।
अच्छी ख़बर: Python का व्याकरण छोटा और सादी English के क़रीब है, इसीलिए यह पहली भाषा के रूप में लोकप्रिय है।
编程也一样。每种语言都有语法(syntax)——计算机会严格检查的规则。遵守它们,计算机就完全按你说的做;违反一条——少一个冒号、缩进不对——Python 就会停下并报错,而不会去猜你的意思。
好消息是:Python 的语法规则少,接近日常英语,所以它很适合作为第一门语言。
Syntax is the set of rules for how Python code must be written so that Python can read it. It covers how you name things, how statements end, how you group code into blocks, and how you write expressions. Python checks the syntax of the whole file before it runs the first line.
Syntax वे नियम हैं जिनके हिसाब से Python code लिखा जाना चाहिए ताकि Python उसे पढ़ सके। इसमें आता है कि चीज़ों के नाम कैसे रखें, statements कैसे ख़त्म हों, code को blocks में कैसे बाँटें, और expressions कैसे लिखें। Python पहली line चलाने से पहले पूरी file का syntax जाँचता है।
语法是 Python 代码必须遵守的书写规则,这样 Python 才能读懂它。它包括怎么命名、语句怎么结束、怎样把代码分成块,以及怎么写表达式。Python 在运行第一行之前,会先检查整个文件的语法。
In C++ or Java you write semicolons, braces and type declarations. Python needs far fewer symbols, so you can focus on the problem instead of the punctuation. This is a big reason Python is widely used in teaching, data science and AI.
C++ या Java में आप semicolons, braces और type declarations लिखते हैं। Python को बहुत कम symbols चाहिए, इसलिए आप punctuation की जगह समस्या पर ध्यान दे पाते हैं। यही बड़ा कारण है कि Python पढ़ाई, data science और AI में ख़ूब इस्तेमाल होता है।
在 C++ 或 Java 里,你要写分号、花括号和类型声明。Python 需要的符号少得多,你可以专注于问题本身而不是标点。这是 Python 在教学、数据科学和 AI 领域被广泛使用的重要原因。
Python Syntax — Five Basic Rules 📐Python Syntax — पाँच बुनियादी नियम 📐Python 语法 —— 五条基本规则 📐
Learn these five rules and you can read most beginner Python code. Everything else builds on them.
ये पाँच नियम सीख लें तो आप beginner स्तर का ज़्यादातर Python code पढ़ सकते हैं। बाक़ी सब इन्हीं पर बनता है।
掌握这五条规则,你就能读懂大多数入门级 Python 代码。其他内容都建立在它们之上。
{ }. Lines in one block must line up exactly. 4 spaces per level is the standard (PEP 8).{ } इस्तेमाल करती हैं। एक block की lines ठीक एक सीध में होनी चाहिए। हर level पर 4 spaces मानक है (PEP 8)।{ }。同一块里的行必须严格对齐。每级 4 个空格是标准写法(PEP 8)。; as in C, Java or JavaScript. (A ; is allowed to put two statements on one line, but PEP 8 discourages it.); नहीं लगाते। (एक line में दो statements के लिए ; चल जाता है, पर PEP 8 इसे टालने को कहता है।); 结尾。(; 可以把两条语句写在同一行,但 PEP 8 不建议这样做。)# on a line is a comment for humans. Explain why the code does something; the code itself shows what.# के बाद सब कुछ इंसानों के लिए comment है। Code कुछ क्यों करता है यह समझाएँ; क्या करता है वह code ख़ुद दिखाता है।# 之后的内容都是写给人看的注释。注释应说明代码为什么这样做;做了什么代码本身已经表达了。Name, name and NAME are three different variables. Keywords are lowercase: IF or For is a syntax error. (True, False, None start with a capital.)Name, name और NAME तीन अलग variables हैं। Keywords lowercase होते हैं: IF या For syntax error है। (True, False, None capital से शुरू होते हैं।)Name、name 和 NAME 是三个不同的变量。关键字都是小写:IF 或 For 是语法错误。(True、False、None 首字母大写。)if, elif, else, for, while, def, class, try, with — end with :. The indented lines below are the body.if, elif, else, for, while, def, class, try, with — : पर ख़त्म होती हैं। नीचे की indented lines उसका body हैं।if、elif、else、for、while、def、class、try、with —— 以 : 结尾,下面缩进的行就是块体。The same logic in two styles. Python uses the colon and the indentation; C-style languages use braces and semicolons.
एक ही logic दो शैलियों में। Python colon और indentation इस्तेमाल करता है; C-शैली की भाषाएँ braces और semicolons।
同一逻辑的两种写法。Python 用冒号和缩进;C 风格语言用花括号和分号。
Indentation — Python's Defining Feature 📏Indentation — Python की पहचान 📏缩进 —— Python 的标志性特征 📏
In most languages indentation only makes code look tidy. In Python, indentation is the structure: it decides which lines belong to an if, a loop or a function.
ज़्यादातर भाषाओं में indentation सिर्फ़ code को साफ़ दिखाता है। Python में indentation ही structure है: यह तय करता है कि कौन सी lines किसी if, loop या function का हिस्सा हैं।
在大多数语言里,缩进只是让代码好看。在 Python 里,缩进就是结构:它决定哪些行属于某个 if、循环或函数。
temperature = 34
# CORRECT — every line in a block has the same indentation (4 spaces is the standard)
if temperature > 30:
print("It's hot outside")
print("Stay hydrated")
else:
print("Weather is fine")
Remove the indent and Python refuses to start. The message names the line and the reason:
Indent हटाएँ तो Python शुरू ही नहीं होता। Message line और कारण बताता है:
去掉缩进,Python 就拒绝运行。报错信息会指出行号和原因:
temperature = 34
if temperature > 30:
print("It's hot outside")
Click lines 3–5 to change their indentation, then read what Python really does. Every result was produced by running the code on Python 3.13.16 — all 64 combinations, for both ages.
Lines 3–5 पर click करके indentation बदलें, फिर देखें Python सच में क्या करता है। हर नतीजा Python 3.13.16 पर code चलाकर बना है — सभी 64 combinations, दोनों ages के लिए।
点击第 3–5 行改变缩进,然后看 Python 实际怎么做。每个结果都是在 Python 3.13.16 上真实运行得到的 —— 两种 age 下全部 64 种组合。
Out of the 64 combinations in the lab, only 9 run at all. The rest fail before a single line executes. Some of the ones that run do something different from what you meant — for example, indenting print("Done") moves it inside the if, so with age 15 it never prints.
Lab के 64 combinations में से सिर्फ़ 9 चलते हैं। बाक़ी एक भी line चलने से पहले असफल हो जाते हैं। जो चलते हैं उनमें से कुछ वह नहीं करते जो आप चाहते थे — जैसे print("Done") को indent करने से वह if के अंदर चला जाता है, तो age 15 पर वह कभी नहीं छपता।
实验室里的 64 种组合中,只有 9 种能运行,其余的在执行任何一行之前就失败了。能运行的组合里,有些做的事情和你想的不一样 —— 例如把 print("Done") 缩进,它就进入了 if 块,age 为 15 时根本不会打印。
Tabs and spaces look the same on screen, but Python counts them differently. Mix them in one block and you get a TabError (the file below has 8 spaces on line 2 and one tab on line 3):
Tabs और spaces screen पर एक जैसे दिखते हैं, पर Python उन्हें अलग गिनता है। एक block में दोनों मिलाएँ तो TabError मिलता है (नीचे की file में line 2 पर 8 spaces और line 3 पर एक tab है):
Tab 和空格在屏幕上看起来一样,但 Python 对它们的计数不同。同一块中混用就会得到 TabError(下面的文件第 2 行是 8 个空格,第 3 行是一个 tab):
if True:
print("8 spaces")
print("1 tab")
Use 4 spaces per level and never mix in tabs. Python itself accepts any consistent amount (the lab shows 2 spaces work), but 4 spaces is the PEP 8 standard every Python developer expects. Editors such as VS Code and PyCharm insert 4 spaces when you press Tab in a Python file — check that this setting is on.
हर level पर 4 spaces रखें और tabs कभी न मिलाएँ। Python ख़ुद कोई भी एक-सी मात्रा मान लेता है (lab दिखाता है कि 2 spaces भी चलते हैं), पर 4 spaces PEP 8 का मानक है जिसकी हर Python developer उम्मीद करता है। VS Code और PyCharm जैसे editors Python file में Tab दबाने पर 4 spaces डालते हैं — यह setting चालू है, जाँच लें।
每级缩进用 4 个空格,绝不混入 tab。Python 本身接受任何一致的缩进量(实验室显示 2 个空格也能运行),但 4 个空格是每位 Python 开发者都默认的 PEP 8 标准。VS Code、PyCharm 等编辑器在 Python 文件中按 Tab 会插入 4 个空格 —— 请确认这个设置已开启。
Comments and Docstrings 💬Comments और Docstrings 💬注释与文档字符串 💬
Comments are notes for people. Python skips them completely. A docstring is different: it is a string written as the first statement of a function, class or module, and Python keeps it, so tools and help() can show it.
Comments लोगों के लिए notes हैं। Python उन्हें पूरी तरह छोड़ देता है। Docstring अलग है: यह function, class या module का पहला statement होता है, और Python इसे रखता है, ताकि tools और help() इसे दिखा सकें।
注释是写给人看的,Python 会完全跳过。文档字符串(docstring)不同:它是函数、类或模块的第一条语句,Python 会保留它,供工具和 help() 显示。
# A single-line comment: Python skips this line
x = 42 # an inline comment, after the code
def greet(name):
"""Return a personalised greeting message.
Args:
name (str): The person's name.
Returns:
str: A greeting like 'Hello, Asha!'
"""
return f"Hello, {name}!"
print(greet("Asha"))
print(greet.__doc__)
Notice the docstring prints without its left margin. Since Python 3.13, the compiler removes the common leading spaces from docstrings. On Python 3.12 and older, the indented lines would print with their original 4 extra spaces. Python has no special multi-line comment syntax — put # at the start of each line.
ध्यान दें docstring बाएँ margin के बिना छपा। Python 3.13 से compiler docstrings से साझा leading spaces हटा देता है। Python 3.12 और पुराने में indented lines अपने 4 अतिरिक्त spaces के साथ छपतीं। Python में multi-line comment का कोई अलग syntax नहीं — हर line की शुरुआत में # लगाएँ।
注意文档字符串打印时没有左边的缩进。从 Python 3.13 起,编译器会去掉文档字符串中共同的前导空格;在 3.12 及更早版本中,缩进的行会带着原来多出的 4 个空格打印。Python 没有专门的多行注释语法 —— 在每行开头加 # 即可。
Do not repeat what the code does — the code shows that. Write why it exists.
Bad: # add 1 to x
Good: # page numbers start at 1, list positions at 0
Code क्या करता है उसे न दोहराएँ — वह code दिखाता है। लिखें कि वह क्यों है।
ख़राब: # x में 1 जोड़ो
अच्छा: # page numbers 1 से शुरू होते हैं, list positions 0 से
不要重复代码做了什么 —— 代码本身已经表明。要写它为什么存在。
差:# x 加 1
好:# 页码从 1 开始,而列表位置从 0 开始
Variables — Name Tags for Your Data 🏷️Variables — आपके Data के Name Tags 🏷️变量 —— 数据的名字标签 🏷️
You can move a note to another object at any time. You can also stick two notes on the same object. That second fact surprises many beginners, and the animation below shows exactly why.
आप note को कभी भी दूसरे object पर ले जा सकते हैं। आप एक ही object पर दो notes भी चिपका सकते हैं। यह दूसरी बात कई beginners को चौंकाती है, और नीचे का animation ठीक इसका कारण दिखाता है।
你随时可以把便利贴移到别的对象上,也可以在同一个对象上贴两张便利贴。第二点常让初学者吃惊,下面的动画正好说明原因。
Creating Variables — No Declaration NeededVariables बनाना — Declaration की ज़रूरत नहीं创建变量 —— 无需声明
In C or Java you declare a type first: int age = 25;. In Python you just assign with = and the name exists. The value has a type; the name does not, so the same name can later point to a value of another type.
C या Java में पहले type declare करते हैं: int age = 25;। Python में बस = से assign करें और नाम बन जाता है। Type मान का होता है, नाम का नहीं, इसलिए वही नाम बाद में दूसरे type के मान की ओर इशारा कर सकता है।
在 C 或 Java 中要先声明类型:int age = 25;。在 Python 中,用 = 赋值,名字就存在了。类型属于值,不属于名字,所以同一个名字之后可以指向另一种类型的值。
# Create a variable by assigning a value — no type declaration
name = "Asha"
age = 30
height = 5.7
is_student = False
print(type(name))
print(type(age))
print(type(height))
print(type(is_student))
# The same name can later point to a value of a different type
x = 10
x = "ten"
x = [1, 2, 3]
print(x, type(x))
Step through two tiny programs. Numbers cannot be changed in place; lists can. That one difference explains the result.
दो छोटे programs को step-by-step चलाएँ। Numbers अपनी जगह बदले नहीं जा सकते; lists बदली जा सकती हैं। यही एक अंतर नतीजा समझाता है।
逐步运行两个小程序。数字不能原地修改,列表可以。这一点区别就解释了结果。
Naming Rules and Conventions ✍️नाम रखने के नियम और परंपराएँ ✍️命名规则与约定 ✍️
Python has rules (break them and the code will not run) and conventions (break them and the code runs, but other developers find it harder to read). Both matter.
Python में नियम हैं (तोड़ें तो code नहीं चलेगा) और परंपराएँ (तोड़ें तो code चलेगा, पर दूसरे developers को पढ़ना मुश्किल लगेगा)। दोनों ज़रूरी हैं।
Python 有规则(违反则代码无法运行)和约定(违反后代码能跑,但别人更难读懂)。两者都重要。
| Ruleनियम规则 | Validमान्य合法 | Invalidअमान्य不合法 | Whyक्यों原因 |
|---|---|---|---|
| Starts with a letter or _अक्षर या _ से शुरू以字母或 _ 开头 | name, _count, age2 | 2name, @email | A leading digit would look like a numberशुरुआती digit संख्या जैसा लगेगा开头是数字会被当成数字 |
| Letters, digits and _ onlyसिर्फ़ अक्षर, digits और _只能有字母、数字和 _ | first_name, item3 | first-name, item#3 | - is minus; # starts a comment- minus है; # comment शुरू करता है- 是减号;# 开始注释 |
| Letters can be from any languageअक्षर किसी भी भाषा के हो सकते हैं字母可以来自任何语言 | नाम, 名字, café | — | Allowed since Python 3.0 (PEP 3131); English names are still the norm in shared codePython 3.0 से अनुमति (PEP 3131); साझा code में English नाम ही चलन है自 Python 3.0 起允许(PEP 3131);共享代码中仍以英文名为主 |
| Not a keywordKeyword नहीं不能是关键字 | my_class, for_loop | class, for, if | 35 keywords are reserved (see below)35 keywords आरक्षित हैं (नीचे देखें)35 个关键字被保留(见下) |
| Case-sensitiveCase-sensitive区分大小写 | Name ≠ name | — | Three spellings, three variablesतीन spellings, तीन variables三种写法,三个变量 |
| No length limitलंबाई की कोई सीमा नहीं没有长度限制 | total_monthly_revenue | — | Be descriptive, not absurdवर्णनात्मक रहें, बेतुके नहीं要有描述性,但别太夸张 |
# Names may use letters from any language, digits and underscores
नाम = "Mohit"
名字 = "李华"
total_price_2026 = 499
print(नाम, 名字, total_price_2026)
import keyword
print(len(keyword.kwlist), "keywords, for example:", keyword.kwlist[:6])
print("soft keywords:", keyword.softkwlist)
# Shadowing a built-in breaks it
list = [1, 2, 3]
try:
print(list("abc"))
except TypeError as err:
print("TypeError:", err)
del list # remove our variable; the built-in list() works again
print(list("abc"))
The last part shows a real trap. After list = [1, 2, 3], the name list points to your list, so calling list("abc") fails. Deleting your variable with del list brings the built-in back. The four soft keywords (match, case, type, _) act as keywords only in special places, so they are still allowed as names.
आख़िरी हिस्सा एक असली जाल दिखाता है। list = [1, 2, 3] के बाद नाम list आपकी list की ओर इशारा करता है, इसलिए list("abc") असफल होता है। del list से अपना variable हटाने पर built-in वापस आ जाता है। चार soft keywords (match, case, type, _) सिर्फ़ ख़ास जगहों पर keyword की तरह काम करते हैं, इसलिए नाम के रूप में अब भी चलते हैं।
最后一部分展示了一个真实陷阱。执行 list = [1, 2, 3] 后,名字 list 指向你的列表,于是 list("abc") 出错。用 del list 删除你的变量后,内置函数就回来了。四个软关键字(match、case、type、_)只在特定位置才充当关键字,所以仍可用作名字。
PEP 8 Naming ConventionsPEP 8 नामकरण परंपराएँPEP 8 命名约定
Avoid list, str, int, type, id, input, print, sum, max as variable names. As shown above, the built-in stops working in that file until the name is deleted. Use items, names, total instead.
list, str, int, type, id, input, print, sum, max को variable नाम न बनाएँ। ऊपर दिखा कि नाम हटाने तक उस file में built-in काम करना बंद कर देता है। इसकी जगह items, names, total इस्तेमाल करें।
不要用 list、str、int、type、id、input、print、sum、max 作变量名。如上所示,在删除该名字之前,内置函数在这个文件中都无法使用。改用 items、names、total。
Multiple Assignment and Swapping 🔄Multiple Assignment और Swapping 🔄多重赋值与交换 🔄
Python can assign several names in one line, and swap two values without a temporary variable. The right side is evaluated first, then unpacked into the names on the left.
Python एक line में कई नाम assign कर सकता है, और बिना temporary variable के दो मान swap कर सकता है। पहले दाईं ओर का हिस्सा evaluate होता है, फिर बाईं ओर के नामों में बँटता है।
Python 可以一行给多个名字赋值,也可以不用临时变量交换两个值。右边先被求值,然后拆开分给左边的名字。
x, y, z = 10, 20, 30
print(x, y, z)
a = b = c = 0
print(a, b, c)
a, b = 5, 10
a, b = b, a # swap in one line
print(a, b)
coordinates = [28.6139, 77.2090] # New Delhi
latitude, longitude = coordinates
print(f"Lat: {latitude}, Lon: {longitude}")
# careful: a = b = [] gives ONE list two names
p = q = []
p.append("shared!")
print(q)
a = b = c = 0 is safe because numbers cannot be changed in place. But p = q = [] creates one list with two names, so changing it through p also changes q (last line of the output). For separate lists write p, q = [], [].
a = b = c = 0 सुरक्षित है क्योंकि numbers अपनी जगह नहीं बदलते। पर p = q = [] दो नामों वाली एक list बनाता है, इसलिए p से बदलने पर q भी बदल जाता है (output की आख़िरी line)। अलग lists के लिए p, q = [], [] लिखें।
a = b = c = 0 是安全的,因为数字不能原地修改。但 p = q = [] 只创建了一个列表、两个名字,通过 p 修改它,q 也跟着变(见输出最后一行)。要两个独立列表,请写 p, q = [], []。
Data Types — The Four Basic Types 🧩Data Types — चार बुनियादी Types 🧩数据类型 —— 四种基本类型 🧩
Each container allows different actions. You can add two egg counts, but adding two labels just sticks them together. In the same way, a value's type decides what you can do with it:
3 + 4 is 7, but "3" + "4" is "34".हर बर्तन अलग काम की अनुमति देता है। दो अंडों की गिनती जोड़ सकते हैं, पर दो labels जोड़ने पर वे बस साथ चिपक जाते हैं। इसी तरह मान का type तय करता है कि आप उसके साथ क्या कर सकते हैं:
3 + 4 है 7, पर "3" + "4" है "34"।每种容器支持的操作不同。两个鸡蛋数量可以相加,两张标签“相加”只是拼在一起。同样,值的类型决定了你能对它做什么:
3 + 4 是 7,而 "3" + "4" 是 "34"。This lesson covers the four basic built-in types you will use every day: int, float, str and bool. They are not the only ones. Python also has None (meaning "no value"), complex numbers, and collection types such as list and dict that hold other values. Collections come in the next lessons.
यह lesson चार बुनियादी built-in types सिखाता है जो आप रोज़ इस्तेमाल करेंगे: int, float, str और bool। ये अकेले types नहीं हैं। Python में None ("कोई मान नहीं"), complex संख्याएँ, और list व dict जैसे collection types भी हैं जो दूसरे मान रखते हैं। Collections अगले lessons में आएँगे।
本课讲解每天都会用到的四种基本内置类型:int、float、str 和 bool。它们并不是全部类型。Python 还有 None(表示“没有值”)、complex 复数,以及 list、dict 等可以容纳其他值的容器类型。容器类型将在后续课程介绍。
bool sits inside int on purpose: True behaves like 1 and False like 0. That is why True + True is 2.
bool जानबूझकर int के अंदर है: True 1 जैसा और False 0 जैसा व्यवहार करता है। इसीलिए True + True 2 है।
bool 特意画在 int 里面:True 相当于 1,False 相当于 0。所以 True + True 等于 2。
intfloatstrboolif and while decision uses it. A subclass of int.if और while का फ़ैसला इसी से होता है। int का subclass।if 和 while 的判断都靠它。是 int 的子类。int — Whole Numbers 🔢int — पूर्ण संख्याएँ 🔢int —— 整数 🔢
Integers are exact and have no fixed size. In C or Java a 32-bit int overflows after 231 − 1 (about 2.1 billion). Python just uses more memory for bigger numbers.
Integers सटीक होते हैं और उनका कोई तय आकार नहीं। C या Java में 32-bit int 231 − 1 (लगभग 2.1 अरब) के बाद overflow हो जाता है। Python बड़ी संख्याओं के लिए बस ज़्यादा memory लेता है।
整数是精确的,且没有固定大小。在 C 或 Java 中,32 位 int 超过 231 − 1(约 21 亿)就会溢出。Python 只是为更大的数使用更多内存。
age = 25
population = 8_000_000_000 # underscores make big numbers readable
big_number = 10 ** 100
print(type(age), population, len(str(big_number)), "digits")
a, b = 17, 5
print(a + b, a - b, a * b)
print(a / b) # true division: always a float
print(a // b) # floor division
print(a % b) # remainder
print(a ** b) # power
print(-17 // 5, -17 % 5) # floor division rounds DOWN, toward minus infinity
print(0b1010, 0o17, 0xFF) # binary, octal, hexadecimal literals
print(10 / 2)
1. / always gives a float, even when the division is exact: 10 / 2 is 5.0. Use // for a whole-number result.
2. // rounds down (toward minus infinity), not toward zero. So -17 // 5 is -4, and the remainder -17 % 5 is 3. (C and Java give −3 and −2.)
1. / हमेशा float देता है, भाग पूरा जाए तब भी: 10 / 2 है 5.0। पूर्ण संख्या चाहिए तो // लगाएँ।
2. // नीचे (minus infinity की ओर) round करता है, शून्य की ओर नहीं। इसलिए -17 // 5 है -4, और शेष -17 % 5 है 3। (C और Java −3 और −2 देते हैं।)
1. / 总是返回浮点数,即使能整除:10 / 2 是 5.0。需要整数结果请用 //。
2. // 向下取整(朝负无穷),而不是朝零。所以 -17 // 5 是 -4,余数 -17 % 5 是 3。(C 和 Java 给出 −3 和 −2。)
"No size limit" has one practical catch. Converting a huge int to text is limited to 4300 digits by default (since Python 3.11), to protect servers from slow conversions. The number itself is fine. The same script also shows how much memory a few objects really use:
"आकार की कोई सीमा नहीं" में एक व्यावहारिक पेच है। बहुत बड़े int को text में बदलना default रूप से 4300 अंकों तक सीमित है (Python 3.11 से), ताकि servers धीमे conversions से बचें। संख्या ख़ुद ठीक रहती है। यही script यह भी दिखाती है कि कुछ objects असल में कितनी memory लेते हैं:
“没有大小限制”有一个实际的例外:默认情况下(自 Python 3.11 起),把超大整数转成文本最多允许 4300 位,以防服务器被缓慢的转换拖垮。数字本身没问题。同一脚本还显示了几个对象实际占用的内存:
import sys
print(sys.getsizeof(True), sys.getsizeof(0), sys.getsizeof(10**100)) # bytes per object
print(sys.getsizeof(0.1)) # every float object is the same size
print(sys.float_info.dig, sys.float_info.max)
big = 10 ** 5000 # the int itself is fine
print(big.bit_length(), "bits")
try:
print(str(big))
except ValueError as err:
print("ValueError:", err)
sys.set_int_max_str_digits(0) # 0 = no limit (only if you really need it)
print(len(str(big)), "digits")
Reading the first lines: True and 0 each take 28 bytes as Python objects (not 1 bit), and 10**100 takes 72 bytes because it needs more digits. Every float object takes 24 bytes; 8 of them hold the 64-bit value.
पहली lines पढ़ें: True और 0 Python objects के रूप में 28-28 bytes लेते हैं (1 bit नहीं), और 10**100 72 bytes लेता है क्योंकि उसे ज़्यादा अंक चाहिए। हर float object 24 bytes लेता है; उनमें से 8 में 64-bit मान रहता है।
看前几行:True 和 0 作为 Python 对象各占 28 字节(不是 1 位),10**100 需要更多位数,占 72 字节。每个 float 对象占 24 字节,其中 8 字节存放 64 位数值。
float — Decimal Numbers 📏float — दशमलव संख्याएँ 📏float —— 小数 📏
Floats store real numbers in 64-bit binary (IEEE 754 double precision, the same as double in C and Java). That gives about 15–17 significant digits and a range up to about 1.8 × 10308.
Floats वास्तविक संख्याओं को 64-bit binary में store करते हैं (IEEE 754 double precision, C और Java के double जैसा)। इससे लगभग 15–17 सार्थक अंक और लगभग 1.8 × 10308 तक की range मिलती है।
浮点数用 64 位二进制存储实数(IEEE 754 双精度,与 C、Java 的 double 相同),约有 15–17 位有效数字,范围可达约 1.8 × 10308。
price = 19.99
tiny = 1e-8
huge = 6.022e23
print(type(price), tiny, huge, float(7))
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
import math
print(math.isclose(0.1 + 0.2, 0.3))
print(round(0.1 + 0.2, 1))
print(round(2.5), round(3.5)) # round-half-to-even ("banker's rounding")
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))
print(Decimal(0.1)) # the value really stored for 0.1
print(float("inf") > 10**308, float("nan") == float("nan"))
Two surprises are worth remembering. First, 0.1 + 0.2 == 0.3 is False; compare floats with math.isclose(). Second, round() sends halves to the nearest even number ("banker's rounding"), so round(2.5) is 2. The Decimal(0.1) line shows the value the computer really stores for 0.1.
दो आश्चर्य याद रखने लायक़ हैं। पहला, 0.1 + 0.2 == 0.3 False है; floats की तुलना math.isclose() से करें। दूसरा, round() आधे को सबसे नज़दीकी even संख्या पर ले जाता है ("banker's rounding"), इसलिए round(2.5) है 2। Decimal(0.1) वाली line दिखाती है कि computer 0.1 के लिए असल में कौन सा मान store करता है।
有两个意外值得记住。第一,0.1 + 0.2 == 0.3 为 False;比较浮点数请用 math.isclose()。第二,round() 把 .5 舍入到最近的偶数(“银行家舍入”),所以 round(2.5) 是 2。Decimal(0.1) 那一行显示了计算机为 0.1 实际存储的值。
Add 0.1 again and again, as a loop would. Green dots: the sum prints exactly as expected. Red bars: tiny errors (shown ×10¹⁶). All values come from real Python runs.
Loop की तरह 0.1 बार-बार जोड़ें। हरे बिंदु: जोड़ ठीक उम्मीद जैसा छपता है। लाल bars: बहुत छोटी errors (×10¹⁶ करके दिखाई)। सारे मान असली Python runs से हैं।
像循环一样一次次加 0.1。绿点:和打印得与预期完全一致。红条:微小误差(放大 10¹⁶ 倍显示)。所有数值都来自真实的 Python 运行。
JavaScript, Java, C, Rust and almost every other language give the same answer, because they all use the same IEEE 754 hardware format. 0.1 has no exact binary form, just as 1/3 has no exact decimal form (0.333…). For money, use from decimal import Decimal and create values from strings — Decimal("0.1"), not Decimal(0.1) — or count in whole paise or cents with int.
JavaScript, Java, C, Rust और लगभग हर दूसरी भाषा यही जवाब देती है, क्योंकि सब एक ही IEEE 754 hardware format इस्तेमाल करती हैं। 0.1 का कोई सटीक binary रूप नहीं, जैसे 1/3 का कोई सटीक दशमलव रूप नहीं (0.333…)। पैसों के लिए from decimal import Decimal इस्तेमाल करें और मान strings से बनाएँ — Decimal("0.1"), Decimal(0.1) नहीं — या int में पूरे पैसे/cents गिनें।
JavaScript、Java、C、Rust 以及几乎所有语言都给出同样的结果,因为它们使用同一种 IEEE 754 硬件格式。0.1 没有精确的二进制形式,就像 1/3 没有精确的十进制形式(0.333…)。处理金额时请用 from decimal import Decimal,并用字符串创建 —— Decimal("0.1"),而不是 Decimal(0.1) —— 或者用 int 以“分”为单位计数。
int vs float — Quick Comparisonint बनाम float — झटपट तुलनाint 与 float —— 快速对比
| Propertyगुण属性 | int | float |
|---|---|---|
| Decimal pointदशमलव बिंदु小数点 | Noनहीं无 | Yes, always (7.0)हाँ, हमेशा (7.0)有,总是(7.0) |
| Precisionसटीकता精度 | Exact, any sizeसटीक, कोई भी आकार精确,任意大小 | About 15–17 significant digitsलगभग 15–17 सार्थक अंक约 15–17 位有效数字 |
| MemoryMemory内存 | Grows with the number (28 bytes for small ones)संख्या के साथ बढ़ती है (छोटी के लिए 28 bytes)随数值增长(小整数 28 字节) | Fixed: 8-byte value inside a 24-byte objectतय: 24-byte object के अंदर 8-byte मान固定:24 字节对象中含 8 字节数值 |
/ and /// और /// 与 // | / → float; // → int/ → float; // → int/ → float;// → int | Both give float (7.5 // 2 → 3.0)दोनों float देते हैं (7.5 // 2 → 3.0)都得 float(7.5 // 2 → 3.0) |
| Use forकहाँ इस्तेमाल用途 | Counting, indexing, IDs, money in paiseगिनती, indexing, IDs, पैसे (पैसों में)计数、索引、ID、以分为单位的金额 | Measurements, science, percentagesमाप, विज्ञान, प्रतिशत测量、科学计算、百分比 |
| Examplesउदाहरण例子 | 42, -7, 1_000_000 | 3.14, -0.5, 2.5e10 |
str — Text 🔤str — Text 🔤str —— 文本 🔤
A string is a sequence of characters. It is immutable: you cannot change one character inside it. Methods like .upper() or .replace() return a new string and leave the old one as it was.
String characters का एक क्रम है। यह immutable है: इसके अंदर एक character भी नहीं बदल सकते। .upper() या .replace() जैसे methods एक नई string लौटाते हैं और पुरानी को वैसा ही छोड़ देते हैं।
字符串是字符序列,它是不可变的:不能修改其中某个字符。.upper()、.replace() 等方法返回一个新字符串,原字符串保持不变。
Creating Strings — Four WaysStrings बनाना — चार तरीक़े创建字符串 —— 四种方式
msg1 = 'Hello, World!'
msg2 = "Hello, World!" # same as single quotes
poem = """Roses are red,
Violets are blue."""
path = r"C:\Users\new_folder\test" # raw string: backslashes kept as they are
print(msg1 == msg2)
print(poem)
print(path)
Without the r, the backslash starts an escape. \U must be followed by 8 hex digits, so this line does not even compile:
r के बिना backslash एक escape शुरू करता है। \U के बाद 8 hex अंक होने चाहिए, इसलिए यह line compile ही नहीं होती:
没有 r 时,反斜杠会开始一个转义。\U 后面必须跟 8 位十六进制数,所以这一行连编译都通不过:
path = "C:\Users\new_folder" # no r prefix: \U starts an escape
print(path)
String Operations — The Essential ToolkitString Operations — ज़रूरी औज़ार字符串操作 —— 必备工具箱
first, last = "Hello", "World"
print(first + " " + last)
print("─" * 20)
word = "Python"
print(len(word), word[0], word[-1], word[2:5], word[::-1])
text = " Hello, Python World! "
print(repr(text.strip()))
print(repr(text.lower()))
print(text.replace("Python", "Coding"))
print(text.split(","))
print("Python" in text)
print(text.count("o")) # Hello, Python, World → 3
print(text.startswith(" H"))
try:
word[0] = "J"
except TypeError as err:
print("TypeError:", err) # strings are immutable
print("J" + word[1:]) # make a new string instead
repr() is used on two lines so you can see the spaces that .strip() removed. Note text.count("o") is 3 (Hello, Python, World). The last two lines show immutability: assigning to word[0] fails, so you build a new string instead.
दो lines पर repr() लगाया है ताकि आप वे spaces देख सकें जो .strip() ने हटाए। ध्यान दें text.count("o") 3 है (Hello, Python, World)। आख़िरी दो lines immutability दिखाती हैं: word[0] में assign करना असफल होता है, इसलिए नई string बनाते हैं।
有两行用了 repr(),方便你看到 .strip() 去掉的空格。注意 text.count("o") 是 3(Hello、Python、World)。最后两行展示了不可变性:给 word[0] 赋值会失败,所以要生成新字符串。
Type a word and a start, stop and step. Blue numbers are positive positions, purple are negative ones. The orange boxes are the characters picked, numbered in the order Python takes them.
एक शब्द और start, stop, step लिखें। नीले अंक positive positions हैं, बैंगनी negative। नारंगी boxes चुने गए characters हैं, उसी क्रम में गिने गए जिसमें Python उन्हें लेता है।
输入一个单词以及 start、stop、step。蓝色数字是正向位置,紫色是负向位置。橙色方框是被选中的字符,编号表示 Python 取它们的顺序。
f-Strings — The Modern Way to Format Textf-Strings — Text Format करने का आधुनिक तरीक़ाf-string —— 现代的文本格式化方式
Put f before the quotes and write any expression inside { }. After a colon you can add a format spec that controls commas, decimals, percentages, padding and alignment. f-strings arrived in Python 3.6; the {age = } debugging form arrived in 3.8.
Quotes से पहले f लगाएँ और { } के अंदर कोई भी expression लिखें। Colon के बाद एक format spec जोड़ सकते हैं जो commas, दशमलव, प्रतिशत, padding और alignment तय करता है। f-strings Python 3.6 में आए; {age = } वाला debugging रूप 3.8 में।
在引号前加 f,就能在 { } 中写任意表达式。冒号后面可以加格式说明(format spec),控制千位分隔符、小数位、百分比、填充和对齐。f-string 在 Python 3.6 引入;{age = } 调试写法在 3.8 引入。
name, age, salary = "Asha", 30, 75000.50
print(f"Name: {name}, Age: {age}")
print(f"In 5 years: {age + 5}")
print(f"Uppercase: {name.upper()}")
print(f"Salary: ₹{salary:,.2f}")
print(f"Percentage: {0.856:.1%}")
print(f"Binary of 10: {10:b}")
print(f"Padded: {age:05d}")
print(f"[{'hi':<10}] [{'hi':>10}] [{'hi':^10}]")
print(f"{age = }") # handy for debugging (Python 3.8+)
Pick a value and a format spec. The square brackets show exactly where the padding spaces go. Wrong combinations show the real error Python raises.
एक मान और एक format spec चुनें। Square brackets ठीक दिखाते हैं कि padding spaces कहाँ जाते हैं। ग़लत combinations पर Python का असली error दिखता है।
选择一个值和一个格式说明。方括号准确显示填充空格的位置。不匹配的组合会显示 Python 实际抛出的错误。
Python has three ways to format text: % formatting (oldest), .format(), and f-strings. For new code, f-strings are the shortest and easiest to read. The older styles still work and you will see them in existing code, and logging calls still commonly use %-style placeholders.
Python में text format करने के तीन तरीक़े हैं: % formatting (सबसे पुराना), .format(), और f-strings। नए code के लिए f-strings सबसे छोटे और पढ़ने में आसान हैं। पुराने तरीक़े अब भी चलते हैं और मौजूदा code में दिखेंगे, और logging calls में अक्सर %-शैली placeholders ही इस्तेमाल होते हैं।
Python 有三种格式化文本的方式:% 格式化(最老)、.format() 和 f-string。写新代码时,f-string 最简短、最易读。旧写法仍然可用,你会在现有代码中见到它们,日志(logging)调用也仍常用 % 风格的占位符。
Escape CharactersEscape Characters转义字符
| EscapeEscape转义 | Meaningअर्थ含义 | Exampleउदाहरण例子 |
|---|---|---|
\n | New lineनई line换行 | "Line1\nLine2" |
\t | TabTab制表符 | "Col1\tCol2" |
\\ | One backslashएक backslash一个反斜杠 | "C:\\Users" |
\' | Single quoteSingle quote单引号 | 'It\'s fine' |
\" | Double quoteDouble quote双引号 | "He said \"hi\"" |
print("Line1\nLine2")
print("Col1\tCol2")
print("C:\\Users")
print('It\'s fine')
print("He said \"hi\"")
bool — True or False 💡bool — True या False 💡bool —— 真或假 💡
A boolean has only two values: True and False, with a capital first letter. Comparisons produce booleans, and every if and while uses one to decide what to do.
Boolean के सिर्फ़ दो मान हैं: True और False, पहला अक्षर capital। Comparisons से booleans बनते हैं, और हर if और while फ़ैसला करने के लिए इन्हीं का इस्तेमाल करता है।
布尔值只有两个:True 和 False,首字母大写。比较运算产生布尔值,每个 if 和 while 都靠它来决定怎么做。
is_active = True
print(type(is_active))
print(10 > 5, 10 == 5, 10 != 5, 10 >= 10, "abc" == "ABC")
x = 15
print(x > 10 and x < 20)
print(x > 10 or x > 100)
print(not (x > 10))
print(True + True, True * 10, False + 7) # bool is a kind of int
scores = [85, 42, 91, 58, 73, 95]
passed = sum(s >= 60 for s in scores)
print(f"Students passed: {passed}/{len(scores)}")
Because bool is a subclass of int, True counts as 1 and False as 0. That is why sum(s >= 60 for s in scores) counts the passing scores.
क्योंकि bool, int का subclass है, True 1 गिना जाता है और False 0। इसीलिए sum(s >= 60 for s in scores) पास होने वाले scores गिनता है।
因为 bool 是 int 的子类,True 算作 1,False 算作 0。所以 sum(s >= 60 for s in scores) 能数出及格的分数个数。
Truthy and Falsy ValuesTruthy और Falsy मान真值与假值
Any value can be used where Python expects a boolean. A short list of values count as falsy; everything else is truthy.
जहाँ Python boolean चाहता है वहाँ कोई भी मान इस्तेमाल हो सकता है। कुछ गिने-चुने मान falsy हैं; बाक़ी सब truthy।
在 Python 需要布尔值的地方可以使用任何值。只有少数几个值算作假值(falsy),其余都是真值(truthy)。
| Valueमान值 | Type |
|---|---|
False | bool |
None | NoneType |
0, 0.0 | int, float |
"" | str |
[], {}, (), set() | empty collectionsख़ाली collections空容器 |
| Valueमान值 | Whyक्यों原因 |
|---|---|
42, -1, 3.14 | non-zero numberशून्य नहीं非零数 |
"hello" | non-empty stringnon-empty string非空字符串 |
"0", "False", " " | still non-empty strings!फिर भी non-empty strings!仍是非空字符串! |
[0] | a list with one itemएक item वाली list含一个元素的列表 |
| most objectsज़्यादातर objects大多数对象 | truthy unless they define otherwiseजब तक अलग न बताएँ, truthy除非另有定义,否则为真 |
username = ""
if username:
print(f"Welcome, {username}")
else:
print("No username provided")
name = ""
display_name = name or "Anonymous"
print(display_name)
items = []
if not items:
print("Cart is empty")
for value in [0, 0.0, "", [], {}, None, "0", "False", " ", [0]]:
print(f"{value!r:>8} → {bool(value)}")
Type Conversion (Casting) 🔁Type Conversion (Casting) 🔁类型转换 🔁
Built-in functions turn a value of one type into another. You need this all the time, because input() always returns a string, even when the user types a number.
Built-in functions एक type के मान को दूसरे में बदलते हैं। इसकी ज़रूरत बार-बार पड़ती है, क्योंकि input() हमेशा string लौटाता है, चाहे user संख्या ही लिखे।
内置函数可以把一种类型的值转换成另一种。这非常常用,因为 input() 总是返回字符串,即使用户输入的是数字。
age_str = input("Enter your age: ") # input() always returns a str
age = int(age_str)
print(f"Next year you'll be {age + 1}")
print(int("100"), int(" 42 "), int(9.99), int(-9.99)) # int() cuts toward zero
print(float("3.14"), str(42) + " cats")
print(bool(0), bool("hello"), bool("False")) # any non-empty string is True!
for bad in ["hello", "3.14", ""]:
try:
int(bad)
except ValueError as err:
print("ValueError:", err)
print(int(float("3.14")))
print(round(float("3.99"))) # round() if you want rounding
The run above typed 25 at the prompt. Note that int("3.14") fails: int() only reads whole-number text. Convert with float() first, then use int() to cut or round() to round.
ऊपर के run में prompt पर 25 लिखा गया। ध्यान दें int("3.14") असफल होता है: int() सिर्फ़ पूर्ण संख्या वाला text पढ़ता है। पहले float() से बदलें, फिर काटने के लिए int() या round करने के लिए round() लगाएँ।
上面的运行在提示符处输入了 25。注意 int("3.14") 会失败:int() 只能读取整数文本。先用 float() 转换,再用 int() 截断或用 round() 舍入。
Pick a value to see what bool(), int(), float() and str() really return. Red rows are the errors Python raises.
एक मान चुनें और देखें bool(), int(), float() और str() सच में क्या लौटाते हैं। लाल rows वे errors हैं जो Python देता है।
选择一个值,看看 bool()、int()、float() 和 str() 实际返回什么。红色行是 Python 抛出的错误。
type() and isinstance() — Checking Types 🔍type() और isinstance() — Types जाँचना 🔍type() 与 isinstance() —— 检查类型 🔍
type(x) returns the exact type of a value. isinstance(x, T) asks "is x a T, or a subtype of T?" and can take several types at once.
type(x) मान का सटीक type लौटाता है। isinstance(x, T) पूछता है "क्या x एक T है, या T का subtype?" और एक साथ कई types ले सकता है।
type(x) 返回值的确切类型。isinstance(x, T) 问的是“x 是 T 或 T 的子类型吗?”,并且可以一次检查多个类型。
print(type(42), type(3.14), type("hello"), type(True))
x = 42
print(type(x) is int, type(x) is str)
print(isinstance(42, int), isinstance(True, int), isinstance(True, bool))
print(isinstance(3.14, (int, float)))
def double(value):
"""Double a number, but reject anything that is not an int or float."""
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError(f"Expected a number, got {type(value).__name__}")
return value * 2
print(double(21), double(3.5))
for bad in ["21", True]:
try:
double(bad)
except TypeError as err:
print("TypeError:", err)
One fix compared with a typical textbook version: because isinstance(True, int) is True, a check for (int, float) lets booleans through, and double(True) would quietly return 2. The function above rejects bool first. Also prefer type(x) is int over type(x) == int when you really need an exact type check.
आम textbook version से एक सुधार: क्योंकि isinstance(True, int) True है, (int, float) की जाँच booleans को भी आने देती है, और double(True) चुपचाप 2 लौटा देता। ऊपर का function पहले bool को रोकता है। जब सच में सटीक type जाँच चाहिए तो type(x) == int की जगह type(x) is int लिखें।
与常见教材写法相比的一处修正:由于 isinstance(True, int) 为 True,检查 (int, float) 会放过布尔值,double(True) 会悄悄返回 2。上面的函数先排除了 bool。另外,确实需要精确类型检查时,用 type(x) is int 而不是 type(x) == int。
Use isinstance() in real code: it accepts subclasses and checks several types at once. Use type() to look at a value while learning or debugging. Remember the bool case: type(True) is int is False, but isinstance(True, int) is True.
असली code में isinstance() इस्तेमाल करें: यह subclasses मानता है और एक साथ कई types जाँचता है। सीखते या debug करते समय मान देखने के लिए type() लगाएँ। bool वाला मामला याद रखें: type(True) is int False है, पर isinstance(True, int) True।
实际代码中用 isinstance():它接受子类,并能一次检查多个类型。学习或调试时用 type() 查看值。记住布尔值的情况:type(True) is int 为 False,而 isinstance(True, int) 为 True。
Cheat Sheet — The Four Types at a Glance 📋Cheat Sheet — चारों Types एक नज़र में 📋速查表 —— 四种类型一览 📋
| Propertyगुण属性 | int | float | str | bool |
|---|---|---|---|---|
| Exampleउदाहरण例子 | 42 | 3.14 | "hello" | True |
| Mutable?Mutable?可变? | Noनहीं否 | Noनहीं否 | Noनहीं否 | Noनहीं否 |
| Limitsसीमाएँ限制 | Memory only (text conversion capped at 4300 digits by default)सिर्फ़ memory (text conversion default रूप से 4300 अंक तक)仅受内存限制(转文本默认最多 4300 位) | ~15–17 significant digits, max ≈ 1.8e308~15–17 सार्थक अंक, अधिकतम ≈ 1.8e308约 15–17 位有效数字,最大约 1.8e308 | Memory onlyसिर्फ़ memory仅受内存限制 | Two values; a full 28-byte object, not 1 bitदो मान; पूरा 28-byte object, 1 bit नहीं两个值;是完整的 28 字节对象,不是 1 位 |
| Falsy valueFalsy मान假值 | 0 | 0.0 | "" | False |
| Convert withबदलें转换 | int() | float() | str() | bool() |
| Check withजाँचें检查 | isinstance(x, int) (also True for bool!)(bool के लिए भी True!)(对 bool 也为 True!) | isinstance(x, float) | isinstance(x, str) | isinstance(x, bool) |
| Common operationsआम operations常用操作 | + - * / // % ** | + - * / round() | + * [] in .split() .join() | and or not |
| Main useमुख्य उपयोग主要用途 | Counting, indexingगिनती, indexing计数、索引 | Measurements, scienceमाप, विज्ञान测量、科学 | Text, messages, labelsText, messages, labels文本、消息、标签 | Conditions, flagsConditions, flags条件、标志 |
Complete Practice Program 🎓पूरा अभ्यास Program 🎓完整练习程序 🎓
This script uses everything from the lesson: blocks and indentation, comments, variables, all four types, f-string alignment, and booleans. Save it as student_report.py and run python3 student_report.py.
यह script lesson की हर चीज़ इस्तेमाल करती है: blocks और indentation, comments, variables, चारों types, f-string alignment, और booleans। इसे student_report.py नाम से save करें और python3 student_report.py चलाएँ।
这个脚本用到了本课的所有内容:代码块与缩进、注释、变量、四种类型、f-string 对齐以及布尔值。保存为 student_report.py,然后运行 python3 student_report.py。
# student_report.py — syntax, variables and all four basic types together
def get_grade(score):
"""Turn a numeric score into a letter grade."""
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
def main():
name = "Asha Verma" # str
student_id = 2026_001 # int (underscore only for reading)
scores = [88, 92, 75, 95, 83] # ints in a list
average = sum(scores) / len(scores) # float
passed = average >= 60.0 # bool
honour_roll = average >= 85.0 # bool
line = "═" * 34
print(line)
print(" STUDENT REPORT CARD")
print(line)
print(f" Name: {name}")
print(f" ID: {student_id}")
print(f" Subjects: {len(scores)}")
print(line)
subjects = ["Maths", "Science", "English", "History", "Art"]
for subject, score in zip(subjects, scores):
mark = "✓" if score >= 60 else "✗"
print(f" {subject:<10} {score:>3} ({get_grade(score)}) {mark}")
print(line)
print(f" Average: {average:.1f}")
print(f" Grade: {get_grade(average)}")
print(f" Passed: {passed}")
print(f" Honour roll: {honour_roll}")
print(line)
for label, value in [("name", name), ("ID", student_id), ("average", average), ("passed", passed)]:
print(f" type of {label:<8} {type(value).__name__}")
if __name__ == "__main__":
main()
The average is 433 / 5 = 86.6, a float, so get_grade(86.6) returns "B" even though it passes the 85 honour-roll line. Try changing one score and predict the new grade before you run it.
औसत 433 / 5 = 86.6 है, एक float, इसलिए get_grade(86.6) "B" लौटाता है, भले ही यह 85 की honour-roll रेखा पार करता है। एक score बदलें और चलाने से पहले नए grade का अंदाज़ा लगाएँ।
平均分是 433 / 5 = 86.6,一个 float,所以 get_grade(86.6) 返回 "B",尽管它超过了 85 分的荣誉榜线。试着改一个分数,并在运行前预测新的等级。
Golden Rules 🏆सुनहरे नियम 🏆黄金法则 🏆
Six questions with traps from this lesson. Pick an answer to see why.
इस lesson के जालों पर छह सवाल। जवाब चुनें और कारण देखें।
六道包含本课陷阱的题目。选择答案查看解释。
Python's grammar is small: a colon opens a block, indentation defines it, and a line ends a statement. Variables are name tags on objects, not boxes. The four everyday types each have their own rules — ints are exact and unlimited, floats are fast approximations, strings are immutable text, and bools are a kind of int. When a result surprises you, check the type first.
Python का व्याकरण छोटा है: colon block खोलता है, indentation उसे तय करता है, और line ख़त्म होने पर statement ख़त्म। Variables objects पर लगे name tags हैं, boxes नहीं। रोज़ के चारों types के अपने नियम हैं — ints सटीक और असीमित, floats तेज़ अनुमान, strings immutable text, और bools int का एक प्रकार। जब नतीजा चौंकाए, पहले type जाँचें।
Python 的语法规则很少:冒号开启代码块,缩进界定代码块,一行结束一条语句。变量是贴在对象上的名字标签,不是盒子。四种日常类型各有规则 —— int 精确且无上限,float 是快速的近似值,str 是不可变文本,bool 是 int 的一种。结果让你意外时,先检查类型。