胆固醇偏高是什么原因| 小肠火吃什么药效果快| 幽门螺杆菌吃什么药好| 东山再起是什么生肖| 3个土念什么| 舌头有点麻是什么病的前兆| 16开是什么意思| adhd是什么病| 事半功倍什么意思| 八月十七是什么星座| 相依相偎是什么意思| 1978年属什么的| 12月13日是什么星座| 骨髓抑制是什么意思| 胆红素高是什么原因引起的| 婴儿蓝是什么颜色| 博字五行属什么| 经常放屁什么原因| 手痒脚痒是什么原因| 龙眼是什么| 头疼呕吐吃什么药| 灵芝有什么功效和作用| 子宫内膜14mm说明什么| 医生是什么生肖| 上热下寒吃什么食物好| 男人为什么喜欢吃奶| 10是什么意思| 喝黑苦荞茶有什么好处和坏处| 为什么会骨盆前倾| 省委常委是什么级别| 烤麸是什么做的| 靳东妹妹叫什么名字| 乾隆的名字叫什么| 十二月六号是什么星座| 白薯是什么| 牙痛安又叫什么| 什么因果才会有双胞胎| 尿酸高什么引起的| 什么是蜂胶| 卡点是什么意思| 7月份可以种什么菜| 花甲吃什么| 月经量减少是什么原因| 稷是什么作物| 总是失眠是什么原因| 形态欠规则是什么意思| 欣字属于五行属什么| 奶泡是什么| 细菌计数高是什么原因| 龙眼是什么季节的水果| 苏轼为什么反对王安石变法| 肾阴阳两虚用什么药| 工装裤配什么鞋| 破相是什么意思| 月经为什么来了一点又不来了| seifini是什么牌子| 猫吃什么下奶最快最多| 晴字五行属什么| 部首和偏旁有什么区别| 鼻咽癌有什么症状| 国历是什么意思| 419是什么意思| 不什么好什么| 拜谒是什么意思| 长命锁一般由什么人送| 白猫进家有什么预兆| 1946年属什么| 玻璃瓶属于什么垃圾| 气性大是什么意思| 草字头一个见念什么| 十二指肠溃疡吃什么中成药| 八路军为什么叫八路军| 左边肚子疼是什么原因| 下眼睑红肿是什么原因| 游泳要带什么东西| 眼睛出血什么原因| 喝红茶有什么好处和坏处| 类风湿不能吃什么东西| 大象的鼻子有什么作用| 小鸟喜欢吃什么食物| 胃出血吃什么药| 正师级相当于地方什么级别| 悲观是什么意思| 婴儿流鼻涕吃什么药| 大拇指发抖是什么原因| 脱式计算是什么意思| 女人胃寒吃什么好得快| 盗汗和自汗有什么区别| u熊是什么意思| 牛油果和什么不能一起吃| 肾结石是因什么而起| 糖化血红蛋白是什么| 回族信奉什么教| 子宫内膜增生是什么原因| 五点多是什么时辰| q1什么意思| 女人做梦哭醒预示什么| 浮肿是什么原因造成的| 睾丸痛挂什么科| 现在有什么水果| island什么意思| 96年的鼠是什么命| 失眠看什么科| 朱砂有什么用| 一什么青蛙| 蚂蚁上树是什么菜| 灰枣和红枣有什么区别| 醋加小苏打有什么作用| 傻白甜什么意思| 馍是什么意思| 睡不着吃什么药最有效| 梦见考试是什么预兆| 怀孕做糖耐是检查什么| 茵陈是什么| 什么言| 枸杞泡水喝有什么功效| 心悸吃什么药效果好| 查询电话号码拨打什么| 粉色配什么颜色| 清明节与什么生肖有关| 失眠去药店买什么药| se什么意思| 有鳞状细胞是什么意思| 海丽汉森是什么档次| 农历12月26日是什么星座| 菊花代表什么| cst是什么时间| 梦见亲人是什么意思| 丘疹性荨麻疹用什么药| 印度尼西亚是什么人种| 减肥晚上吃什么合适| 团委书记是什么级别| 洗面奶和洁面乳有什么区别| 撞车了打什么电话| 姨妈发黑量少什么原因| 知府相当于现在什么官| 灵犀是什么意思| cet是什么意思| 粉条是什么做的| 晚上夜尿多吃什么药| 吃什么减肥| 倒模是什么意思| 女性性冷淡是什么原因| 基围虾为什么叫基围虾| 扁平疣是什么病| 白鹭吃什么| 空降是什么意思| 乳头胀痛什么原因| 窦性心律早期复极是什么意思| 怀孕两个月出血是什么原因| 手腕长痣代表什么意思| 钠是什么东西| 六亲不认什么意思| 什么的大自然| 六月底是什么星座| 舌头两侧溃疡吃什么药| 天梭手表属于什么档次| 为什么一个月来两次姨妈| 儿童乘坐高铁需要什么证件| 梦见捡金首饰是什么意思| 放下执念是什么意思| vr眼镜是什么| 尾骨疼是什么原因| 国窖1573是什么香型| 化痰吃什么药| 农历七月份是什么星座| 早期教育是什么专业| 尿浑浊是什么病的前兆| 县级干部是什么级别| 肾构错瘤要注意什么| 拉肚子为什么会发烧| 今天什么时候出梅| 反式脂肪酸是什么| 大姨妈量少是什么原因| 皮毒清软膏有什么功效| 肝脏低密度灶是什么意思| 四大发明有什么| 好人是什么意思| 英语四级是什么水平| 2.16是什么星座| 丁字是什么意思| 皮肤黑穿什么颜色的衣服| 有什么汤菜谱大全| 狗狗冠状是什么症状| 寒酸是什么意思| 男人吃秋葵有什么好处| 皮重是什么意思| 低烧挂什么科| 胎盘内血池是什么| 2月17日是什么星座| 句号代表什么意思| 为什么左眼皮一直跳| 北斗是什么意思| 黄体破裂是什么原因| pr是什么意思| 下野是什么意思| 标准员是干什么的| mens是什么意思| a02是什么牌子| 巨峰葡萄为什么叫巨峰| 组织部是干什么的| 小产是什么意思| 词讼是什么意思| rj什么意思| 7月15是什么节日| 血容量不足是什么意思| 琛字五行属什么| cmb是什么意思| 血糖高能喝什么饮料| 上夜班吃什么对身体好| 剪什么样的发型好看| 01什么意思| 屌丝是什么| 尿检阴性是什么意思| 毛躁是什么意思| 肠胀气是什么原因| 心跳过缓吃什么药| 鼻子上火吃什么药| ray是什么意思| 天天流鼻血是什么原因| 白芍的功效与作用是什么| 低血糖吃什么水果| 我们为什么会笑| 睡觉流口水是什么原因| 马华读什么| 里正相当于现在什么官| 同居是什么意思| 50米7秒什么水平| 脂肪瘤应该挂什么科| 甲沟炎用什么药| 脚趾抽筋是什么原因引起的| 宿便是什么意思| 肾衰竭有什么症状| 枕神经痛吃什么药| 波司登是什么档次| menu是什么意思| 寒露是什么季节| 一般手脚慢进什么工厂| 8五行属什么| 三句半是什么意思| 牛跟什么生肖相冲| 1962年属什么生肖| 6月什么星座| 吃鱼油有什么好处| 遗传代谢病是什么意思| 妆前乳是什么| 什么是条件兵| 单车是什么意思| 哺乳期发烧吃什么药| 夏至吃什么食物| 什么季节补钙效果最好| 孕妇吃什么坚果比较好| 黄体不足吃什么| 过房养是什么意思| 天秤女和什么星座最配| 喝山楂泡水有什么功效| 打板是什么意思| 月经为什么会提前| 冰岛茶属于什么茶| 打日本电话前面加什么| 上海为什么叫魔都| 1992属什么生肖| 木节念什么| 外痔疮有什么症状| 百度
Bytes

东北小咬是什么虫子

Last Updated: 7th December, 2024
百度 而目前正进行的二期考古中,已发掘出的河床基岩结构特征与文物出土情况,有力佐证了专家用“3D藏宝图”划定的古河道。

This tutorial provided an overview of indentation in Python, a significant aspect of the language's syntax used to define code blocks. Python uses indentation to indicate the scope of code blocks such as functions, loops, conditionals, classes, etc. Let's understand the role and importance of indentation in python in detail.

Indentation in Python

What is Indentation in Python?

Indentation is significant in Python, a programming language known for its readability and simplicity indentation groups statements that belong together, such as a loop or a conditional statement. Python uses indentation instead of brackets to indicate blocks of code. Incorrect indentation could result in an error. ? Similar to a hopscotch game - hopping on one foot and after that the other, following the lines of the board, Python takes after the lines of code within the program. On the off chance that the lines of code were not enough indented, Python would not be able to execute the code within the correct order, and the program would not work as intended:

What is Indentation

For example, Let's write a simple program that prints the numbers from 1 to 10 using a for loop:

for?i?in?range(1,?11):?
    print(i)

In this program, the print(i) statement should be indented one level to the right of the for statement. This indentation indicates that the print(i) statement is part of the loop and should be executed for each value of I in the range. ?? To ensure proper execution of the program, it is crucial to include indentation before the print(i) statement.

for?i?in?range(1,?11):
print(i)

This program will also raise an IndentationError because the print(i) statement is not indented to the right of the for statement. Python cannot determine which statements are part of the block.

How to Intend Your Python Code?

If you're coding in Python, one of the most important things to remember is the proper indentation of your code. Good Python indentation is necessary to make your code readable and easy to understand, both for yourself and others who may read your code later.

  • So how can you ensure that your code is properly indented? To automatically indent your code, use a text editor with this feature already included. Some widely-used text editors that offer this feature are Sublime Text, Google Studio, Visual Studio Code, etc.
  • To ensure proper indentation, use the tab key to indent your code. This will help keep your code organized and easy to read. However, avoid over-indenting your code, as this can make it difficult to read.

How to Intend Your Python Code

For Example:

If we are writing a code if a particular number is even or odd:

number=20
if number!=0:
    if number%2==0:    
        print('Number is Even')
    else:
        print('Number is Odd')
else: 
    print('Number is neither even nor odd')

The above example shows that the second if-else statement is a code block under the first if-else statement because we have given a proper indentation for that code block.

How will the Above Code be Compiled?

  • It will check the first line to find ?? an integer variable??.
  • Then?? , as soon as ?? it goes to the second line, it will find the if statement, and another if statement under the first statement will check ?? if the condition is satisfied.
  • If the second condition is unsatisfied, it will go to ?? the nested else statement.
  • But if the first if statement condition is not satisfied??, it will directly jump to the last else ???? statement as it is outside our code block and the first else statement after the if code block.

Python Indentation Rules with Examples

1. Indentation is Mandatory

  • All lines in a code block must be indented.
  • A block of code is typically associated with structures like if, for, while, def, class, etc.

Example:

if x >?0:
    print("Positive number")? # Correctly indented
else:
print("Non-positive number")? # Raises an IndentationError

2. Consistency in Indentation

  • Use the?same amount of spaces or tabs within a block.
  • Mixing tabs and spaces leads to errors.

Example:

if?True:
    print("Use 4 spaces")? # Consistent indentation
        print("Inconsistent indentation")? # Error: IndentationError

3. Recommended Indentation (PEP 8 Style Guide)

Example:

# PEP 8 Recommended Indentation
def?greet():
    print("Hello!")? # 4 spaces
    if?True:
        print("Python is awesome!")? # Nested block with 4 more spaces

4. Indentation for Nested Blocks

  • Indentation increases for each nested block to clearly define scope and hierarchy.

Example:

if condition1:
    print("Block 1")
    if condition2:
        print("Nested Block")
    print("Back to Block 1")
print("Outside all blocks")

5. Improper Indentation Raises Errors

  • Inconsistent or missing indentation will raise an IndentationError or TabError.

Example:

# Mixing tabs and spaces
def?function():
\tprint("Tab used here")? # Tab character
    print("Spaces used here")? # Raises TabError

6. Blank Lines and Continuation Lines

  • Indentation is not required for blank lines.
  • For long lines broken across multiple lines, use?hanging indentation or parentheses, and align properly.

Example:

# Hanging Indentation
result = (first_value
          + second_value
          + third_value)? # Aligned indentation

7. Comments Do Not Affect Indentation

  • Comments can be placed at any indentation level.

Example:

if?True:
    # This is a comment
    print("Indented code")

Python Indentation Examples

1. Proper Indentation in if-else

Proper indentation ensures that blocks of code execute in the right context.

# Example
number =?5
if number >?0:
    print("Positive number")
else:
    print("Non-positive number")

Output:

Positive number

2. Improper Indentation

Incorrect indentation leads to a syntax error since Python relies on indentation to define code blocks.

# Example
number =?5
if number >?0:
print("Positive number")? # Improper indentation
else:
    print("Non-positive number")

Error:

IndentationError: expected an indented block

3. Nested Indentation

Nested blocks should have progressively deeper indentation to maintain structure.

# Example
number =?5
if number >?0:
    print("Positive number")
    if number %?2 ==?0:
        print("Even number")
    else:
        print("Odd number")

Output:

Positive number
Odd number

4. Mixing Tabs and Spaces (Improper)

Mixing tabs and spaces within the same block leads to a TabError.

# Example
def?greet():
\tprint("Hello!")? # Tab used here
    print("Welcome!")? # Spaces used here

Error:

TabError: inconsistent use of tabs?and spaces?in indentation

5. Indentation in Loops

Loops with proper indentation execute nested and outer loops without issues.

# Example
for i?in range(3):
    print(f"Outer Loop {i}")
    for j?in range(2):
        print(f"? Inner Loop {j}")
    print("Back to Outer Loop")

Output:

Outer Loop?0
  Inner Loop?0
  Inner Loop?1
Back to Outer Loop
Outer Loop?1
  Inner Loop?0
  Inner Loop?1
Back to Outer Loop
Outer Loop?2
  Inner Loop?0
  Inner Loop?1
Back to Outer Loop

6. Function with Correct Indentation

Correctly indented functions ensure proper execution of statements within their block.

# Example
def?add_numbers(a, b):
    result = a + b
    print(f"Sum of {a} and {b} is {result}")
    return result

add_numbers(3,?4)

Output:

Sum of?3?and?4?is?7

7. Indentation with Comments

Comments do not affect indentation and can be placed anywhere.

# Example
if?True:
    # This is a comment
    print("Indented code")
    # Another comment
    print("Still indented")
print("Outside the block")

Output:

Indented code
Still indented
Outside the block

9. Multi-line Statements with Indentation

Multi-line statements require proper alignment for readability and execution.

# Example
total = (1 +?2 +
        3 +?4 +
        5)
print("Total:", total)

Output:

Total:?15

10. Indentation in Class Definitions

Classes with correct indentation ensure that methods and attributes are scoped properly.

# Example
class?MyClass:
    def?__init__(self, name):
        self.name = name

    def?greet(self):
        print(f"Hello, {self.name}!")

obj = MyClass("Python")
obj.greet()

Output:

Hello, Python!

How to Avoid Indentation Error in Python?

Python Indentation Errors

What is Indentation Error in Python?

In Python, an indentation error occurs when spaces or tabs are not placed properly. Python uses indentation to group statements. If the interpreter finds issues with the spaces or tabs, it can halt execution. The error message indicates the line number and nature of the error. To fix it, check each line for proper indentation, ensuring 4 whitespaces for each level of indentation.

Incorrect Spacing

def my_function():
  print("Hello, Data Science Enthusiasts!")
   print("This line has an extra space.")
   
my_function()

In this example, the second print statement contains an additional space before it, which leads to an indentation error.

Mixing Spaces and Tabs

def my_function():
  print("Hello,Data Science Enthusiasts!")
        print("This line uses both spaces and tabs.")
        
my_function()

In this example, the second print statement has an indentation error because it uses a mix of spaces and tabs for indentation.

Inconsistent Indentation

def my_function():
    print("Hello, Data Science Enthusiasts!")
  print("This line has inconsistent indentation.")
  
my_function()

In this example, the second print statement has inconsistent indentation compared to the first print statement, which causes an indentation error.

Bad Block Indentation

def my_function():
    print("Hello, Data Science Enthusiasts!")
        print("This line is incorrectly indented.")
    print("This line is back to the correct indentation.")
    
my_function()

In this example, the second print statement needs to be indented correctly. This causes an indentation error for the entire block of code. To avoid most indentation errors in Python code, pay attention to these errors and follow the tips I mentioned earlier.

Best Practices for using Indentation in Python

Here are a few best practices for using indentation in Python: ??

  • Use consistent indentation throughout your code. ??
  • Use four spaces for indentation. ??
  • Avoid mixing spaces and tabs. ???
  • Indent the code inside blocks consistently. ??
  • Use an editor that supports automatic indentation. ??

Conclusion

In conclusion, space could be a principal perspective of Python utilized to demonstrate the structure of the code. Python's dependence on space has been questionable, but it is by and large considered a supportive highlight that creates code more readable and simpler to get it. By taking after the best hones for space, you'll be able to guarantee that your Python code is steady and simple to preserve.

Quiz

  1. Which of the following statements is true about Python's use of indentation?
    1. Indentation is optional in Python.?
    2. Python uses braces to indicate the structure of the code.?
    3. Indentation is used to group statements that belong together.?
    4. Indentation is used for decoration purposes only.

Answer: C: Indentation is used to group statements that belong together.

  1. What is the purpose of indentation in Python?
    1. To make code more complex
    2. To indicate the start and end of a block of code
    3. To reduce the number of lines of code required
    4. To make the code run faster

Answer: B. To indicate the start and end of a block of code.

  1. Why is proper indentation important in Python?
    1. It makes the code look more organized.
    2. It helps to improve code readability.
    3. It is a requirement in Python syntax.?
    4. It makes the code easier to debug.

Answer: B. It helps to improve code readability.

Module 2: Basics of Python ProgrammingIndentation in Python (With Examples)

Top Tutorials

Related Articles

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

? 2025 AlmaBetter
手上长小水泡很痒是什么原因 飞地是什么意思 清奇是什么意思 鸽子炖什么补气血 2004年属猴的是什么命
骨质密度不均匀是什么意思 特别容易出汗是什么原因 有什么无什么的成语 鑫字属于五行属什么 什么嘴什么舌
肚脐中间疼是什么原因 属马跟什么属相犯冲 骨质疏松症有什么症状 来大姨妈喝什么汤比较好 陈皮泡酒喝有什么功效和作用
不妄作劳什么意思 抗美援朝什么时候结束 吃什么药减肥效果好 什么叫咳嗽变异性哮喘 男性看下面挂什么科室
儿童肠胃炎吃什么药aiwuzhiyu.com 鸡蛋加什么吃壮阳持久hcv8jop2ns3r.cn 吃百家饭是什么意思hcv7jop5ns1r.cn 同床出血什么原因呢hcv9jop1ns4r.cn 丹毒用什么药膏hcv9jop6ns9r.cn
zf是什么意思baiqunet.com 吃什么补叶酸最快wmyky.com 易岗易薪是什么意思hcv9jop0ns1r.cn 喜大普奔什么意思hcv8jop2ns7r.cn 想改名字需要什么手续96micro.com
枸杞泡水喝有什么作用和功效hcv9jop2ns6r.cn 为什么说金克木生财hcv8jop8ns0r.cn 7月12日是什么日子hcv8jop6ns3r.cn 高密度脂蛋白是什么意思hcv7jop9ns1r.cn 埃及法老是什么意思hcv7jop9ns8r.cn
心跳过缓是什么原因造成的hcv9jop5ns5r.cn 脖子上长小肉疙瘩是什么原因hcv8jop8ns8r.cn 肩袖损伤吃什么药hcv8jop8ns2r.cn db是什么单位1949doufunao.com 双修是什么意思hcv8jop3ns7r.cn
百度