BASIC Python (Beginner Level) 📂 Basic Python Programming · 2 of 15 180 min read

Python Syntax, Variables & Data Types

Master Python's core building blocks. This tutorial covers Python syntax rules (indentation, colons, comments), variable creation, naming conventions (PEP 8), and all four primitive data types — int, float, str, and bool — with real code examples and output. Includes type conversion, truthy/falsy values, f-string formatting, type checking with isinstance(), and a complete practice program combining everything.

🌐
SectionSection第 01 节

The Story That Explains Python Syntax 🗾Python Syntax समझाने वाली कहानी 🗾一个解释 Python 语法的故事 🗾

Grammar in a Foreign Countryविदेश में व्याकरण在异国说外语
Imagine landing in Japan for the first time. You want to order food. In Japanese the verb comes at the end of the sentence, and small words called particles mark who does what. Get the grammar wrong and the waiter looks at you, confused.

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.
सोचिए आप पहली बार Japan पहुँचे हैं। आप खाना order करना चाहते हैं। Japanese में verb वाक्य के अंत में आता है, और particles नाम के छोटे शब्द बताते हैं कि कौन क्या कर रहा है। व्याकरण ग़लत हुआ तो waiter उलझन में आपको देखता रह जाता है।

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 在运行第一行之前,会先检查整个文件的语法。

💡
Why Python Syntax MattersPython Syntax क्यों मायने रखता है为什么 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 领域被广泛使用的重要原因。


SectionSection第 02 节

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 代码。其他内容都建立在它们之上。

📏
Rule 1 — Indentation is structureनियम 1 — Indentation ही structure है规则 1 —— 缩进就是结构
Whitespace mattersWhitespace मायने रखता है空白有意义
Spaces at the start of a line group code into blocks. Other languages use { }. Lines in one block must line up exactly. 4 spaces per level is the standard (PEP 8).
Line की शुरुआत के spaces code को blocks में बाँटते हैं। दूसरी भाषाएँ { } इस्तेमाल करती हैं। एक block की lines ठीक एक सीध में होनी चाहिए। हर level पर 4 spaces मानक है (PEP 8)।
行首的空格把代码分成代码块。其他语言用 { }。同一块里的行必须严格对齐。每级 4 个空格是标准写法(PEP 8)。
↵
Rule 2 — No semicolons neededनियम 2 — Semicolon की ज़रूरत नहीं规则 2 —— 不需要分号
One statement per lineहर line एक statement每行一条语句
A line ends a statement. You do not end lines with ; as in C, Java or JavaScript. (A ; is allowed to put two statements on one line, but PEP 8 discourages it.)
Line ख़त्म = statement ख़त्म। C, Java या JavaScript की तरह lines के अंत में ; नहीं लगाते। (एक line में दो statements के लिए ; चल जाता है, पर PEP 8 इसे टालने को कहता है।)
一行结束即一条语句结束,不用像 C、Java 或 JavaScript 那样以 ; 结尾。(; 可以把两条语句写在同一行,但 PEP 8 不建议这样做。)
#
Rule 3 — Comments start with #नियम 3 — Comments # से शुरू规则 3 —— 注释以 # 开头
Ignored by PythonPython इन्हें छोड़ देता हैPython 会忽略
Everything after # on a line is a comment for humans. Explain why the code does something; the code itself shows what.
Line पर # के बाद सब कुछ इंसानों के लिए comment है। Code कुछ क्यों करता है यह समझाएँ; क्या करता है वह code ख़ुद दिखाता है।
一行中 # 之后的内容都是写给人看的注释。注释应说明代码为什么这样做;做了什么代码本身已经表达了。
Aa
Rule 4 — Case-sensitiveनियम 4 — Case-sensitive规则 4 —— 区分大小写
Exact spelling mattersसही spelling ज़रूरी拼写必须精确
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 首字母大写。)
:
Rule 5 — A colon opens a blockनियम 5 — Colon block खोलता है规则 5 —— 冒号开启代码块
if · for · while · def · classif · for · while · def · classif · for · while · def · class
Lines that start a block — if, elif, else, for, while, def, class, try, with — end with :. The indented lines below are the body.
Block शुरू करने वाली lines — if, elif, else, for, while, def, class, try, with — : पर ख़त्म होती हैं। नीचे की indented lines उसका body हैं।
开启代码块的行 —— if、elif、else、for、while、def、class、try、with —— 以 : 结尾,下面缩进的行就是块体。
␣
Bonus — Blank lines are freeBonus — ख़ाली lines मुफ़्त附加 —— 空行随便用
Readability helperपढ़ने में मदद提升可读性
Python ignores blank lines. PEP 8 suggests two blank lines around top-level functions and classes, and single blank lines to separate steps inside a function.
Python ख़ाली lines को अनदेखा करता है। PEP 8 सुझाता है: top-level functions और classes के आसपास दो ख़ाली lines, और function के अंदर क़दम अलग करने के लिए एक।
Python 忽略空行。PEP 8 建议:顶层函数和类前后空两行,函数内部用单个空行分隔逻辑步骤。
🧱 PICTURE 1 — ANATOMY OF A BLOCKतस्वीर 1 — BLOCK की बनावट图 1 —— 代码块的结构
Anatomy of a Python block compared with braces Python — indentationPython — indentationPython —— 缩进 C / Java / JavaScript — bracesC / Java / JavaScript — bracesC / Java / JavaScript —— 花括号 if age >= 18: print("Adult") print("Can vote") print("Done") the blockblock代码块 same indentएक जैसा indent缩进相同 ① colon opens a block① colon block खोलता है① 冒号开启代码块 ② 4 spaces of indent = inside② 4 spaces indent = अंदर② 缩进 4 个空格 = 块内 ③ back to column 0 = block ends③ column 0 पर लौटें = block ख़त्म③ 回到第 0 列 = 块结束 if (age >= 18) { printf("Adult"); printf("Can vote"); } printf("Done"); braces + semicolons mark the structure; indentation is only for humansbraces + semicolons structure बताते हैं; indentation सिर्फ़ इंसानों के लिए花括号和分号决定结构;缩进只是给人看的

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 风格语言用花括号和分号。


SectionSection第 03 节

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")
OUTPUT
It's hot outside Stay hydrated

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")
OUTPUT
File "c1b.py", line 3 print("It's hot outside") ^^^^^ IndentationError: expected an indented block after 'if' statement on line 2
LIVELIVE互动Indentation LabIndentation Lab缩进实验室

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 种组合。

age

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")
OUTPUT
File "c1c.py", line 3 print("1 tab") ^ TabError: inconsistent use of tabs and spaces in indentation
⚠️
Tabs vs Spaces — The Golden RuleTabs बनाम Spaces — सुनहरा नियम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 个空格 —— 请确认这个设置已开启。


SectionSection第 04 节

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__)
OUTPUT
Hello, Asha! Return a personalised greeting message. Args: name (str): The person's name. Returns: str: A greeting like 'Hello, Asha!'

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 没有专门的多行注释语法 —— 在每行开头加 # 即可。

🔑
Comment Best PracticeComment का सबसे अच्छा तरीक़ा注释的最佳实践

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 开始


SectionSection第 05 节

Variables — Name Tags for Your Data 🏷️Variables — आपके Data के Name Tags 🏷️变量 —— 数据的名字标签 🏷️

Sticky Notes, Not BoxesSticky Notes, Boxes नहीं是便利贴,不是盒子
Many books say a variable is a labelled box. For Python, a better picture is a sticky note. The value — a number, some text, a list — is an object living in memory. A variable is just a name written on a sticky note and stuck onto that object.

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.
बहुत सी किताबें कहती हैं variable एक label लगा box है। Python के लिए बेहतर तस्वीर है sticky note। मान — संख्या, text, list — memory में रहने वाला एक object है। Variable बस एक नाम है जो sticky note पर लिखकर उस object पर चिपकाया गया है।

आप note को कभी भी दूसरे object पर ले जा सकते हैं। आप एक ही object पर दो notes भी चिपका सकते हैं। यह दूसरी बात कई beginners को चौंकाती है, और नीचे का animation ठीक इसका कारण दिखाता है।
很多书说变量是贴了标签的盒子。对 Python 来说,更好的比喻是便利贴。值 —— 数字、文本、列表 —— 是存在内存中的对象;变量只是写在便利贴上、贴到这个对象上的名字。

你随时可以把便利贴移到别的对象上,也可以在同一个对象上贴两张便利贴。第二点常让初学者吃惊,下面的动画正好说明原因。

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))
OUTPUT
<class 'str'> <class 'int'> <class 'float'> <class 'bool'> [1, 2, 3] <class 'list'>
LIVELIVE互动Name Tags in ActionName Tags काम करते हुए名字标签的实际表现

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 बदली जा सकती हैं। यही एक अंतर नतीजा समझाता है।

逐步运行两个小程序。数字不能原地修改,列表可以。这一点区别就解释了结果。


SectionSection第 06 节

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, age22name, @emailA leading digit would look like a numberशुरुआती digit संख्या जैसा लगेगा开头是数字会被当成数字
Letters, digits and _ onlyसिर्फ़ अक्षर, digits और _只能有字母、数字和 _first_name, item3first-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_loopclass, for, if35 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"))
OUTPUT
Mohit 李华 499 35 keywords, for example: ['False', 'None', 'True', 'and', 'as', 'assert'] soft keywords: ['_', 'case', 'match', 'type'] TypeError: 'list' object is not callable ['a', 'b', 'c']

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 命名约定

📚 Python naming conventions (PEP 8)Python नामकरण परंपराएँ (PEP 8)Python 命名约定(PEP 8)
Variables
snake_case — lowercase words joined by underscores: user_name, total_price
snake_case — underscores से जुड़े lowercase शब्द: user_name, total_price
snake_case —— 小写单词用下划线连接:user_name、total_price
Functions
snake_case too: calculate_total(), get_user_data()
यह भी snake_case: calculate_total(), get_user_data()
同样用 snake_case:calculate_total()、get_user_data()
Classes
PascalCase — each word capitalised: ShoppingCart, UserProfile
PascalCase — हर शब्द capital से: ShoppingCart, UserProfile
PascalCase —— 每个单词首字母大写:ShoppingCart、UserProfile
Constants
UPPER_SNAKE_CASE: MAX_RETRIES, PI. Python does not stop you changing them — the capitals are a promise to readers.
UPPER_SNAKE_CASE: MAX_RETRIES, PI। Python इन्हें बदलने से नहीं रोकता — capitals पाठकों से एक वादा हैं।
UPPER_SNAKE_CASE:MAX_RETRIES、PI。Python 并不阻止你修改它们 —— 大写只是对读者的约定。
Internal
_leading_underscore means "internal, please don't use from outside": _helper()
_leading_underscore का मतलब "अंदरूनी, बाहर से इस्तेमाल न करें": _helper()
_前导下划线表示“内部使用,请勿从外部调用”:_helper()
⚠️
Never Shadow Built-in NamesBuilt-in नामों को कभी न ढकें切勿遮蔽内置名称

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。


SectionSection第 07 节

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)
OUTPUT
10 20 30 0 0 0 10 5 Lat: 28.6139, Lon: 77.209 ['shared!']
🪤
The Shared-List TrapShared-List का जाल共享列表陷阱

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 = [], []。


SectionSection第 08 节

Data Types — The Four Basic Types 🧩Data Types — चार बुनियादी Types 🧩数据类型 —— 四种基本类型 🧩

Different Containers for Different Thingsअलग चीज़ों के लिए अलग बर्तन不同的东西用不同的容器
A kitchen has different containers: a counting tray for eggs (whole numbers — int), a measuring jug for milk (measurements that can be slightly off — float), a label maker for words (str), and a light switch that is only ON or OFF (bool).

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".
रसोई में अलग-अलग बर्तन होते हैं: अंडे गिनने की tray (पूर्ण संख्याएँ — int), दूध नापने का जग (माप जो थोड़ा ऊपर-नीचे हो सकता है — float), शब्दों के लिए label maker (str), और एक switch जो सिर्फ़ ON या OFF होता है (bool)।

हर बर्तन अलग काम की अनुमति देता है। दो अंडों की गिनती जोड़ सकते हैं, पर दो labels जोड़ने पर वे बस साथ चिपक जाते हैं। इसी तरह मान का type तय करता है कि आप उसके साथ क्या कर सकते हैं: 3 + 4 है 7, पर "3" + "4" है "34"।
厨房里有不同的容器:数鸡蛋的托盘(整数 —— int)、量牛奶的量杯(可能略有误差的测量值 —— float)、给物品贴字的标签机(str),以及只有开和关两种状态的开关(bool)。

每种容器支持的操作不同。两个鸡蛋数量可以相加,两张标签“相加”只是拼在一起。同样,值的类型决定了你能对它做什么: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 等可以容纳其他值的容器类型。容器类型将在后续课程介绍。

🌳 PICTURE 2 — THE TYPE FAMILYतस्वीर 2 — TYPE परिवार图 2 —— 类型家族
Family of Python built-in types object everything in Python is an objectPython में सब कुछ object हैPython 中一切皆对象 NUMBERSNUMBERS数字 intwhole numbers, any sizeपूर्ण संख्याएँ, किसी भी आकार की整数,任意大小boolTrue / False — a kind of intTrue / False — int का एक प्रकारTrue / False —— int 的一种 floatdecimalsदशमलव小数 complex3 + 4j TEXTTEXT文本 str"text""text""文本" NOTHINGकुछ नहीं空值 NoneTypethe value Noneमान None值 None list tuple dict setcollections that hold other objects — next lessonsदूसरे objects रखने वाले collections — अगले lessons容纳其他对象的容器 —— 后续课程 This lesson: int · float · str · boolइस lesson में: int · float · str · bool本课:int · float · str · bool (plus None and complex in brief)(साथ में None और complex संक्षेप में)(另简述 None 和 complex)

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。

🔢
int
Whole numbersपूर्ण संख्याएँ整数
Positive or negative, no decimal point. No size limit — only memory limits it. Exact.
धनात्मक या ऋणात्मक, बिना दशमलव। आकार की कोई सीमा नहीं — सिर्फ़ memory की। बिल्कुल सटीक।
正数或负数,无小数点。没有大小限制 —— 只受内存限制。完全精确。
📏
float
Decimal numbersदशमलव संख्याएँ小数
64-bit IEEE 754 double: about 15–17 significant digits. Fast, but many decimals are stored as close approximations.
64-bit IEEE 754 double: लगभग 15–17 सार्थक अंक। तेज़, पर कई दशमलव क़रीबी अनुमान के रूप में store होते हैं।
64 位 IEEE 754 双精度:约 15–17 位有效数字。速度快,但很多小数只能存为近似值。
🔤
str
TextText文本
A sequence of Unicode characters in quotes. Immutable: you build new strings instead of editing old ones.
Quotes में Unicode characters का क्रम। Immutable: पुरानी strings बदलने की जगह नई बनती हैं।
引号中的 Unicode 字符序列。不可变:不能修改旧字符串,只能生成新字符串。
💡
bool
True or FalseTrue या FalseTrue 或 False
Only two values. Every if and while decision uses it. A subclass of int.
सिर्फ़ दो मान। हर if और while का फ़ैसला इसी से होता है। int का subclass।
只有两个值。每个 if 和 while 的判断都靠它。是 int 的子类。

SectionSection第 09 节

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)
OUTPUT
<class 'int'> 8000000000 101 digits 22 12 85 3.4 3 2 1419857 -4 3 10 15 255 5.0
💡
Two Division TrapsDivision के दो जाल除法的两个陷阱

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")
OUTPUT
28 28 72 24 15 1.7976931348623157e+308 16610 bits ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit 5001 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 位数值。


SectionSection第 10 节

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"))
OUTPUT
<class 'float'> 1e-08 6.022e+23 7.0 0.30000000000000004 False True 0.3 2 4 0.3 0.1000000000000000055511151231257827021181583404541015625 True False

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 实际存储的值。

LIVELIVE互动Float Lab: Keep Adding 0.1Float Lab: 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 运行。

⚠️
The 0.1 + 0.2 Problem — Not a Python Bug0.1 + 0.2 की समस्या — Python का Bug नहीं0.1 + 0.2 问题 —— 不是 Python 的 bug

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गुण属性intfloat
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;// → intBoth 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_0003.14, -0.5, 2.5e10

SectionSection第 11 节

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)
OUTPUT
True Roses are red, Violets are blue. C:\Users\new_folder\test
🪤
Why Windows Paths Need r"..."Windows Paths को r"..." क्यों चाहिए为什么 Windows 路径需要 r"..."

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)
OUTPUT
File "c8b.py", line 1 path = "C:\Users\new_folder" # no r prefix: \U starts an escape ^^^^^^^^^^^^^^^^^^^^^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

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
OUTPUT
Hello World ──────────────────── 6 P n tho nohtyP 'Hello, Python World!' ' hello, python world! ' Hello, Coding World! [' Hello', ' Python World! '] True 3 True TypeError: 'str' object does not support item assignment Jython

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] 赋值会失败,所以要生成新字符串。

LIVELIVE互动String SlicerString Slicer字符串切片器

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+)
OUTPUT
Name: Asha, Age: 30 In 5 years: 35 Uppercase: ASHA Salary: ₹75,000.50 Percentage: 85.6% Binary of 10: 1010 Padded: 00030 [hi ] [ hi] [ hi ] age = 30
LIVELIVE互动Format Spec LabFormat Spec Lab格式说明实验室

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 实际抛出的错误。

🎯
Prefer f-Stringsf-Strings को प्राथमिकता दें优先使用 f-string

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उदाहरण例子
\nNew lineनई line换行"Line1\nLine2"
\tTabTab制表符"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\"")
OUTPUT
Line1 Line2 Col1 Col2 C:\Users It's fine He said "hi"

SectionSection第 12 节

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)}")
OUTPUT
<class 'bool'> True False True True False True True False 2 10 7 Students passed: 4/6

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)。

❌ Falsy (act as False)Falsy (False जैसे)假值(相当于 False)
Valueमान值Type
Falsebool
NoneNoneType
0, 0.0int, float
""str
[], {}, (), set()empty collectionsख़ाली collections空容器
✅ Truthy (act as True)Truthy (True जैसे)真值(相当于 True)
Valueमान值Whyक्यों原因
42, -1, 3.14non-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)}")
OUTPUT
No username provided Anonymous Cart is empty 0 → False 0.0 → False '' → False [] → False {} → False None → False '0' → True 'False' → True ' ' → True [0] → True

SectionSection第 13 节

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() 总是返回字符串,即使用户输入的是数字。

🔄 Conversion functionsConversion functions转换函数
int()
int("42") → 42, int(" 42 ") → 42 (spaces are OK), int(3.99) → 3 and int(-3.99) → −3: it cuts toward zero, it does not round.
int("42") → 42, int(" 42 ") → 42 (spaces चलते हैं), int(3.99) → 3 और int(-3.99) → −3: यह शून्य की ओर काटता है, round नहीं करता।
int("42") → 42,int(" 42 ") → 42(允许空格),int(3.99) → 3,int(-3.99) → −3:向零截断,不是四舍五入。
float()
float("3.14") → 3.14, float(7) → 7.0, float("inf") → inf
float("3.14") → 3.14, float(7) → 7.0, float("inf") → inf
float("3.14") → 3.14,float(7) → 7.0,float("inf") → inf
str()
str(42) → "42", str(True) → "True". Works on any value.
str(42) → "42", str(True) → "True"। किसी भी मान पर चलता है।
str(42) → "42",str(True) → "True"。适用于任何值。
bool()
bool(0) → False, bool("") → False, but bool("False") → True. It checks emptiness, not meaning.
bool(0) → False, bool("") → False, पर bool("False") → True। यह ख़ालीपन जाँचता है, अर्थ नहीं।
bool(0) → False,bool("") → False,但 bool("False") → True。它检查是否为空,而不是含义。
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
OUTPUT
Enter your age: 25 Next year you'll be 26 100 42 9 -9 3.14 42 cats False True True ValueError: invalid literal for int() with base 10: 'hello' ValueError: invalid literal for int() with base 10: '3.14' ValueError: invalid literal for int() with base 10: '' 3 4

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() 舍入。

LIVELIVE互动Conversion LabConversion Lab类型转换实验室

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 抛出的错误。


SectionSection第 14 节

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)
OUTPUT
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> True False True True True True 42 7.0 TypeError: Expected a number, got str TypeError: Expected a number, got bool

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。

🔑
type() vs isinstance() — Which to Use?type() बनाम isinstance() — कौन सा?type() 还是 isinstance()?

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。


SectionSection第 15 节

Cheat Sheet — The Four Types at a Glance 📋Cheat Sheet — चारों Types एक नज़र में 📋速查表 —— 四种类型一览 📋

Propertyगुण属性intfloatstrbool
Exampleउदाहरण例子423.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.8e308Memory onlyसिर्फ़ memory仅受内存限制Two values; a full 28-byte object, not 1 bitदो मान; पूरा 28-byte object, 1 bit नहीं两个值;是完整的 28 字节对象,不是 1 位
Falsy valueFalsy मान假值00.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条件、标志

SectionSection第 16 节

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()
OUTPUT
══════════════════════════════════ STUDENT REPORT CARD ══════════════════════════════════ Name: Asha Verma ID: 2026001 Subjects: 5 ══════════════════════════════════ Maths 88 (B) ✓ Science 92 (A) ✓ English 75 (C) ✓ History 95 (A) ✓ Art 83 (B) ✓ ══════════════════════════════════ Average: 86.6 Grade: B Passed: True Honour roll: True ══════════════════════════════════ type of name str type of ID int type of average float type of passed bool

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 分的荣誉榜线。试着改一个分数,并在运行前预测新的等级。


SectionSection第 17 节

Golden Rules 🏆सुनहरे नियम 🏆黄金法则 🏆

🐍 Python Syntax, Variables & Data Types — 8 RulesPython Syntax, Variables & Data Types — 8 नियमPython 语法、变量与数据类型 —— 8 条法则
1
Indent with 4 spaces, never tabs. Lines in one block must line up exactly. Mixing tabs and spaces raises TabError; a missing indent raises IndentationError.
4 spaces से indent करें, tabs कभी नहीं। एक block की lines ठीक एक सीध में हों। Tabs और spaces मिलाने पर TabError; indent छूटने पर IndentationError।
用 4 个空格缩进,不用 tab。同一块中的行必须严格对齐。混用 tab 和空格会引发 TabError;缺少缩进会引发 IndentationError。
2
End block-starting lines with a colon. if, for, while, def, class — forgetting : gives a SyntaxError.
Block शुरू करने वाली lines colon पर ख़त्म करें। if, for, while, def, class — : भूले तो SyntaxError।
开启代码块的行以冒号结尾。if、for、while、def、class —— 忘了 : 就会 SyntaxError。
3
Use snake_case for variables and functions, PascalCase for classes, UPPER_CASE for constants.
Variables और functions के लिए snake_case, classes के लिए PascalCase, constants के लिए UPPER_CASE।
变量和函数用 snake_case,类用 PascalCase,常量用 UPPER_CASE。
4
Never shadow built-ins. A variable called list or str breaks that function for the rest of the file.
Built-ins को कभी न ढकें। list या str नाम का variable बाक़ी file में उस function को तोड़ देता है।
绝不遮蔽内置名称。名为 list 或 str 的变量会让该函数在文件其余部分失效。
5
input() always returns a string. Convert with int() or float() before doing maths, and handle the ValueError bad input causes.
input() हमेशा string लौटाता है। गणित से पहले int() या float() से बदलें, और ग़लत input से आने वाले ValueError को संभालें।
input() 总是返回字符串。做数学运算前用 int() 或 float() 转换,并处理错误输入引发的 ValueError。
6
Never compare floats with ==. Use math.isclose(a, b). For money, use Decimal("…") from strings, or whole paise in an int.
Floats की तुलना == से कभी न करें। math.isclose(a, b) लगाएँ। पैसों के लिए strings से Decimal("…"), या int में पूरे पैसे।
不要用 == 比较浮点数。使用 math.isclose(a, b)。处理金额用字符串创建的 Decimal("…"),或用 int 以分计数。
7
Remember the surprises: bool("False") is True, round(2.5) is 2, -17 // 5 is −4, and p = q = [] is one shared list.
आश्चर्य याद रखें: bool("False") True है, round(2.5) 2 है, -17 // 5 −4 है, और p = q = [] एक साझा list है।
记住这些意外:bool("False") 为 True,round(2.5) 为 2,-17 // 5 为 −4,p = q = [] 是同一个共享列表。
8
Use f-strings for formatting and isinstance() for type checks — and exclude bool explicitly when you mean "a real number".
Formatting के लिए f-strings और type जाँच के लिए isinstance() — और जब "असली संख्या" चाहिए तो bool को अलग से बाहर करें।
格式化用 f-string,类型检查用 isinstance() —— 当你指的是“真正的数字”时,要显式排除 bool。
LIVELIVE互动Quick Checkछोटी जाँच小测验

Six questions with traps from this lesson. Pick an answer to see why.

इस lesson के जालों पर छह सवाल। जवाब चुनें और कारण देखें।

六道包含本课陷阱的题目。选择答案查看解释。

🧮
Key Takeawayमुख्य सीख核心要点

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 的一种。结果让你意外时,先检查类型。

🐍 Try Python Yourself

Write, run and visualize Python step by step. No install needed.