0% found this document useful (0 votes)
8 views

Python Keywords and Syntax Overview

Python basics

Uploaded by

nikambhavesh9147
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python Keywords and Syntax Overview

Python basics

Uploaded by

nikambhavesh9147
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Python_Keywords_and_Syntax_Overview

November 15, 2024

1 Keywords in Python
Here are the key points related to keywords in Python:
Definition: Keywords in Python are reserved words that cannot be used as ordinary identifiers.
They are used to define the syntax and structure of the Python language.
Immutability: Keywords are immutable. This means their meaning and definition can't be altered.
Case Sensitivity: Keywords are case-sensitive. For example, True is a valid keyword, but true is
not.
Total Number: As of Python 3.9, there are 35 keywords.
List of Keywords: The complete list of Python keywords are False, None, True, and, as, assert,
async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import,
in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield.
Special Keywords: async and await are used for handling asynchronous processing, and they became
keywords in Python 3.7.
Usage: Each keyword has a specific meaning and usage in Python programming. For instance, def
is used for defining functions, if is used for making conditional statements, for and while are used
for loops, class is used for defining a class, and so on.
Identifying Keywords: You can get the list of all keywords in Python by using the following code:

[65]: # instal package "keyword" to check how many keywords are there
# pip install keyword

# load package
import keyword

# display all keywords


print(keyword.kwlist)

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',


'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

1
[66]: # To check current working directory
%pwd

[66]: 'D:\\Data Science material\\basic python'

[67]: none = 10

[68]: # Incorrect use of keywords as variable names

class = 10 # 'class' is a reserved keyword


return = 5 # 'return' is a reserved keyword
if = "hello" # 'if' is a reserved keyword
else = 3.14 # 'else' is a reserved keyword

print(class, return, if, else)

Cell In[68], line 3


class = 10 # 'class' is a reserved keyword
^
SyntaxError: invalid syntax

[ ]: # Correct use of variable names

class_number = 10
return_value = 5
if_string = "hello"
else_number = 3.14

print(class_number, return_value, if_string, else_number)

2 Identifiers
Here are the key points related to identifiers in Python:
Definition: An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Syntax: Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore (_).
No digits: They must start with a letter or the underscore character, but not with a digit.
Case-Sensitive: Identifiers in Python are case-sensitive. For example, myVariable and myvariable
are two different identifiers in Python.
No Special Characters: Identifiers cannot have special characters such as !, @, #, $, %, etc.

2
Reserved Words: Python keywords cannot be used as identifiers. Words like for, while, break,
continue, in, elif, else, import, from, pass, return, etc. are reserved words. You can view all
keywords in your current version by typing help(”keywords”) in the Python interpreter.
Unlimited Length: Python does not put any restriction on the length of the identifier. However,
it's recommended to keep it within a reasonable size, to maintain readability and simplicity in the
code.
Private Identifiers: In Python, if the identifier starts with a single underscore, it indicates that it is
a non-public part of the class, module, or function. This is just a convention and Python doesn't
enforce it. If it starts with two underscores, it's a strongly private identifier. If the identifier also
ends with two trailing underscores, the identifier is a language-defined special name.
Non-ASCII Identifiers: Python 3 allows the use of non-ASCII letters in the identifiers. This means
you can use letters like é, ñ, ö, �, etc. in your identifiers if you wish.

[ ]: num1 = 5
_value = 10
text_string = 'Hello, Everyone!'
print(num1, _value, text_string)

[ ]: _1a = 10
_1b = 20
c = _1a + _1b
print(c)

[ ]: my_var = 'lowercase'
MY_VAR = 'UPPERCASE'
print(my_var, MY_VAR)

3 Comments
Here are some key points about comments in Python:
Definition: A comment in Python is a piece of text in your code that is not executed. It's typi-
cally used to explain what the code is doing or leave notes for developers who will be reading or
maintaining the code.
Single-Line Comments: Python uses the hash symbol (#) to denote a comment. Any text following
the # on the same line will be ignored by the Python interpreter.
Multi-Line Comments: Python does not have a specific syntax for multi-line comments. Developers
typically use a single # for each line to create multi-line comments. Alternatively, multi-line strings
using triple quotes (''' or ”””) can also be used as multi-line comments because any string not
assigned to a variable is ignored by Python.
Docstrings or documentation strings: Docstrings are a type of comment used to explain the purpose
of a function or a class. They are created using triple quotes and are placed immediately after the
definition of a function or a class. Docstrings can span multiple lines and are accessible at runtime
using the .__doc__ attribute.

3
[ ]: # This is a comment in Python
x = 5 # This is an inline comment

[ ]: # This is a multi-line comment


# We are adding two numbers a and b.
a = 5
b = 3
c = a + b
print(c)

[ ]: # Docstring Example
def add_numbers(a, b):
"""
This function adds two numbers and returns the result.

Parameters:
a (int): The first number
b (int): The second number

Returns:
int: The sum of the two numbers
"""
return a + b

[ ]: # You can access this docstring using the .__doc__ attribute.


# Here's how:
print(add_numbers.__doc__)

[ ]: # Incorrect use of identifiers

1variable = 10 # Identifier starts with a digit


$second = 20 # Identifier contains special character
third variable = 30 # Identifier contains a space
for = 40 # Identifier is a reserved keyword

print(1variable, $second, third variable, for)

[ ]: # Correct use of identifiers

variable1 = 10
second_variable = 20
third_variable = 30
variable_for = 40

print(variable1, second_variable, third_variable, variable_for)

4
4 Indentation
Indentation
Importance: In Python, indentation is not just for readability. It's a part of the syntax and is used
to indicate a block of code.
Space Usage: Python uses indentation to define the scope of loops, functions, classes, etc. The
standard practice is to use four spaces for each level of indentation, but you can use any number
of spaces, as long as the indentation is consistent within a block of code.
Colon: Usually, a colon (:) at the end of the line is followed by an indented block of code. This is
common with structures like if, for, while, def, class, etc.

[ ]: def say_hello():
print("Hello, Eeveryone!")

[69]: # Incorrect use of indentation

if True:
print("This is True!") # Error: expected an indented block

for i in range(3):
print(i) # Error: expected an indented block

def hello():
print("Hello, World!") # Error: expected an indented block

while False:
print("This won't print") # Error: expected an indented block

Cell In[69], line 4


print("This is True!") # Error: expected an indented block
^
IndentationError: expected an indented block after 'if' statement on line 3

[ ]: # Correct use of indentation

if True:
print("This is True!")

for i in range(3):
print(i)

def hello():
print("Hello, World!")

5
while False:
print("This won't print")

5 Statements
Definition: A statement in Python is a logical instruction that the Python interpreter can read and
execute. In general, a statement performs some action or action.
Types: Python includes several types of statements including assignment statements, conditional
statements, looping statements, etc.

[ ]: # Conditional Statement
x = 2
if x > 0:
print("Positive number")

[ ]: #
for i in range(5):
print(i)

Multi-Line Statements: In Python, end of a statement is marked by a newline character. But we


can make a statement extend over multiple lines with the line continuation character (</code>),
or within parentheses (), brackets [], braces {}, or strings. You can also write multiple statements
on a single line using semicolons (;)

[ ]: # Multi-Line Statements
# Using line continuation character
s = 1 + 2 + 3 + \
4 + 5

# Using parentheses
s = (1 + 2 + 3 +
4 + 5)

# Multiple Statements on a Single Line


x = 5; y = 10; print(x + y)

6 Variables
Definition: In Python, a variable is a named location used to store data in memory.
Declaration and Assignment: Variables are declared by writing the variable name and assigning it
a value using the equals sign (=). For example:

[ ]: a = 5
st = "hello"

Dynamic Typing: Python is dynamically typed, which means that you don't have to declare the
type of a variable when you create one. You can even change the type of data held by a variable

6
at any time.

[ ]: x = 5 # x is an integer
x = "Hello" # now x is a string

7 Data types in Python


Integers: Integers are whole numbers, without a fractional component. They can be positive or
negative.

[ ]: x = 10
y = -3

Floats: Floats represent real numbers and are written with a decimal point.

[ ]: x = 10.0
y = -3.14

Strings: Strings in Python are sequences of character data. They are created by enclosing characters
in quotes.

[ ]: s = "Hello, World!"
print(s)

———————————————————————————–
Lists
Definition: A list in Python is an ordered collection (also known as a sequence) of items. Lists are
similar to arrays in other languages, but with additional functionality.
Mutable: Lists are mutable, which means their elements can be changed (added, modified, or
deleted) after they are created.
Creation: A list is created by placing items (elements) inside square brackets [], separated by
commas.

[ ]: fruits = ["apple", "banana", "cherry"]


print(fruits)

Heterogeneous Elements: A list can contain elements of different types: integers, floats, strings,
and even other lists or tuples.

[ ]: mixed_list = [1, "Bhavesh", 3.14, [5, 6, 7]]


print(mixed_list)

Indexing and Slicing: Lists support indexing and slicing to access and modify their elements.
Python list indices start at 0.

[ ]: my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 1
print(my_list[1:3]) # [2, 3]

7
my_list[0] = 10 # change the first element to 10
print(my_list)

———————————————————————————–
Tuples
Definition: A tuple in Python is similar to a list. It’s an ordered collection of items.
Immutable: The major difference from lists is that tuples are immutable, which means their ele-
ments cannot be changed (no addition, modification, or deletion) after they are created.
Creation: A tuple is created by placing items (elements) inside parentheses (), separated by commas.

[ ]: my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)

Heterogeneous Elements: Like lists, a tuple can also contain elements of different types: integers,
floats, strings, and even other tuples or lists.

[ ]: my_tuple = (1, 2, 3, "harshal", [5, 6, 7])


print(my_tuple)

Indexing and Slicing: Tuples also support indexing and slicing, like lists, but you cannot modify
their elements.

[70]: my_tuple = (1, 2, 3, 4, 5)


print(my_tuple[0]) # 1
print(my_tuple[1:3]) # (2, 3)

1
(2, 3)
———————————————————————————–
Dictionaries
Definition: A dictionary in Python is an unordered collection of items. Each item stored in a
dictionary has a key and value, making it a key-value pair.
Mutable: Dictionaries are mutable, which means you can change their elements. You can add,
modify, or delete key-value pairs from a dictionary.
Creation: A dictionary is created by placing items (key-value pairs) inside curly braces {}, separated
by commas. Each item is a pair made up of a key and a value, separated by a colon :.

[71]: person = {"name": "Bhavesh", "age": 19}


print(person)

{'name': 'Bhavesh', 'age': 19}


Heterogeneous Elements: Keys and values in a dictionary can be of any type. Values can be
heterogeneous, but keys should be of an immutable type (like string, number, or tuple).

8
[72]: my_dict = {1: "Harshal", "age": 19, (1, 3): [4, 5, 3]}
print(my_dict)

{1: 'Harshal', 'age': 19, (1, 3): [4, 5, 3]}


Unique Keys: Each key in a dictionary should be unique. If a dictionary is created with duplicate
keys, the last assignment will overwrite the previous ones.

[73]: my_dict = {"name": "Bhavesh", "name": "Harshal"}


print(my_dict) # {'name': 'Bob'}

{'name': 'Harshal'}
Accessing Values: You can access a value in a dictionary by providing the corresponding key inside
square brackets [].

[74]: my_dict = {"name": "Bhavesh", "age": 19}


print(my_dict["name"]) # harshal

Bhavesh
Updating Values: You can update the value for a particular key by using the assignment operator
=.

[75]: my_dict = {"name": "Harshal", "age": 19}

my_dict["age"] = 20

print(my_dict) # {'name': 'harshal', 'age': 20}

{'name': 'Harshal', 'age': 20}


Adding and Deleting Key-Value Pairs: You can add a new key-value pair simply by assigning a
value to a new key. You can delete a key-value pair using the del keyword.

[76]: my_dict = {"name": "Bhavesh", "age": 19}

my_dict["city"] = "Nashik" # adding a new key-value pair

del my_dict["age"] # deleting a key-value pair

print(my_dict) # {'name': 'harshal', 'city': 'Nashik'}

{'name': 'Bhavesh', 'city': 'Nashik'}


———————————————————————————–
Sets: A set is an unordered collection of items where every element is unique.

[77]: colors = {"red", "green", "blue"}


print(colors)

{'blue', 'green', 'red'}

9
To determine the type of a variable, you can use the type() function:

[78]: x = 10
print(type(x))

<class 'int'>

[79]: # Incorrect use of data types

# Trying to add a string and an integer


result1 = "5" + 3 # Error: must be str, not int

# Trying to access a non-existing index of a list


my_list = [1, 2, 3]
result2 = my_list[5] # Error: list index out of range

# Trying to change a value in a tuple


my_tuple = (1, 2, 3)
my_tuple[1] = 4 # Error: 'tuple' object does not support item assignment

# Trying to access a non-existing key in a dictionary


my_dict = {"one": 1, "two": 2}
result4 = my_dict["three"] # Error: 'three' key not found

print(result1, result2, my_tuple, result4)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[79], line 4
1 # Incorrect use of data types
2
3 # Trying to add a string and an integer
----> 4 result1 = "5" + 3 # Error: must be str, not int
6 # Trying to access a non-existing index of a list
7 my_list = [1, 2, 3]

TypeError: can only concatenate str (not "int") to str

[80]: # Correct use of data types

# Convert the integer to a string before adding


result1 = "5" + str(3)

# Check if the index exists before accessing


result2 = my_list[2] if len(my_list) > 2 else None

# Tuples are immutable, create a new one if you need to change a value

10
my_tuple = (1, 4, 3)

# Check if the key exists before accessing


result4 = my_dict.get("three", None)

print(result1, result2, my_tuple, result4)

53 3 (1, 4, 3) None

8 Standard Input and Output


Standard Output
This is typically the terminal (or the console) where the program is run. When a program wants
to output some information, it will typically print to the standard output.
Python provides print() function to send data to standard output. Here is an example:

[81]: print("Welcome to Python World!!!")


# In this example, the string "Welcome to Python World!!!" is sent to the␣
↪standard output.

# Usually your terminal or console where you are running the program.

Welcome to Python World!!!


Standard Input:
This is usually the keyboard, but it can also be data coming from a file or another program.
Python provides the input() function to read data from standard input. Here is an example:

[82]: name = input("Enter your name: ")


print(f"Hello, {name}!!!!")

Enter your name: Bhavesh


Hello, Bhavesh!!!!
The f before the string in print(f”Hello, {name}!“) is used to denote a formatted string literal, often
called f-string for short.
F-strings were introduced in Python 3.6 as a new way to format strings. They are prefixed with ‘f’
and are followed by a string literal enclosed in quotes. The expression within the curly braces {}
gets evaluated and inserted into the string.
Redirecting Standard Output and Input:
Sometimes, you might want to save the output of a program to a file instead of printing it to the
terminal. This is called redirecting the standard output.
While this isn’t done with Python code, but with command line syntax, it is still a common and
important concept.
Similarly to redirecting output, you can also redirect the standard input from a file.

11
[ ]: python my_script.py > output.txt
#python my_script.py: Runs the Python script my_script.py.
#>: Redirects the output (stdout) to a specified file.
#output.txt: The file where the output will be saved. If the file doesn’t␣
↪already exist,

#it will be created. If it exists, its content will be overwritten.

[ ]: python my_script.py < input.txt


#< input.txt redirects the contents of input.txt to sys.stdin, so any input()
#or line-reading functions will read from input.txt instead of waiting for␣
↪keyboard input

[83]: # Take input from the user for two numbers


num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Calculate the sum of the two numbers


sum_of_numbers = num1 + num2

# Print the result


print(f"The sum of {num1} and {num2} is {sum_of_numbers}.")

Enter the first number: 10


Enter the second number: 6
The sum of 10 and 6 is 16.

[84]: Maths = 90
English = 85
print("Your marks in Maths:", Maths, "and in English:", English)

Your marks in Maths: 90 and in English: 85

[85]: Maths = 90
English = 85

print("Your marks in Maths:", Maths, "\nYour marks in English:", English)

Your marks in Maths: 90


Your marks in English: 85
program that prompts the user to enter two numbers. The program should then perform addi-
tion, subtraction, multiplication, and division on these numbers and display the results.

[87]: # Prompt the user to enter two numbers


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Perform arithmetic operations


sum = num1 + num2

12
difference = num1 - num2
product = num1 * num2

# Handle division carefully as division by zero is undefined


if num2 != 0:
quotient = num1 / num2
else:
quotient = "Undefined (division by zero)"

# Print the results


print(f"The sum of {num1} and {num2} is: {sum}")
print(f"The difference between {num1} and {num2} is: {difference}")
print(f"The product of {num1} and {num2} is: {product}")
print(f"The quotient of {num1} and {num2} is: {quotient}")

Enter the first number: 10


Enter the second number: 5.5
The sum of 10.0 and 5.5 is: 15.5
The difference between 10.0 and 5.5 is: 4.5
The product of 10.0 and 5.5 is: 55.0
The quotient of 10.0 and 5.5 is: 1.8181818181818181

9 Operators
Various Operators in Python are:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic Operators: Used to perform mathematical operations.

[88]: a = 10
b = 3

print(a + b) # Addition, Output: 13


print(a - b) # Subtraction, Output: 7
print(a * b) # Multiplication, Output: 30
print(a / b) # Division, Output: 3.3333333333333335
print(a // b) # Floor Division, Output: 3
print(a % b) # Modulus, Output: 1

13
print(a ** b) # Exponent, Output: 1000

13
7
30
3.3333333333333335
3
1
1000
Assignment Operators: Used to assign values to variables.
a = 10 # Assigns value 10 to a print(a)
a += 5 # Same as a = a + 5, Output: 15 print(a)
a -= 3 # Same as a = a - 3, Output: 12 print(a)
a = 2 # Same as a = a 2, Output: 24 print(a)
a /= 6 # Same as a = a / 6, Output: 4.0 print(a)
Comparison Operators: Used to compare two values.

[89]: a = 10
b = 20

print(a == b) # Equal to, Output: False


print(a != b) # Not equal to, Output: True
print(a > b) # Greater than, Output: False
print(a < b) # Less than, Output: True
print(a >= b) # Greater than or equal to, Output: False
print(a <= b) # Less than or equal to, Output: True

False
True
False
True
False
True
Logical Operators: Used to combine conditional statements.

[90]: a = True
b = False

print(a and b) # Logical AND, Output: False


print(a or b) # Logical OR, Output: True
print(not a) # Logical NOT, Output: False

False
True
False

14
Bitwise Operators: Used to perform bitwise calculations on integers.
AND Operator &: Compares each bit of the first operand with the corresponding bit of the second
operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the result bit is set
to 0.

[91]: a = 10 # in binary: 1010


b = 4 # in binary: 0100
result = a & b # result is 0 (in binary: 0000)
print(result)

0
OR Operator |: Compares each bit of the first operand with the corresponding bit of the second
operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the result bit is set
to 0.

[92]: a = 10 # in binary: 1010


b = 4 # in binary: 0100
result = a | b # result is 14 (in binary: 1110)
print(result)

14
NOT Operator ~: Inverts all the bits of the operand. Every 0 is changed to 1, and every 1 is
changed to 0.

[93]: a = 10 # in binary: 1010


result = ~a # result is -11 (in binary: -1011)
print(result)

-11
XOR Operator ^: Compares each bit of the first operand with the corresponding bit of the second
operand. If one of the bits is 1 (but not both), the corresponding result bit is set to 1. Otherwise,
the result bit is set to 0.

[94]: a = 10 # in binary: 1010


b = 4 # in binary: 0100
result = a ^ b # result is 14 (in binary: 1110)
print(result)

14
Right Shift Operator »: Shifts the bits of the number to the right by the number of bits specified.
Each shift to the right corresponds to dividing the number by 2.

[95]: a = 10 # in binary: 1010


result = a >> 2 # result is 2 (in binary: 0010)
print(result)

15
Left Shift Operator «: Shifts the bits of the number to the left by the number of bits specified.
Each shift to the left corresponds to multiplying the number by 2.

[96]: a = 10 # in binary: 1010


result = a << 2 # result is 40 (in binary: 101000)
print(result)

40
Remember, bitwise operations are only applicable to integers.
Membership Operators: Used to test whether a value or variable is found in a sequence (string,
list, tuple, set, and dictionary).

[97]: list = [1, 2, 3, 4, 5]


print(1 in list) # Output: True
print(6 not in list) # Output: True

True
True
Identity Operators: Used to compare the objects, not if they are equal, but if they are actually the
same object, with the same memory location.

[98]: a = 5
b = 5

solve few problems:

[99]: # Using Arithmetic Operators


num1 = 10
num2 = 5

add = num1 + num2


print("The addition of num1 and num2 is:", add)

sub = num1 - num2


print("The subtraction of num1 and num2 is:", sub)

mul = num1 * num2


print("The multiplication of num1 and num2 is:", mul)

The addition of num1 and num2 is: 15


The subtraction of num1 and num2 is: 5
The multiplication of num1 and num2 is: 50

[100]: # write this code using Assignment operators


# Using Assignment Operators
num1 = 10
num2 = 5

16
num1 += num2 # equivalent to num1 = num1 + num2
print("The addition of num1 and num2 is:", num1)

num1 = 10 # reset num1


num1 -= num2 # equivalent to num1 = num1 - num2
print("The subtraction of num1 and num2 is:", num1)

num1 = 10 # reset num1


num1 *= num2 # equivalent to num1 = num1 * num2
print("The multiplication of num1 and num2 is:", num1)

The addition of num1 and num2 is: 15


The subtraction of num1 and num2 is: 5
The multiplication of num1 and num2 is: 50

10 Control flow: if else elif


Conditional statements are used to execute or skip blocks of code based on certain conditions. The
if, elif, and else keywords are used to define these conditional statements.

[101]: age = 20
if age >= 18:
print("You are eligible to vote.")

You are eligible to vote.

[102]: age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

You are not eligible to vote.

[103]: score = 85
if score >= 90:
print("Grade is A")
elif score >= 80:
print("Grade is B")
elif score >= 70:
print("Grade is C")
else:
print("Grade is D")

Grade is B
Program for using “IF” to find 2nd largest number form 3 numbers.

17
[104]: # Program to find the second-largest number from three numbers

# Input the three numbers


#num1 = float(input("Enter the first number: "))
#num2 = float(input("Enter the second number: "))
#num3 = float(input("Enter the third number: "))

num1 = 10
num2 = 20
num3 = 30

# Compare the numbers to find the second-largest


if num1 >= num2 and num1 >= num3:
if num2 >= num3:
second_largest = num2
else:
second_largest = num3
elif num2 >= num1 and num2 >= num3:
if num1 >= num3:
second_largest = num1
else:
second_largest = num3
else:
if num1 >= num2:
second_largest = num1
else:
second_largest = num2

# Print the second-largest number


print("The second-largest number is:", second_largest)

The second-largest number is: 20

18

You might also like