Python syntax PDF

Jasmine 133 Published: 09/07/2024

Python syntax PDF

I'm happy to help!

Here is a comprehensive guide to the syntax of Python programming language:

Variables and Data Types

In Python, variables are used to store values. You can assign a value to a variable using the assignment operator (=). The data type of the variable is determined by the type of value you assign.

Integers: x = 1 - whole numbers Floats: y = 3.14 - decimal numbers Strings: name = "John" - sequences of characters, enclosed in quotes Boolean: isAdmin = True - true or false values List: fruits = ["apple", "banana"] - ordered collections of values Tuple: coordinates = (1.0, 2.0) - ordered, immutable collection of values Dictionary: person = {"name": "John", "age": 30} - unordered collection of key-value pairs

Operators

Python supports various operators for performing arithmetic, comparison, logical, and assignment operations.

Arithmetic Operators: Addition: x + y Subtraction: x - y Multiplication: x * y Division: x / y Modulus: x % y Comparison Operators: Equal: x == y Not Equal: x != y Greater Than: x > y Less Than: x < y Greater Than or Equal: x >= y Less Than or Equal: x <= y Logical Operators: And: x and y (both conditions must be true) Or: x or y (at least one condition must be true) Not: not x (negates the result of the expression) Assignment Operators: Simple Assignment: x = y Addition Assignment: x += y Subtraction Assignment: x -= y Multiplication Assignment: x *= y Division Assignment: x /= y

Control Structures

Python supports various control structures for managing the flow of your program.

If-Else Statements: if x > 0: print("Positive"); else: print("Negative") (executes a block of code if a condition is true, or executes another block if it's false) For Loops: for fruit in fruits: print(fruit) (repeats a block of code for each item in a sequence) While Loops: while x < 10: print(x); x += 1 (repeats a block of code while a condition is true) Try-Except Blocks: try: x = 1 / 0; except ZeroDivisionError: print("Cannot divide by zero!") (catches and handles exceptions)

Functions

Python functions are reusable blocks of code that take arguments and return values.

Defining a Function: def greet(name): print(f"Hello, {name}!") Calling a Function: greet("John")

Modules

Python modules are pre-written code libraries that you can import into your program.

Importing a Module: import math (loads the built-in math module) Using a Module: print(math.pi) (uses the pi constant from the math module)

Additional Tips and Tricks

Indentation: Python uses indentation to denote block-level structure. Use spaces or tabs consistently. Comments: Use # for single-line comments, and triple quotes (""") for multi-line comments. Error Handling: Catch and handle exceptions using try-except blocks.

That's a comprehensive overview of the syntax in Python!

Python syntax list

Here is the list of Python syntax:

Variables

x = 5 - Assigning a value to a variable (integer) name = 'John' - Assigning a string to a variable pi = 3.14 - Assigning a floating-point number to a variable is_admin = True - Assigning a boolean value to a variable

Operators

x + y - Addition operator (integer) name == 'John' - Equality operator (boolean) x > 5 - Greater-than operator (boolean) a % b - Modulus operator (integer) -x - Unary minus operator (integer)

Control Structures

if x > 5: print("X is greater than 5") - If statement while x < 10: print(x); x += 1 - While loop for i in range(10): print(i) - For loop try: ... except ExceptionType: ... - Try-except block

Functions

def add(x, y): return x + y - Defining a function (returning the sum of two integers) result = add(3, 5) - Calling the function and storing the result print(add(2, 4)) - Calling the function again with different arguments

Data Structures

my_list = [1, 2, 3] - Creating a list (integer) my_dict = {'name': 'John', 'age': 30} - Creating a dictionary (key-value pairs) my_set = {1, 2, 3} - Creating a set (unordered collection of unique elements)

Importing Modules

import math - Importing the math module from datetime import date - Importing the date class from the datetime module

Working with Files

with open('file.txt', 'r') as file: ... - Opening a file for reading (context manager) open('file.txt', 'w').write('Hello, world!') - Creating or writing to a file file = open('file.txt', 'a'); file.write('New linen'); file.close() - Appending to a file

Working with Strings

s = 'hello' - Assigning a string to a variable print(s.upper()) - Converting the string to uppercase print(s.replace('h', 'H')) - Replacing characters in the string print(s.split()) - Splitting the string into words or substrings

Working with Lists

my_list = [1, 2, 3] - Creating a list (integer) my_list.append(4) - Adding an element to the end of the list print(my_list[0]) - Accessing the first element of the list my_list.sort() - Sorting the list in ascending order

Working with Dictionaries

my_dict = {'name': 'John', 'age': 30} - Creating a dictionary (key-value pairs) print(my_dict['name']) - Accessing the value associated with the key 'name' my_dict.update({'city': 'New York'}) - Updating the dictionary by adding a new key-value pair del my_dict['age'] - Removing the key-value pair associated with the key 'age'