0% found this document useful (0 votes)
3 views8 pages

Python Basics: Variables, Data Types, Operators

Uploaded by

yalluhavaldar2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

Python Basics: Variables, Data Types, Operators

Uploaded by

yalluhavaldar2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

#Proprietary content. ©Great Learning. All Rights Reserved.

Unauthorized use or distribution prohibited

#First Program
print("This is sparta!!!")

This is sparta!!!

#Variables
var1="John"
print(var1)

John

var1="Sam"
print(var1)

Sam

var1="Matt"
print(var1)

Matt

#Data-Type
a=10
type(a)

int

a=10.5
type(a)

float

a="sparta"
type(a)

str

a=True
type(a)

bool

a=3+4j
type(a)

complex

#Arithmetic Operators

a=10
b=20
print(a+b)

30

print(a-b)

-10

print(a*b)

200

print(a/b)

0.5

#Relational Operators

a=10
b=20

a>b

False

a<b

True

a==b

False

a!=b

True

#Logical Operators

a=True
b=False

a&b

False

b&a

False

b&b

False

a&a
True

a|b

True

b|a

True

a|a

True

b|b

False

#Strings

my_string="My name is John"

my_string[0]

'M'

my_string="My name is John"

my_string[-1]

'n'

my_string[0:4]

'My n'

len(my_string)

15

my_string.lower()

'my name is john'

my_string.upper()

'MY NAME IS JOHN'

my_string.replace('y','a')

'Ma name is John'

new_string = "hello hello world"

new_string.count("hello")
2

s1 = 'This is sparta!!!'
[Link]('sparta')

[Link]('b')

fruit = 'I like apples, mangoes, bananas'

[Link](',')

['I like apples', ' mangoes', ' bananas']

#Tuples in Python

tup1=(1,"a",True,2,"b",False)

tup1

----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
<ipython-input-17-afd04ff38ac4> in <module>
----> 1 tup1

NameError: name 'tup1' is not defined

tup1[0]

tup1[-1]

False

tup1=(1,"a",True,2,"b",False)
tup1[1:4]

('a', True, 2)

tup1[1:4]

('a', True, 2)

tup1[2]="hello"

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
<ipython-input-49-2fc16622751e> in <module>
----> 1 tup1[2]="hello"

TypeError: 'tuple' object does not support item assignment

tup1[6]=3+4j

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
<ipython-input-50-3b75c4b77e6a> in <module>
----> 1 tup1[6]=3+4j

TypeError: 'tuple' object does not support item assignment

min(tup1)

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
<ipython-input-52-ce68c930ff7f> in <module>
----> 1 min(tup1)

TypeError: '<' not supported between instances of 'str' and 'int'

tup1=(1,"a",True,2,"b",False)
len(tup1)

tup1 = (1,"a",True)
tup2 = (4,5,6)

tup2+tup1

(4, 5, 6, 1, 'a', True)

tup1 = ('sparta',300)
tup2 = (4,5,6)
tup1*3 + tup2

('sparta', 300, 'sparta', 300, 'sparta', 300, 4, 5, 6)

tup1=(1,2,3,4,5)
min(tup1)

tup1=(1,2,3,4,5)
max(tup1)
5

cmp(tup1,tup2)

----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
<ipython-input-34-e27d9faf1f7f> in <module>
----> 1 cmp(tup1,tup2)

NameError: name 'cmp' is not defined

#List in Python

l1=[1,"a",2,"b",3,"c"]

l1=[1,"a",2,"b",3,"c"]
l1[1]

'a'

l1=[1,"a",2,"b",3,"c"]
l1[2:5]

[2, 'b', 3]

l1=[1,"a",2,"b",3,"c"]
l1[0]=100
l1

[100, 'a', 2, 'b', 3, 'c']

l1=[1,"a",2,"b",3,"c"]
[Link]("Sparta")
l1

[1, 'a', 2, 'b', 3, 'c', 'Sparta']

l1

[100, 'a', 2, 'b', 3, 'c', True]

l1=[1,"a",2,"b",3,"c"]
[Link]()
l1

[1, 'a', 2, 'b', 3]

l1

[1, 'a', 2, 'b', 3]


l1=[1,"a",2,"b",3,"c"]
[Link](1,"Sparta")
l1

[1, 'Sparta', 'a', 2, 'b', 3, 'c']

l1 = ["mango","banana","guava","apple"]
[Link]()
l1

['apple', 'banana', 'guava', 'mango']

l1 = [1,2,3]
l2 = ["a","b","c"]
l1+l2

[1, 2, 3, 'a', 'b', 'c']

l1 = [1,"a",True]
l1*3

[1, 'a', True, 1, 'a', True, 1, 'a', True]

#Dictionary in Python

fruit={"Apple":10,"Orange":20,"Banana":30,"Guava":40}

fruit={"Apple":10,"Orange":20,"Banana":30,"Guava":40}
[Link]()

dict_keys(['Apple', 'Orange', 'Banana', 'Guava'])

fruit={"Apple":10,"Orange":20,"Banana":30,"Guava":40}
[Link]()

dict_values([10, 20, 30, 40])

fruit["Apple"]

10

fruit={"Apple":10,"Orange":20,"Banana":30,"Guava":40}
fruit["Mango"]=50
fruit

{'Apple': 10, 'Orange': 20, 'Banana': 30, 'Guava': 40, 'Mango': 50}

fruit={"Apple":10,"Orange":20,"Banana":30,"Guava":40,"Mango":50}
fruit["Apple"]=100
fruit

{'Apple': 100, 'Orange': 20, 'Banana': 30, 'Guava': 40, 'Mango': 50}
fruit1={"Apple":10,"Orange":20}
fruit2={"Banana":30,"Guava":40}

[Link](fruit2)

fruit1

{'Apple': 10, 'Orange': 20, 'Banana': 30, 'Guava': 40}

fruit={"Apple":10,"Orange":20,"Banana":30,"Guava":40}
[Link]("Orange")
fruit

{'Apple': 10, 'Banana': 30, 'Guava': 40}

#Set in Python

s1={1,"a",True,2,"b",False}
s1

{1, 2, False, 'a', 'b'}

s1={1,"a",True,2,"b",False}
[Link]("Hello")
s1

{1, 2, False, 'Hello', 'a', 'b'}

s1={1,"a",True,2,"b",False}
[Link]([10,20,30])
s1

{1, 10, 2, 20, 30, False, 'a', 'b'}

s1={1,"a",True,2,"b",False}
[Link]("b")
s1

{1, 2, False, 'a'}

s1 = {1,2,3,4,5,6}
s2 = {5,6,7,8,9}

[Link](s2)

{5, 6}

Common questions

Powered by AI

Python dictionaries provide a mapping of keys to values, allowing efficient data manipulation through key-based access. Insertion and updates are performed by assigning a value to a key or using methods like .update() to merge another dictionary . Concurrently, they maintain unique keys, making them suitable for representing complex associations. Sets, by contrast, are collections of unordered, unique items that primarily focus on membership tests, intersection, and union operations. They support addition of items via .add(), meaning new entries cannot specify a key-value relationship but rather encompass single item values . The primary distinction is that dictionaries are key-driven data structures suitable for organizing data in a structured way, while sets excel in managing groups of unique items with fast access.

In Python, the logical 'and' operator returns True only if both operands are True; otherwise, it returns False. For example, if a=True and b=False, the expression a and b results in False . On the other hand, the 'or' operator returns True if at least one of its operands is True. Using the same boolean values as before, the expression a or b evaluates to True . Understanding these operators is essential for making complex logical decisions in programming.

Cross-data manipulation between Python data structures allows the leveraging of different features to create efficient programs. For instance, sets can be derived from lists using the set() function to remove duplicates or achieve quick membership tests, as demonstrated when a list is updated using set methods such as .update(). Conversely, when a set should be ordered, it can be converted back to a list using list(). Python lists and sets can also be combined in operations like intersection, where a set method finds common elements between two sets . These integrations allow programs to dynamically adjust data representation formats to match specific requirements or optimize performance.

In Python, mutable data types are those that can have their elements modified after they're created. Examples include lists and dictionaries. Lists allow items to be added, removed, or changed, as seen with operations like append, pop, and insert . Immutable data types, such as tuples and strings, cannot be altered after creation. This means that operations that seem to modify them actually result in the creation of a new object. For instance, attempting to assign a new value to a specific index in a tuple results in a TypeError since tuples do not support item assignment . Understanding the difference is crucial for managing resources effectively in programs, as immutability can lead to predictable behavior and optimization of memory usage.

When manipulating tuples, developers must be aware of their immutable nature, which can lead to TypeErrors if attempts are made to alter their elements, such as assin tup1[2]='hello' . Another potential error arises from using operations that imply order or comparison between incompatible types, resulting in TypeErrors during functions such as min() which attempt comparisons in tuples containing mixed data types . To avoid such errors, developers should ensure tuples contain a consistent data type when comparisons are needed and resort to creating new tuples for changes rather than modifying existing ones.

Set operations such as union, intersection, and difference are essential in Python because they enable efficient manipulation and analysis of large data collections. Union combines elements from multiple sets, ensuring uniqueness, which is useful in merging datasets. Intersection finds common elements between sets, critical for identifying overlaps or commonalities . Difference identifies the mismatch between datasets, allowing analysts to exclude subsets of data. These operations are pivotal in data analysis tasks, offering fast membership checks, de-duplication, and cross-referencing capabilities, thereby optimizing data processing and pattern identification.

Lists in Python are mutable, ordered collections that allow changes to their elements, such as adding, deleting, or altering items. Common operations include append(), pop(), and insert(), which modify the list in-place . Tuples, in contrast, are immutable and ordered collections, disallowing any modifications to their elements once defined. This fundamental difference means that lists offer greater flexibility, whereas tuples provide optimization in cases where constant sets of values are used . Additionally, tuples generally perform faster due to their immutability, making them suitable for use as dictionary keys or where an immutable sequence is required.

Arithmetic operators in Python, such as addition (+), subtraction (-), multiplication (*), and division (/), are designed to handle numeric types. Python, however, does not apply these operators to incompatible types like strings and lists directly without explicit conversion . A key pitfall is the division operator, as it results in a float by default when used with integers (e.g., 10/20 results in 0.5), which can be undesirable if integers are expected . Developers need to ensure appropriate type checking and conversions to avoid unexpected behavior and runtime errors, especially when dealing with mixed data types.

Data type conversions in Python allow developers to switch between different data or number formats to suit specific operations. Integer-to-float conversions can happen implicitly in arithmetic operations (e.g., division), or explicitly using functions like float(), which converts integers to floating-point numbers . Similarly, converting numbers to strings with str() allows numeric data to be concatenated with string data in operations like string formatting or file writing. These conversions are essential when interfacing between systems handling different data types or ensuring proper formatting and precision in computations or textual representations.

Python string operations offer a range of functionalities for text transformation and data extraction. Methods like .lower(), .upper(), and .replace() facilitate transforming the case and content of strings . The method .find() helps in extracting data by finding the position of a substring, while slicing (e.g., my_string[0:4]) enables selective extraction of string parts . These operations are fundamental in text processing tasks, allowing for efficient manipulation and formatting of text data.

You might also like