What is python syntax??
Python syntax refers to the set of rules that defines the combinations of symbols that are considered to be correctly structured programs in the Python language. These rules make sure that programs written in Python should be structured and formatted, ensuring that the Python interpreter can understand and execute them correctly. Here are some aspects of
Python Interactive Shell
- Start the Python interpreter by simply typing python (or python3 on some systems) in the terminal or command prompt. We can then run Python commands interactively.
- To exit, we can type exit() or press Ctrl + D
Indentation in Python
Python Indentation refers to the use of whitespace (spaces or tabs) at the beginning of a line of code in Python. It is used to define the code blocks. Indentation is crucial in Python because, unlike many other programming languages that use braces “{}” to define blocks, Python uses indentation. It improves the readability of Python code, but on other hand it became difficult to rectify indentation errors. Even one extra or less space can leads to identation error.
Python Variables
Variables in Python are essentially named references pointing to objects in memory. Unlike some other languages, in Python, you don’t need to declare a variable’s type explicitly. Based on the value assigned, Python will dynamically determine the type. In the below example, we create a variable ‘a’ and initialize it with interger value so, type of ‘a’ is int then we store the string value in ‘a’ it become ‘str’ type. It is called dynamic typing which means variable’s data type can change during runtime.
Python Identifiers
In Python, identifiers are the building blocks of a program. Identifiers are unique names that are assigned to variables, functions, classes, and other entities. They are used to uniquely identify the entity within the program. They should start with a letter (a-z, A-Z) or an underscore “_” and can be followed by letters, numbers, or underscores. In the below example “first_name” is an identifier that store string value.
first_name = "Ram"
For naming of an identifier we have to follows some rules given below:
- Identifiers can be composed of alphabets (either uppercase or lowercase), numbers (0–9), and the underscore character (_). They shouldn’t include any special characters or spaces.
- The starting character of an identifier must be an alphabet or an underscore.
- Certain words in Python, known as reserved Identifier, have specific functions and meanings. As such, these words can’t be chosen as identifiers. For instance, the term “print” already serves a specific purpose in Python and can’t be used as an identifier.
- Within its specific scope or namespace, each identifier should have a distinct name.
Python Identifiers
In Python, identifiers are the building blocks of a program. Identifiers are unique names that are assigned to variables, functions, classes, and other entities. They are used to uniquely identify the entity within the program. They should start with a letter (a-z, A-Z) or an underscore “_” and can be followed by letters, numbers, or underscores. In the below example “first_name” is an identifier that store string value.
first_name = "Ram"
For naming of an identifier we have to follows some rules given below:
- Identifiers can be composed of alphabets (either uppercase or lowercase), numbers (0–9), and the underscore character (_). They shouldn’t include any special characters or spaces.
- The starting character of an identifier must be an alphabet or an underscore.
- Certain words in Python, known as reserved Identifier, have specific functions and meanings. As such, these words can’t be chosen as identifiers. For instance, the term “print” already serves a specific purpose in Python and can’t be used as an identifier.
- Within its specific scope or namespace, each identifier should have a distinct name.
Python keywords
Keywords in Python are reserved words that have special meanings. For example if, else, while, etc. They cannot be used as identifiers. Below is the list of keywords in Python.
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
With different versions of Python some keywords may vary. We can see all the keywords of current version of Python using below code.
>>>import keyword
>>>print(keyword.kwlist)
Comments in Python
Comments in Python are statements written within the code. They are meant to explain, clarify, or give context about specific parts of the code. The purpose of comments is to explain the working of a code, they have no impact on the execution or outcome of a program.
Python Single Line Comment
Single line comments are preceded by the “#” symbol. Everything after this symbol on the same line is considered a comment and not considered as the part of execution of code. Below is the example of single line comment and we can see that there is no effect of comment on output.
Python3
first_name = "Reddy"
last_name = "Anna"
# print full name
print(first_name, last_name)
Output
Reddy Anna
Python Multi-line Comment
Python doesn’t have a specific syntax for multi-line comments. However, programmers often use multiple single-line comments, one after the other, or sometimes triple quotes (either ”’ or “””), even though they’re technically string literals. Below is the example of multiline comment.
Python3
# This is a Python program
# to explain multiline comment.
'''
Functions to print table of
any number.
'''
def print_table(n):
for i in range(1,11):
print(i*n)
print_table(4)
Output
4
8
12
16
20
24
28
32
36
40
Multiple Line Statements
Writing a long statement in a code is not feasible or readable. Writing a long single line statement in multiple lines by breaking it is more readable so, we have this feature in Python and we can break long statement into different ways such as:
Using Backslashes (\)
In Python, you can break a statement into multiple lines using the backslash (\). This method is useful, especially when we are working with strings or mathematical operations.
Python3
sentence = "This is a very long sentence that we want to " \
"split over multiple lines for better readability."
print(sentence)# For mathematical operations
total = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9print(total)
Output
This is a very long sentence that we want to split over multiple lines for better readability.
45
Using Parentheses
For certain constructs, like lists, tuples, or function arguments, we can split statements over multiple lines inside the parentheses, without needing backslashes.
Python3
# Create list
numbers = [1, 2, 3,
4, 5, 6,
7, 8, 9]
def total(num1, num2, num3, num4):
print(num1+num2+num3+num4)
# Function call
total(23, 34,
22, 21)
Output
100
Triple Quotes for Strings
If we are working with docstrings or multiline strings, we can use triple quotes (single ”’ or double “””).
Python3
text = """GeeksforGeeks Interactive Live and Self-Paced
Courses to help you enhance your programming.
Practice problems and learn with live and online
recorded classes with GFG courses. Offline Programs."""
print(text)
Output
GeeksforGeeks Interactive Live and Self-Paced
Courses to help you enhance your programming.
Practice problems and learn with live and online
recorded classes with GFG courses. Offline Programs.
Quotation in Python
In Python, strings can be enclosed using single (‘), double (“), or triple (”’ or “””) quotes. Single and double quotes are interchangeable for defining simple strings, while triple quotes allow for the creation of multiline strings. That we have used in above example. The choice of quotation type can simplify inserting one type of quote within a string without the need for escaping, for example, using double quotes to enclose a string that contains a single quote. Below is the example of using single and double quotes.
Python3
# Embedded single quote inside double.
text1 = "He said, 'I learned Python from GeeksforGeeks'"
# Embedded double quote inside single.
text2 = 'He said, "I have created a project using Python"'print(text1)
print(text2)
Output
He said, 'I learned Python from GeeksforGeeks'
He said, "I have created a project using Python"
Continuation of Statements in Python
In Python, statements are typically written on a single line. However, there are scenarios where writing a statement on multiple lines can improve readability or is required due to the length of the statement. This continuation of statements over multiple lines is supported in Python in various ways:
Implicit Continuation
Python implicitly supports line continuation within parentheses (), square brackets [], and curly braces {}. This is often used in defining multi-line lists, tuples, dictionaries, or function arguments.
Python3
# Line continuation within square brackets '[]'
numbers = [
1, 2, 3,
4, 5, 6,
7, 8, 9
]
# Line continuation within parentheses '()'
result = max(
10, 20,
30, 40
)# Line continuation within curly braces '{}'
dictionary = {
"name": "Alice",
"age": 25,
"address": "123 Wonderland"
}print(numbers)
print(result)
print(dictionary)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
40
{'name': 'Alice', 'age': 25, 'address': '123 Wonderland'}
Explicit Continuation
If you’re not inside any of the above constructs, you can use the backslash ‘\’ to indicate that a statement should continue on the next line. This is known as explicit line continuation.
Python3
# Explicit continuation
s = "GFG is computer science portal " \
"that is used by geeks."
print(s)
Output
GFG is computer science portal that that is used by geeks.
Note: Using a backslash does have some pitfalls, such as if there’s a space after the backslash, it will result in a syntax error.
Strings
Strings can be continued over multiple lines using triple quotes (”’ or “””). Additionally, if two string literals are adjacent to each other, Python will automatically concatenate them.
Python3
text = '''A Geek can help other
Geek by writing article on GFG'''
message = "Hello, " "Geeks!"print(text)
print(message)
Output
A Geek can help other
Geek by writing article on GFG
Hello, Geeks!
String Literals in Python
String literals in Python are sequences of characters used to represent textual data. Here’s a detailed look at string literals in Python. String literals can be enclosed in single quotes (‘), double quotes (“), or triple quotes (”’ or “””).
Python3
string1 = 'Hello, Geeks'
string2 = "Namaste, Geeks"
multi_line_string = '''Ram learned Python
by reading tutorial on
GeeksforGeeks'''print(string1)
print(string2)
print(multi_line_string)
Output
Hello, Geeks
Namaste, Geeks
Ram learned Python
by reading tutorial on
GeeksforGeeks
Command Line Arguments
In Python, command-line arguments are used to provide inputs to a script at runtime from the command line. In other words, command line arguments are the arguments that are given after the name of program in the command line shell of operating system. Using Python we can deal with these type of argument in various ways. Below are the most common ways:
Example: In this example we write the program to sum up all the numbers provided in command line. Firstly we import sys module. After that we checks if there are any numbers passed as arguments. Iterates over the command-line arguments, skipping the script name i.e. “sys.argv[0]” and then converts each argument to a float and then add them. We have used try-except block to handle the “Value Error”.
Python3
import sys
# Check if at least one number is provided
if len(sys .argv) < 2:
print("Please provide numbers as arguments to sum.")
sys .exit(1) # Exit with an error status codetry:
# Convert arguments to floats and sum them
total = sum(map(float, sys .argv[1:]))
print(f"Sum: {total}")
except Value Error:
print("All arguments must be valid numbers.")
Output
Please provide numbers as arguments to sum.
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of these classes. The following are the standard or built-in data types in Python:
- Numeric
- Sequence Type
- Boolean
- Set
- Dictionary
- Binary Types
What is Python Data Types?
To define the values of various data types of Python and check their data types we use the type() function. Consider the following examples.
This code assigns variable ‘x’ different values of various Python data types. It covers string, integer, float, complex, list, tuple, range, dictionary, set, frozenset, boolean, bytes, bytearray, memory view, and the special value ‘None’ successively. Each assignment replaces the previous value, making ‘x’ take on the data type and value of the most recent assignment.
1. Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A numeric value can be an integer, a floating number, or even a complex number. These values are defined as Python int, Python float, and Python complex classes in Python.
- Integers — This value is represented by int class. It contains positive or negative whole numbers (without fractions or decimals). In Python, there is no limit to how long an integer value can be.
- Float — This value is represented by the float class. It is a real number with a floating-point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation.
- Complex Numbers — A complex number is represented by a complex class. It is specified as (real part) + (imaginary part)j. For example — 2+3j
Note — type() function is used to determine the type of Python data type.
Example: This code demonstrates how to determine the data type of variables in Python using the type() function. It prints the data types of three variables: a (integer), b (float), and c (complex). The output shows the respective data type Python for each variable.
. Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or different Python data types. Sequences allow storing of multiple values in an organized and efficient fashion. There are several sequence data types of Python:
String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote, or triple-quote. In Python, there is no character data type Python, a character is a string of length one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes, double quotes, or even triple quotes.
Example: This Python code showcases various string creation methods. It uses single quotes, double quotes, and triple quotes to create strings with different content and includes a multiline string. The code also demonstrates printing the strings and checking their data types.
List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very flexible as the items in a list do not need to be of the same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square brackets[].
Example: This Python code demonstrates list creation and manipulation. It starts with an empty list and prints it. It creates a list containing a single string element and prints it. It creates a list with multiple string elements and prints selected elements from the list. It creates a multi-dimensional list (a list of lists) and prints it. The code showcases various ways to work with lists, including single and multi-dimensional lists.
Python3
List = []
Tuple Data Type
Just like a list, a tuple is also an ordered collection of Python objects. The only difference between a tuple and a list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is represented by a tuple class.
Creating a Tuple in Python
In Python Data Types, tuples are created by placing a sequence of values separated by a ‘comma’ with or without the use of parentheses for grouping the data sequence. Tuples can contain any number of elements and of any datatype (like strings, integers, lists, etc.). Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
Example: This Python code demonstrates different methods of creating and working with tuples. It starts with an empty tuple and prints it. It creates a tuple containing string elements and prints it. It converts a list into a tuple and prints the result. It creates a tuple from a string using the tuple() function. It forms a tuple with nested tuples and displays the result.
3. Boolean Data Type in Python
Python Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). However non-Boolean objects can be evaluated in a Boolean context as well and determined to be true or false. It is denoted by the class bool.
Note — True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.
Example: The first two lines will print the type of the boolean values True and False, which is <class ‘bool’>. The third line will cause an error, because true is not a valid keyword in Python. Python is case-sensitive, which means it distinguishes between uppercase and lowercase letters. You need to capitalize the first letter of true to make it a boolean value.
Python3
print(type(True))
4. Set Data Type in Python
In Python Data Types, a Set is an unordered collection of data types that is iterable, mutable, and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set.
Example: The code is an example of how to create sets using different types of values, such as strings, lists, and mixed values
5. Dictionary Data Type in Python
A dictionary in Python is an unordered collection of data values, used to store data values like a map, unlike other Python Data Types that hold only a single value as an element, a Dictionary holds a key: value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon : , whereas each key is separated by a ‘comma’.
Create a Dictionary in Python
In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable. The dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing it in curly braces{}. Note — Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly.
Example: This code creates and prints a variety of dictionaries. The first dictionary is empty. The second dictionary has integer keys and string values. The third dictionary has mixed keys, with one string key and one integer key. The fourth dictionary is created using the dict() function, and the fifth dictionary is created using the [(key, value)] syntax