[Go to site: main page, start]

0% found this document useful (0 votes)
5 views4 pages

Python Syntax Guide

This document serves as a beginner's guide to Python syntax, covering key topics such as variables, data types, operators, control flow, loops, functions, exception handling, file handling, classes, built-in functions, and importing modules. It includes code examples for each topic to illustrate their usage. The guide concludes with practice ideas for applying the concepts learned.

Uploaded by

Priya / DMG
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Python Syntax Guide

This document serves as a beginner's guide to Python syntax, covering key topics such as variables, data types, operators, control flow, loops, functions, exception handling, file handling, classes, built-in functions, and importing modules. It includes code examples for each topic to illustrate their usage. The guide concludes with practice ideas for applying the concepts learned.

Uploaded by

Priya / DMG
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Beginner Syntax Guide

1. Variables & Data Types

# Integer
x = 10 # an integer

# Float
y = 3.14 # a floating point number

# String
name = "Priya" # a string of text

# Boolean
is_active = True # boolean (True or False)

# List
colors = ["red", "green", "blue"] # list of strings

# Dictionary
person = {"name": "Priya", "age": 28} # key-value pairs

2. Operators

# Arithmetic
result = 10 + 5 # addition
result = 10 - 5 # subtraction
result = 10 * 5 # multiplication
result = 10 / 5 # division
result = 10 % 3 # modulus (remainder)
result = 2 ** 3 # exponentiation (power)

# Comparison
print(10 > 5) # greater than -> True
print(10 == 5) # equals -> False
print(10 != 5) # not equal -> True

# Logical
print(True and False) # and -> False
print(True or False) # or -> True
print(not True) # not -> False

1
3. Control Flow (Conditions)

age = 20
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")

4. Loops

For Loop:

# Iterate over list


colors = ["red", "green", "blue"]
for color in colors:
print(color)

While Loop:

count = 0
while count < 5:
print(count)
count += 1 # increment count

5. Functions

def greet(name):
"""Function with one parameter"""
print(f"Hello, {name}!")

greet("Priya") # call function with argument

6. Exception Handling

try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero.")

2
except ValueError:
print("Invalid input.")

7. File Handling

# Write to file
with open("[Link]", "w") as file:
[Link]("Hello File!")

# Read from file


with open("[Link]", "r") as file:
content = [Link]()
print(content)

8. Classes (Object-Oriented Programming)

class Person:
def __init__(self, name, age):
[Link] = name # instance variable
[Link] = age

def greet(self):
print(f"Hi, I'm {[Link]} and I'm {[Link]} years old.")

p1 = Person("Priya", 28)
[Link]()

9. Useful Built-In Functions

len("Hello") # length of string -> 5


int("123") # convert string to integer -> 123
str(456) # convert integer to string -> '456'
range(5) # generates numbers 0 to 4

10. Importing Modules

import math
print([Link](16)) # square root -> 4.0

3
import random
print([Link](1, 10)) # random number between 1 and 10

🎯 Practice Idea:
Start small projects like a To-Do List App, Simple Calculator, or Guess the Number Game to apply these
concepts!

Common questions

Powered by AI

Python operators like the addition (`+`) and multiplication (`*`) can be applied to strings. The `+` operator concatenates strings, such as `'Hello, ' + 'World!'` producing `'Hello, World!'`. The `*` operator repeats strings, like `'Hi' * 3` resulting in `'HiHiHi'`. However, these operators are limited to basic manipulation and cannot directly modify string content or formats without additional methods. Moreover, incorrect assumptions about operator use with non-string data types can lead to `TypeError`. For sophisticated string manipulation, methods like `replace()`, `join()`, and slicing techniques are more powerful but require a deeper understanding of string immutability and Python's method syntax .

Logical operators such as `and`, `or`, and `not` are crucial in constructing complex conditional statements. They can be used within `if` statements to combine multiple conditions. For example, in `if True and False:`, the statement returns `False`, thus the block will not execute . The `or` operator allows execution if at least one condition is true, and `not` reverses the condition's logic, e.g., `not True` results in `False`. These operators impact how code executes by short-circuiting evaluations, which can optimize performance and influence decision-making paths within a program's execution .

Python modules are files containing Python definitions and statements, which can be imported into other programs to use their functionality. Importing modules extends a program's capabilities without writing complex code. For example, the `math` module provides mathematical functions like `math.sqrt()` for square root calculations, while the `random` module offers tools for generating random numbers, such as `random.randint(1, 10)`. These modules enhance functionality by offering pre-built methods and classes, facilitating tasks in scientific computing, random data generation, and more specific applications, thus promoting code efficiency and reusability .

The primary difference between a 'for' loop and a 'while' loop is their use cases. A 'for' loop is best suited for iterating over a sequence, like a list or a range of numbers, where the number of iterations is known beforehand. For example, `for color in colors:` iterates through a list of colors . A 'while' loop, however, is used when the number of iterations is not known and it depends on a condition being true. It continues until the condition becomes false, such as `while count < 5:` which continues until `count` is no longer less than 5. The 'for' loop is more effective when you need to perform a task for each element of a sequence, whereas a 'while' loop is useful for repeating actions until a certain dynamic condition changes .

In Python, dictionaries are collections of key-value pairs, where keys must be of immutable data types like strings, numbers, or tuples. This immutability is essential because it ensures that keys are hashable and can consistently produce a hash value used to retrieve values. For example, using strings like `'name'`, one might construct a dictionary `{'name': 'Priya'}`. Mutable types like lists cannot be used as keys since changes to the object would alter its hash and disrupt dictionary storage, leading to potential errors. The use of mutable versus immutable keys affects the stability and predictability of dictionary operations, underscoring the importance of key choice in data structure design .

Built-in functions in Python provide essential capabilities without needing additional imports. They perform common tasks efficiently, such as type conversion (`int()`, `str()`), iteration (`range()`), and data structure evaluation (`len()`). For instance, `len('Hello')` returns the length of a string, `5`, and `int('123')` converts a string to an integer. Meanwhile, `range(5)` generates numbers from 0 to 4 for iteration purposes. These functions streamline programming by simplifying code for routine operations and enhance productivity by being readily available .

Python's arithmetic operators support operations such as addition (`+`), subtraction (`-`), multiplication (`*`), division (`/`), modulus (`%`), and exponentiation (`**`). These operators can be applied across numeric data types like integers and floats. However, common pitfalls include type errors when combining operations on incompatible types, such as adding an integer to a string directly without conversion. Also, division using `/` always returns a float, which may require type conversion if an integer is desired, and using `%` requires the divisor not to be zero to avoid a `ZeroDivisionError` .

Python's class implementation demonstrates key object-oriented programming (OOP) principles: encapsulation, inheritance, and polymorphism. Encapsulation is seen in the way classes define and restrict access to data and methods. For instance, a `Person` class defines `name` and `age` as attributes, and `greet()` as a method, encapsulating related data and behavior . Inheritance, while not shown explicitly in the example, allows one class to inherit attributes and methods from another, facilitating code reuse. Polymorphism enables different classes to be treated as instances of the same class through a shared interface, enhancing modularity. These principles support building complex, reusable, and maintainable software systems .

To write and read from a file in Python, you can use the `open()` function with different modes. For writing, you can open the file in write mode (`'w'`) and use the `write()` method to add content to the file. For reading, open the file in read mode (`'r'`) and use the `read()` method to retrieve the content. For example, `with open('example.txt', 'w') as file: file.write('Hello File!')` writes to a file, and `with open('example.txt', 'r') as file: content = file.read()` reads from it. The potential outcomes to consider include handling file exceptions such as `FileNotFoundError` when the file does not exist or `IOError` if there are issues with file permissions .

Exception handling improves the robustness of a Python program by allowing it to gracefully handle errors that occur during execution, maintaining execution continuity. By using `try` and `except` blocks, a program can respond to specific errors, such as `ZeroDivisionError` and `ValueError`, with informative messages or alternative logic, thus preventing crashes . Neglecting exception handling can lead to program termination due to unhandled exceptions, producing user-unfriendly error messages and potentially causing loss of unsaved data or states. Proper exception management is crucial for creating resilient software that can deal with unexpected runtime issues .

You might also like