Skip to content

Latest commit

History

History
263 lines (185 loc) · 5.08 KB

File metadata and controls

263 lines (185 loc) · 5.08 KB

Python syntax, data types, and variables

Python Syntax:

Python is known for its clean and readable syntax. Here are some fundamental syntax rules:

  1. Statements and Indentation:

    • Python uses indentation (whitespace) to define blocks of code, rather than curly braces {}. This is a unique feature of Python and helps in maintaining a clean and consistent code structure.

    Example:

    ifcondition:
    # This block is indented, it belongs to the if statementprint("This is indented")
    else:
    print("This is also indented")
  2. Comments:

    • Comments start with a # character and are ignored by the Python interpreter. They are used to add explanations or notes within the code.

    Example:

    # This is a comment
  3. Variables and Identifiers:

    • Variables are used to store data. In Python, you can assign a value to a variable using =. Identifiers are names given to variables, functions, classes, etc.

    Example:

    # Variable assignmentx=10name="John"# Identifiersmy_variable=5
  4. Data Types:

    • Python has several built-in data types, including integers, floats, strings, booleans, lists, tuples, dictionaries, etc. We'll discuss them in more detail below.

Data Types:

1. Numeric Types:

  • int: Integer numbers (e.g., -5, 0, 100)
  • float: Floating-point numbers (e.g., 3.14, -0.5)

Examples:

num_int=42num_float=3.14

2. String:

  • A sequence of characters enclosed in single (' '), double (" "), or triple (''' ''' or """ """) quotes.

Examples:

name="Alice"message='Hello, world!'

3. Boolean:

  • Represents truth values True or False.

Examples:

is_valid=Truehas_permission=False

4. List:

  • Ordered collection of items, which can be of different types.

Example:

my_list= [1, 2, 3, "hello", True]

5. Tuple:

  • Similar to lists but immutable (cannot be changed after creation).

Example:

my_tuple= (1, 2, 3, "world")

6. Dictionary:

  • Collection of key-value pairs.

Example:

my_dict= {'name': 'John', 'age': 30, 'city': 'New York'}

7. Set:

  • Unordered collection of unique items.

Example:

my_set= {1, 2, 3, 4, 4, 4} # Only contains 1, 2, 3, 4

Examples:

Let's combine these concepts in some examples:

Example 1: Variables and Basic Operations

# Variables and basic operationsx=5y=3# Arithmetic operationssum_result=x+ydifference_result=x-yproduct_result=x*ydivision_result=x/yprint(sum_result, difference_result, product_result, division_result)

Lists:

Example 1 - Creating and Manipulating Lists:

# Creating a listmy_list= [1, 2, 3, 4, 5]
# Accessing elementsprint("First element:", my_list[0])
print("Last element:", my_list[-1])
# Modifying elementsmy_list[2] =10print("Modified list:", my_list)
# Appending and removing elementsmy_list.append(6)
my_list.remove(4)
print("Updated list:", my_list)

Tuples:

Example 2 - Creating and Accessing Tuples:

# Creating a tuplemy_tuple= (1, 2, 3, 4, 5)
# Accessing elementsprint("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])

Dictionaries:

Example 3 - Creating and Manipulating Dictionaries:

# Creating a dictionarymy_dict= {'name': 'John', 'age': 30, 'city': 'New York'}
# Accessing valuesprint("Name:", my_dict['name'])
print("Age:", my_dict['age'])
# Adding a new key-value pairmy_dict['email'] ='john@example.com'print("Updated dictionary:", my_dict)
# Iterating through keys and valuesforkey, valueinmy_dict.items():
print(f"{key}: {value}")

Sets:

Example 4 - Creating and Operating on Sets:

# Creating a setmy_set= {1, 2, 3, 4, 4, 4}
# Adding and removing elementsmy_set.add(5)
my_set.remove(2)
print("Updated set:", my_set)

Sample Program for all data types

# Integerinteger_var=42print("Integer Variable:", integer_var)
# Floatfloat_var=3.14print("Float Variable:", float_var)
# Stringstring_var="Hello, World!"print("String Variable:", string_var)
# Listlist_var= [1, 2, 3, 4, 5]
print("List Variable:", list_var)
# Tupletuple_var= (10, 20, 30, 40, 50)
print("Tuple Variable:", tuple_var)
# Dictionarydict_var= {'a': 1, 'b': 2, 'c': 3}
print("Dictionary Variable:", dict_var)
# Setset_var= {1, 2, 3, 4, 5}
print("Set Variable:", set_var)
# Basic tasks# Integer and Float operationsresult=integer_var+float_varprint("Integer + Float:", result)
# String concatenationnew_string=string_var+" Have a nice day!"print("Concatenated String:", new_string)
# List manipulationlist_var.append(6)
list_var.remove(2)
print("Modified List:", list_var)
# Dictionary operationsdict_var['d'] =4deldict_var['a']
print("Modified Dictionary:", dict_var)
# Set operationsset_var.add(6)
set_var.remove(3)
print("Modified Set:", set_var)