Skip to content

Python

Taking input in Python

By default, it returns the user input in form of a string. If we want to convert it into other type we should num = type(input("Enter a ...: "))​ for example num = int(input("Enter a number: "))

Also we can name = str(3);

Example

name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")

Output

# Multiple Variables
s = "Alice"
age = 25
city = "New York"
print(s, age, city)

Dynamic Typing, assignment

Python variables are dynamically typed, meaning the same variable can hold different types of values during execution.

x = 10
x = "Now a string"
x, y, z = 1, 2.5, "Python"
print(x, y, z)

Practical Examples

1. Swapping Two Variables

Using multiple assignments, we can swap the values of two variables without needing a temporary variable.

a, b = 5, 10
a, b = b, a
print(a, b)

Output

10 5

2. Counting Characters in a String

Assign the results of multiple operations on a string to variables in one line.

word = "Python"
length = len(word)
print("Length of the word:", length)

Output

Length of the word: 6

Operators

Arithmetic operators

# Variables
a = 15
b = 4

# Addition
print("Addition:", a + b)  

# Subtraction
print("Subtraction:", a - b) 

# Multiplication
print("Multiplication:", a * b)  

# Division
print("Division:", a / b) 

# Floor Division
print("Floor Division:", a // b)  

# Modulus
print("Modulus:", a % b) 

# Exponentiation
print("Exponentiation:", a ** b)

"""
Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625
"""

Logic operators

a = True
b = False
print(a and b)
print(a or b)
print(not a)

"""
Output
False
True
False
"""

Membership Operators in Python

In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.

x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
    print("x is NOT present in given list")
else:
    print("x is present in given list")

if (y in list):
    print("y is present in given list")
else:
    print("y is NOT present in given list")

"""
Output
x is NOT present in given list
y is present in given list
"""

Ternary Operator in Python

[on_true] if [expression] else [on_false]

a, b = 10, 20
min = a if a < b else b

print(min)

"""
Output
10
"""

Operator Precedence in Python

expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0

if name == "Alex" or name == "John" and age >= 2:
    print("Hello! Welcome.")
else:
    print("Good Bye!!")

"""
output
610
Hello! Welcome.
"""

Keyword

Category Keywords
Value Keywords True, False, None
Operator Keywords and, or, not, in, is
Control Flow Keywords if, else, elif, for, while, break, continue, pass, try, except, finally, raise, assert
Function and Class def, return, lambda, yield, class
Context Management with, as
Import and Module import, from, as
Scope and Namespace global, nonlocal
Async Programming async, await
  • in keyword (membership operator) - Check if a value exists in a sequence (like a list, tuple, or string). It returns True if value is found.
  • is keyword - Check if two variables point to the same object in memory. It returns True if the objects are identical.
  • pass keyword: pass is the null statement in python. Nothing happens when this is encountered

Exception Handling Keywords

a, b = 4, 0


try:
    k = a // b  # Attempt integer division (4 // 0)
    print(k)

# This block catches the ZeroDivisionError
except ZeroDivisionError: 
    print("Can't divide by zero")

finally:
    # This block is always executed regardless of the exception
    print('This is always executed')



# Will raise an AssertionError because b == 0
assert b != 0, "Divide by 0 error"  

# Division is attempted but will not reach due to assert
print(a / b)  

# Raise a TypeError if the strings are different
temp = "geeks for geeks"
if temp != "geeks":
    raise TypeError("Both the strings are different.")

Structure Keywords : def

def​ keyword - Defines a function named fun​ using the def​ keyword. When the function is called using fun()​.

def fun():
    print("Inside Function")

fun()

Output

Inside Function

Data type

String Data Type

s = 'Welcome to the Geeks World'
print(s)

# check data type 
print(type(s))

# access string with index
print(s[1])
print(s[2])
print(s[-1])

"""
Output
Welcome to the Geeks World
<class 'str'>
e
l
d
"""

List Data Type

#Creating a Empty list in Python 
a = []

# list with int values
a = [1, 2, 3]
print(a)

# list with mixed int and string
b = ["Geeks", "For", "Geeks", 4, 5]
print(b)

"""
output
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]
"""

Access list element

a = ["Geeks", "For", "Geeks"]
print("Accessing element from the list")
print(a[0])
print(a[2])

print("Accessing element using negative indexing")
print(a[-1])
print(a[-3])

"""
output
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
"""

Tuple Data Type

# initiate empty tuple
tup1 = ()

tup2 = ('Geeks', 'For')
print("\nTuple with the use of String: ", t2)

"""
Output
Tuple with the use of String:  ('Geeks', 'For')
"""

Access element

tup1 = tuple([1, 2, 3, 4, 5])

# access tuple items
print(tup1[0])
print(tup1[-1])
print(tup1[-3])

"""
Output
1
5
3
"""

Set Data Type

# initializing empty set
s1 = set()

s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)

s2 = set(["Geeks", "For", "Geeks"])
print("Set with the use of List: ", s2)

"""
Output
Set with the use of String:  {'s', 'o', 'F', 'G', 'e', 'k', 'r'}
Set with the use of List:  {'Geeks', 'For'}
"""

Access element

set1 = set(["Geeks", "For", "Geeks"])
print(set1)

# loop through set
for i in set1:
    print(i, end=" ")

# check if item exist in set    
print("Geeks" in set1)

"""
Output
{'Geeks', 'For'}
Geeks For 
True
"""

Dictionary Data Type

# initialize empty dictionary
d = {}


d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d)

# creating dictionary using dict() constructor
d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(d1)

"""
Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
"""

Accessing Key-value in Dictionary

In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets. Using get() method we can access the dictionary elements

d = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# Accessing an element using key
print(d['name'])

# Accessing a element using get
print(d.get(3))

"""
Output
For
Geeks
"""

Q1. Code to implement basic list operations

fruits = ["apple", "banana", "orange"]
print(fruits)
fruits.append("grape")
print(fruits)
fruits.remove("orange")
print(fruits)

"""
Output
['apple', 'banana', 'orange']
['apple', 'banana', 'orange', 'grape']
['apple', 'banana', 'grape']
"""

Code to implement basic tuple operation

coordinates = (3, 5)
print(coordinates)
print("X-coordinate:", coordinates[0])
print("Y-coordinate:", coordinates[1])

"""
Output
(3, 5)
X-coordinate: 3
Y-coordinate: 5
"""

if-else statement

"""
In python the if-else statement syntax is the following
"""
if condition:
    statement
elif condition:
    statement
else:
    statement

For example

import sys

x = 3
if len(sys.argv) > 1:
    if not sys.argv[1].isdigit():
        raise Exception("Not an integer " + sys.argv[1])
    x = int(sys.argv[1])

if x == 1:
    print("If statement 1")
    print("If statement 2")
elif x == 2:
    print("Else if statement")
else:
    print("Else statement")
print("Not an if statement")

‍```bash
stein@Stein-Surface:~/.../tutorial8$ python3 gramar-basic.py Hello
Traceback (most recent call last):
  File "/home/stein/GTIIIT/GTIIITsystemsProgrammingSpring25/tutorials/tutorial8/gramar-basic.py", line 24, in <module>
    raise Exception("Not an integer " + sys.argv[1])
Exception: Not an integer Hello
stein@Stein-Surface:~/.../tutorial8$

The same for while loop

import sys

x = 3
if len(sys.argv) > 1:
    if not sys.argv[1].isdigit(): 注意这里是not 不是!, !只用在=前面在python
        raise Exception("Not an integer " + sys.argv[1])
    x = int(sys.argv[1])

while x >= 0:
    print(x)
    x = x - 1

For loop

In java
for(int i = 0; i < 8; i++) {

}

But in python the syntax is this way
for i in range(init, final_value + 1, increment) 左闭右开
for i in range(3) 这个是指0,1,2 不包含三 默认increment为一 起始值为0

For example

import sys

x = 3
if len(sys.argv) > 1:
    if not sys.argv[1].isdigit():
        raise Exception("Not an integer " + sys.argv[1])
    x = int(sys.argv[1])
for i in range(x, -1, -1):
    print(i)
import sys

letter_count: list[(str, int)] = [('a', 1), ('b', 2), ('c', 3)]
count = 0
for _ in letter_count: # _ is a placeholder, refer to anything in letter_count
    count += 1
print("You have {} tuples".format(count))

import sys
letter_count: list[(str, int)] = [('a', 1), ('b', 2), ('c', 0)]
for (letter, count) in letter_count:
    print("Letter {} was counted {} times".format(letter, count))

"""
Output
Letter a was counted 1 times
Letter b was counted 2 times
Letter c was counted 0 times
"""
import sys

letter_count: list[(str, int)] = [('a', 1), ('b', 2), ('c', 0)]

for (letter, _) in letter_count:
    print("I have a count for letter {}".format(letter))
‍```

‍```bash
stein@Stein-Surface:~/.../tutorial8$ python3 grammar-basic.py
I have a count for letter a
I have a count for letter b
I have a count for letter c
stein@Stein-Surface:~/.../tutorial8$

If we want to print a letter with a int, we should print("a" + str(3))

If we want to define our own str function in our class, we should def __str__(self)

Array

import sys
even_numbers = [x*2 for x in range(0, 21) if x % 2 == 0]
print(str(even_numbers))

‍```bash
stein@Stein-Surface:~/.../tutorial18$ python3 gramar-basic.py
[0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40]

Equal function

== equals content

is equal reference

import sys

x = str("Hell" + 'o')
y = str("Hel") + str("lo")

print(x)
print(y)
print(str(x == y))
print(str(x is y)) # we should only use this when checking the reference
# a useful way is `x is not none` to check whether it is null


‍```bash
stein@Stein-Surface:~/.../tutorial8$ python3 grammar-basic.py 3
Hello
Hello
True
False
stein@Stein-Surface:~/.../tutorial8$

Generic Types

First let's see what is enumerate

It's a python function that can be used to iterate and returns a tuple containing the index

Syntax: enumerate(iterable, start = 0)

Example

elements = ['a', 'b', 'c', 'd']
for index, element in enumerate(elements):
    print(f"Index: {index}, Element: {element}")

"""
Output
Index: 0, Element: a
Index: 1, Element: b
Index: 2, Element: c
Index: 3, Element: d
"""

Then if we want to create a generic type, then it's should like this

def process_numbers(numbers: list[int]) -> list[int]:
    return [number + 1 for number in numbers]

def process_elements(elements: list[T]) -> list[T]:
    # return elements at odd indices
    return [element for index, element in enumerate(elements) if index % 2 == 1]

def main() -> None:
    pass

if __name__ == "__main__":
    main()

But here T​ is not defined, thus we need to add

from typing import TypeVar
T = TypeVar("T")

Then we can do this

from typing import TypeVar

T = TypeVar("T")

def process_numbers(numbers: list[int]) -> list[int]:
    return [number + 1 for number in numbers]

def process_elements(elements: list[T]) -> list[T]:
    # return elements at odd indices
    return [element for index, element in enumerate(elements) if index % 2 == 1]

def main() -> None:
    my_list = [1, 2, 3, 4, 5]
    processed = process_elements(my_list)
    print(processed) # Outputs: [2, 4]

    my_str_list = ["a", "b", "c", "d", "e"]
    processed = process_elements(my_str_list)
    print(processed) # Outputs: ['b', 'd']

if __name__ == "__main__":
    main()

Python in Keyword

The in keyword in Python is a powerful operator used for membership testing and iteration. It helps determine whether an element exists within a given sequence, such as a list, tuple, string, set or dictionary.

Example:

s = "Geeks for geeks"

if "for" in s:
    print("found")
else:
    print("not found")

Output

found

Explanation: if "for" in s​ checks if the substring "for"​ exists in the string s​ using the in keyword, which performs a membership test.

Purpose of the in keyword

The in keyword in Python serves two primary purposes:

  • Membership Testing: To check if a value exists in a sequence such as a list, tuple, set, range, dictionary or string.
  • Iteration: To iterate through elements of a sequence in a for​ loop.

Example 1: in Keyword with if Statement

In this example, we will check if the string "php" is present in a list of programming languages. If it is, the program will print True.

a = ["php", "python", "java"]
if "php" in a:
    print(True)

Output

True

Explanation: The in operator checks if the string "php" is present in the list a. Since "php" exists in the list, the output will be True.

Example 2: in keyword in a for loop

Here, we will use the in keyword to loop through each character of the string "GeeksforGeeks" and print each character until the character 'f' is encountered, at which point the loop will stop.

s = "GeeksforGeeks"
for char in s:
    if char == 'f':
        break
    print(char)

Output

G
e
e
k
s

Explanation: The for loop iterates through each character in the string. The loop prints each character until it encounters 'f', at which point it breaks the loop and stops execution.

Example 3: in keyword with dictionaries

In this case, we will check if the key "Alice" exists in a dictionary of student names and marks. If the key is found, we will print Alice's marks.

d = {"Alice": 90, "Bob": 85}
if "Alice" in d:
    print("Alice's marks are:", d["Alice"])

Output

Alice's marks are: 90

Explanation: The in operator checks whether "Alice" is present as a key in dictionary d. Since "Alice" is a key, it prints her marks.

Example 4: in keyword with sets

We will check if the character 'e' is present in a set of vowels and print the result as True or False based on its presence.

v = {'a', 'e', 'i', 'o', 'u'}
print('e' in v)

Output

True

Explanation: The in operator checks if 'e' is present in the set v. Since 'e' exists in the set, the output will be True.