0% found this document useful (0 votes)
80 views18 pages

Python Variables and Data Types Guide

The document is an assignment by Kiran Ganesh Tayde, detailing various aspects of Python programming, including key features, data types, variable scopes, comments, literals, string formatting, and several programming exercises. It covers topics such as local and global variables, escape characters, and methods for string manipulation, along with example code snippets. The assignment was submitted on April 20, 2022.

Uploaded by

Gaikwad Nikhil
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)
80 views18 pages

Python Variables and Data Types Guide

The document is an assignment by Kiran Ganesh Tayde, detailing various aspects of Python programming, including key features, data types, variable scopes, comments, literals, string formatting, and several programming exercises. It covers topics such as local and global variables, escape characters, and methods for string manipulation, along with example code snippets. The assignment was submitted on April 20, 2022.

Uploaded by

Gaikwad Nikhil
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

Assignment - 1

Topics: Variables, String, int, float


Roll No. : 027

Name: Kiran Ganesh Tayde

Assignment date: 20/04/2022

1. What are the key features of Python? ¶

Ans:

1 1. Python is dynamically typed language (no need to assign type of variable)


2 2. Supports object oriented programming
3 4. Free & open source language.
4 5. Python is versatile language & widely use in every field like, AI, Web
development, ML, scientific calculations
5 7. It's a readable language like English.
6 8. It has pretty large standard library which contains different packages and
modules.
7 (ready to use)
8 9. extensible - can use code from other languages like C++ in your Python code.
9 10. embeddable - can embed your Python code in other languages like C++.
10 3. Can be used to create GUI.(Graphical User Interphase)
11 6. It's an integrated language.

2. What are the Data Types in Python?

Ans:

1 A data type, is a classification that specifies which type of value a variable


has and what type of mathematical, relational or logical operations can be
applied to it without causing an error
2
3 following are the different data types use in python:
4
5 1. Numeric data type : int , float, complex
6 2. Text data type : str
7 3. sequence data type : list, tuple, set, Frozenset
8 4. Boolean data type : Bool(True, False)
9 5. Mapping data type : Dict
10 6. Binary data type: bytes, bytearray, memoryview

3. What are local variables and global variables in Python?

Ans:
1 Local variables : variables which are defined inside the function, are called as
local variables
2 It can only be accessed inside the function.
3 Global variables: Variables which are defined outside the function are called as
global variable.
4 It can be accessed inside as well as outside the function.

In [7]:

1 #Example:
2
3 a=20 #global variable
4 def my_fun():
5 b=40 #local variable
6 print("value of b is:",b)
7 print("value of a is:",a)
8 my_fun()
9
10 print("value of a is:",a)

value of b is: 40
value of a is: 20
value of a is: 20

4. How do you write comments in python? And Why Comments are


important?

Ans:

1 You can use '#' and it will comment everything after '#'.
2 (ctrl + /) is a shortcut to comment multiple lines at the same time
3
4 Importance of comment:
5
6 Comments in Python are nothing but short descriptions along with the code to
increase its readability. A developer uses them to write his or her thought
process while writing the code. It explains the basic logic behind why a
particular line of code was written.

5. How to comment on multiple lines in python?

Ans:

1 We can use triple quotes (""" Text """) to comment on multiple lines in python

6. What do you mean by Python literals?

Ans:

1 Literals in Python is defined as the raw data assigned to variables or constants


while programming.
2 We mainly have five types of literals which includes string literals, numeric
literals, boolean literals, literal collections and a special literal None

7. What are different ways to assign value to variables?

Ans:

1 Method 1: by using assignment opearators.


2 following is the list of assignment operators , we can use to assign
values to the variable
3
4 = : a = 1
5 += : a += 1 : a = a + 1 >> increment operator
6 -= : a -= 1 : a = a - 1 >> decrement operator
7 *= : a *= 1 : a = a * 1 >> multiplication operator
8 /= : a /= 1 : a = a / 1 >> divisional operator
9 %= : a %= 1 : a = a % 1 >> modulus operator
10 //= : a //= 1 : a = a // 1 >> floor division operator
11 **= : a **= 1 : a = a ** 1 >> exponent operator
12 &= : a &= 5 : a = a & 5 >> and operator
13 |= : a |= 5 : a = a | 5 >> or operator
14 ^= : a ^= 5 : a = a ^ 5 >> exponent operator
15 >>= : a >>= 2 : a = a >>2 : right shift operator
16 <<= : a <<=2 : a = a <<2 : left shift operator
17
18 Method 2: by using conditional statements
19 we can use if else statements

In [52]:

1 #Example 1:
2
3 a ="python"
4 print("value of a is:",a)
5
6 #Example 2:
7
8 b=10 if 20>19 else 0
9 print("value of b is:",b)

value of a is: python


value of b is: 10

8. What are the Escape Characters in python?

Ans:

1 Escape character : We can use escape character, to insert characters that are
illegal in string without causing an errror
2 escape characters are , '\' '\t' '\n' 'r'
In [13]:

1 #Example:
2 # To Print a path without an errot
3
4 str="C:\\Users\\abc\\Desktop\\Python velocity notes" #by using backward slash
5 print("path is:",str)

path is: C:\Users\abc\Desktop\Python velocity notes

9. Which are the different ways to perform string formatting? Explain with
example.

Ans:

1 There are two diffrent ways to perform string formatting: 1. by using 'f-string '
2 2. by using .fomat()

In [3]:

1 # Example of 1st method:


2
3 a1= 10
4 b1= 25
5 Addition= a1+b1
6 print(f"Addition of {a1} and {b1} is:",Addition)
7
8 # Example of 2nd method:
9
10 a=100
11 b=800
12 Addition=a+b
13 print("Addition of {} and {} is :{}".format(a,b,Addition))

Addition of 10 and 25 is: 35


Addition of 100 and 800 is :900

10. Write a program to print every character of a string entered by the user in a
new line using a loop

Ans:
In [15]:

1 a =input("Enter a string name: ")


2 for i in a:
3 print(i)

Enter a string name: KIRAN


K
I
R
A
N

11. Write a program to find the length of the string "machine learning" with and
without using len function.

Ans:

In [1]:

1 a = "machine learning"
2 length = 0
3 for i in a:
4 length= length+1
5 print(f"Length of {a} is >> {length}")
6 print(f"length by using len function >>",len(a))

Length of machine learning is >> 16


length by using len function >> 16

12. Write a program to check if the word 'orange' is present in the "This is
orange juice".

Ans.

In [2]:

1 a = "This is orange juice"


2 print("orange is present") if "orange" in a else print("orange is not present")

orange is present

In [4]:

1 a= "This is orange juice"


2 print("orange is present") if [Link]("orange") >= 1 else print("orange is not prese

orange is present

13. Write a program to find the number of vowels, consonants, digits, and white
space characters in a string.

Ans:
In [5]:

1 s = "My name is Kiran and I m from 123456 Mumbai"


2 vl = list("aeiou")
3 nv=nc=nd=ns=0
4 for i in [Link]():
5 if i in vl:
6 nv=nv+1
7 elif [Link]() == True:
8 nd= nd+1
9 elif [Link]() == True:
10 ns=ns+1
11 else:
12 nc=nc+1
13 print("Final result")
14 print("Number of vowels :",nv)
15 print("Number of consonants:",nc)
16 print("Number of digits :",nd)
17 print("Number of white space:",ns)

Final result
Number of vowels : 11
Number of consonants: 17
Number of digits : 6
Number of white space: 9

14. Write a Python program to count Uppercase, Lowercase, special character,


and numeric values in a given string.

Ans:
In [6]:

1 s = "PYTHON and DATA SCience class $$@@ 123\u00BD"


2 nu=nl=ns=nn=0
3 for i in s:
4 if [Link]() == True:
5 nu=nu+1
6 elif [Link]() == True:
7 nl=nl+1
8 elif [Link]()== True:
9 nn=nn+1
10 elif [Link]() == True:
11 pass
12 else:
13 ns=ns+1
14 print("Final result")
15 print("Number of upper case char >>",nu)
16 print("Number of lower case char >>",nl)
17 print("Number of special char >>",ns)
18 print("Number of numeric values >>",nn)
19

Final result
Number of upper case char >> 12
Number of lower case char >> 13
Number of special char >> 4
Number of numeric values >> 4

15. Write a program to make a new string with all the consonants deleted from
the string "Hello, have a good day".

Ans:

In [7]:

1 x = "Hello, have a good day"


2 x1=""
3 lv = list("aeiou")
4 for i in [Link]():
5 if i in lv or [Link]()==True:
6 x1=x1+i
7 print(x1)

eo ae a oo a

16. Write a Python program to remove the nth index character from a non-
empty string

Ans:
In [8]:

1 s = "Kiran as a data scientist"


2 n = int(input("enter index value :"))
3 s1 = [Link](s[n],"")
4 s1

enter index value :4

Out[8]:

'Kira as a data scietist'

In [9]:

1 a = "Kiran as a data scientist"


2 n = int(input("Enter nth index:"))
3 result = a[0:n]+a[n+1:]
4 result

Enter nth index:4

Out[9]:

'Kira as a data scientist'

17. Write a Python program to change a given string to a new string where the
first and last characters have been exchanged.

Ans:

In [75]:

1 s = "kiran tayde"
2 s1 = s[0]
3 s2 = s[1:len(s)-1]
4 s3 = s[-1]
5 print("Final result >>>", s3+s2+s1)

Final result >>> eiran taydk

18. Write a Python program to count the occurrences of each word in a given
sentence.

Ans:
In [13]:

1 s= "python is an easy programming language, python is dynamically typed language"


2 for i in set([Link]()):
3 print(f"{i} occurs {[Link](i)} times ")

easy occurs 1 times


typed occurs 1 times
language, occurs 1 times
an occurs 3 times
dynamically occurs 1 times
python occurs 2 times
language occurs 2 times
is occurs 2 times
programming occurs 1 times

In [12]:

1 s= "python is an easy programming language, python is dynamically typed language"


2 d1 = {}
3 for i in [Link]():
4 d1[i]= [Link](i)
5 print(d1)

{'python': 2, 'is': 2, 'an': 3, 'easy': 1, 'programming': 1, 'language,':


1, 'dynamically': 1, 'typed': 1, 'language': 2}

In [175]:

1 string="python is an easy programming language python is dynamically typed language


2 s = [Link]()
3 l1 = []
4 for i in s:
5 if i not in l1:
6 [Link](i)
7 for i in l1:
8 print(f"{i} occurs {[Link](i)} times ")

python occurs 2 times


is occurs 2 times
an occurs 3 times
easy occurs 1 times
programming occurs 1 times
language occurs 2 times
dynamically occurs 1 times
typed occurs 1 times

19. How do you count the occurrence of a given character in a string?

Ans: we can find Occurences of given character by using count() function


In [172]:

1 string="python is an easy programming language"


2 char = input("Enter char >> ")
3 [Link](char)

Enter char >> a

Out[172]:

20. Write a program to find last 10 characters of a string?

Ans:

In [59]:

1 string="python is an easy programming language, python is dynamically typed language


2 result= string[-10:]
3 result

Out[59]:

'd language'

21. WAP to convert a given string to all uppercase if it contains at least 2


uppercase characters in the first 4 characters.

Ans:

In [98]:

1 s = input()
2 c = 0
3 for i in s[0:4]:
4 if [Link]() == True:
5 c=c+1
6 else:
7 pass
8 if c > 1:
9 print("it satisfies the given condition")
10 print("updated string:", [Link]())
11 else:
12 print("it does not satisfies the given condition")
13

DATa science
it satisfies the given condition
updated string: DATA SCIENCE

22. Write a Python program to remove a newline in Python.

Ans:
In [65]:

1 abc=""" We are leaning python


2 We are leaning python"""
3
4 x=[Link]("\n","")
5 x

Out[65]:

' We are leaning python We are leaning python'

23. Write a Python program to swap commas and


○ Sample string: "32.054,23"
○ Expected Output: "32,054.23"

Ans:

In [99]:

1 s = "32.054,23"
2 s1 = [Link](".","@").replace(",",".").replace("@",",")
3 s1

Out[99]:

'32,054.23'

24. Write a Python program to find the first repeated character in a given
string

Ans:

In [100]:

1 s = "kiran tayde"
2 for i in s:
3 c = [Link](i)
4 if c > 1:
5 print("First repeated character >>", i)
6 break
7

First repeated character >> a


In [117]:

1 s = "kiran ganesh tayde "


2 d1 ={}
3 for i in s:
4 c = [Link](i)
5 if c > 1:
6 d1[i] = c
7 print(d1)
8 print("2nd repated character >>", [v for i, v in enumerate([Link]()) if i ==1])
9

{'a': 3, 'n': 2, ' ': 3, 'e': 2}


2nd repated character >> ['n']

25. Write a Python program to find the second most repeated word in a given
string

Ans:

In [137]:

1 s = "data science python data data science ml nlp nlp data nlp"
2 d1 = {i: [Link](i) for i in [Link]()}
3 d2 = {}
4 for i in sorted([Link]()):
5 for j in [Link]():
6 if d1[j] == i:
7 d2[j] = i
8 x = list([Link]())
9 print("second most repeated word in a given string :",x[-2])

second most repeated word in a given string : ('nlp', 3)

26. Python program to Count Even and Odd numbers in a string

Ans:

In [139]:

1 s = "hasga123545"
2 ne=no=0
3 for i in s:
4 if [Link]()==True:
5 if int(i) %2 == 0:
6 ne=ne+1
7 else:
8 no=no+1
9 print("count of even numbers :",ne)
10 print("count of odd numbers :",no)

count of even numbers : 2


count of odd numbers : 4
27. How do you check if a string contains only digits?

Ans: We can check it by using isdigit() function

In [101]:

1 string = "4535454"
2 if [Link]()==True:
3 print("Yes, string contains only digits")
4 else:
5 print("string does not contains only digits")

Yes, string contains only digits

28. How do you remove a given character/word from String?

Ans: we can remove it by using replace () function

In [103]:

1 x = "python is a dynamically typed programming language"


2 word = input("Enter a word:")
3 y = [Link](word,"")
4 print("Updated string:",y)

Enter a word:typed
Updated string: python is a dynamically programming language

29. Write a Python program to remove the characters which have odd index
values of a given string

Ans:

In [14]:

1 s = "data science"
2 print("Result >> ", s[::2])

Result >> dt cec

In [115]:

1 s = "data science"
2 result =""
3 for i,v in enumerate(s):
4 if i%2==0:
5 result=result+v
6 else:
7 continue
8 print(result)

dt cec
30. Write a Python function to reverses a string if its length is a multiple of
5

Ans:

In [15]:

1 s= "python and"
2 if len(s)%5==0:
3 print(s[::-1])
4 else:
5 print("does not satisfies given condition")

dna nohtyp

In [16]:

1 s= "python and science"


2 if len(s)%5==0:
3 print(s[::-1])
4 else:
5 print("does not satisfies given condition")

does not satisfies given condition

31. Write a Python program to format a number with a percentage(0.05 >>


5%)

Ans:

In [17]:

1 n=0.05
2 result= n*100
3 print(f"given number : {n} >> {result}%")

given number : 0.05 >> 5.0%

32. Write a Python program to reverse words in a string

Ans:

In [18]:

1 s= "python and data science"


2 s1 = [Link]()[::-1]
3 z=" ".join(s1)
4 z

Out[18]:

'science data and python'


In [127]:

1 s= "python and data science" #reverses characters of each word


2 s1 = [Link]()
3 l1=[]
4 for i in s1:
5 x=i[::-1]
6 [Link](x)
7 z=" ".join(l1)
8 z

Out[127]:

'nohtyp dna atad ecneics'

33. Write a Python program to swap cases of a given string

Ans:

In [130]:

1 s ="PYthonN"
2 [Link]()

Out[130]:

'pyTHONn'

34. Write a Python program to remove spaces from a given string

Ans:

In [22]:

1 s = "Data SCience and Algorithms "


2 s1 = [Link](" ","")
3 print("string after removing spaces :",s1)

string after removing spaces : DataSCienceandAlgorithms

In [134]:

1 s="Data SCience and Algorithms "


2 s1=""
3 for i in s:
4 if [Link]()==False:
5 s1=s1+i
6 else:
7 continue
8 print(s1)
9

DataSCienceandAlgorithms
35. Write a Python program to remove duplicate characters of a given
string

Ans:

In [156]:

1 s = "aacbdee"
2 s1 = []
3 for i in s:
4 if i not in s1:
5 [Link](i)
6 "".join(s1)

Out[156]:

'acbde'

36. Write a Python Program to find the area of a circle

Ans:

In [24]:

1 r = int(input("Enter value of radius:"))


2 area= 3.14*r**2
3 print("Area of circle is:",area)

Enter value of radius:12


Area of circle is: 452.16

37. Python Program to find Sum of squares of first n natural numbers

Ans:

In [25]:

1 n = int(input("enter the value of n :"))


2 s=0
3 for i in range(1, n+1):
4 s=s+i**2
5 print("Sum of squares of first {} numbers is {}".format(n,s))

enter the value of n :10


Sum of squares of first 10 numbers is 385

[Link] Program to find cube sum of first n natural numbers.

Ans:
In [26]:

1 n = int(input("Enter value of n:"))


2 s=0
3 for i in range(1,n+1):
4 s= s+i**3
5 print("cube sum of first {} natural numbers is :{}".format(n,s))
6

Enter value of n:5


cube sum of first 5 natural numbers is :225

[Link] Program to find simple interest and compound interest

Ans:

In [180]:

1 P = int(input("Enter principle amount >> "))


2 R = float(input("Enter Rate of interest >> "))
3 T = int(input("Enter Time period in years >>"))
4 SI =( P*R*T)/100
5 print("Simple Intrest >>",SI)
6
7 c=(P*(1+(R/100))**T)
8 compound_interest=c-P
9 print("compound_interest is:",compound_interest)
10

Enter principle amount >> 452036


Enter Rate of interest >> 8.9
Enter Time period in years >>5
Simple Intrest >> 201156.02
compound_interest is: 240292.83818300033

[Link] program to check whether a number is Prime or not

Ans:

In [27]:

1 # prime number >> number which is divisible by 1 or itself


2
3 n = int(input("enter number :"))
4 for i in range(2,n):
5 if n % i == 0:
6 print("Number is not prime")
7 break
8 else:
9 print("It is prime number")

enter number :13


It is prime number
In [28]:

1 n=int(input("enter a number:"))
2 c=0
3 for i in range(2,n):
4 if n%i == 0:
5 c=c+1
6 break
7 if c==0:
8 print(" number is prime")
9 else:
10 print("number is not prime")
11

enter a number:88
number is not prime

Common questions

Powered by AI

Python offers two primary methods for string formatting: the f-string (formatted string literals) introduced in Python 3.6 and the format() method. F-strings are prefixed with an 'f' and allow the inclusion of expressions inside curly braces, directly embedding variable values within strings, which simplifies the syntax and enhances readability . The format() method, on the other hand, uses placeholders defined by curly braces, populated by passing variables as arguments, providing a flexible way to build strings with dynamic values while maintaining separation between format and data . Both methods support alignment, width, precision control, and type-specific formatting, improving code functionality.

In Python, local variables are declared inside a function and are only accessible within that specific scope. They are created when the function is called and destroyed once the execution of the function is complete . In contrast, global variables are defined outside any function and are accessible both inside and outside functions. This makes them useful for maintaining state information across function calls or sharing data between different parts of a program . However, excessive use of global variables can lead to less maintainable code due to their widespread visibility and susceptibility to unintended modifications.

To count occurrences of each word in a Python string, the string is typically split into words using the split() method, which breaks the string at whitespace characters. A loop iterates over this list, and a dictionary is used to maintain count totals for each word. Challenges arise in handling punctuation or case sensitivity. Words with trailing punctuation or different capitalizations may be counted separately unless processed uniformly (e.g., stripping punctuation or lowering the case), thereby requiring additional steps for data cleaning and normalization .

Escape characters in Python, designated by a backslash (\), allow the inclusion of characters that are otherwise illegal in strings. They are used to represent whitespace characters like tab (\t), newline (\n), or carriage return (\r), as well as to insert special characters like backslash itself (\\) or single and double quotes (\' and "). This capability is essential for managing strings that span multiple lines or include paths and special formatting requirements without causing syntax errors .

String literals in Python are defined as sequences of characters enclosed in quotes, used to represent text. They can be single, double, or triple-quoted strings, with triple quotes also allowing for multi-line strings. String literals are fundamental for code readability as they clearly delineate text and string operations, ensuring that strings are handled accurately within the program logic. By using literals, developers can embed descriptive text, document pieces of code, or include necessary language elements without ambiguity, thus contributing to maintainable and clear coding practices .

Variable assignment in Python can be performed primarily through assignment operators and conditional expressions. The standard "=" operator assigns a value directly to a variable, while compound assignment operators like "+=", "-=" modify the variable and update it in place, providing concise ways to express calculations . Conditional expressions can also assign values using concise if-else statements to determine which value to assign based on a boolean condition, promoting readable conditional logic within expressions . These methods enhance code efficiency by reducing redundant operations and maintaining clear and concise code blocks.

Python is a dynamically typed language, which means variables do not require an explicit declaration to reserve memory space. It supports object-oriented programming, making it possible to create reusable code and manage large codebases efficiently. Python is free and open-source, contributing to a significant global community and library repositories like PyPI. Its versatility is apparent as it's used extensively in various fields such as AI, web development, machine learning, and scientific calculations . Additionally, Python is known for its readability, mimicking English structure, and has an extensive standard library that includes many convenient packages and modules . It is also extensible and embeddable, allowing integration with languages like C++ .

Python supports several data types, each providing unique capabilities. Numeric data types like int, float, and complex are used for mathematical calculations. The str type is used for text manipulation. Sequence types include list, tuple, set, and frozenset, catering to ordered and unordered collections of data. The bool data type represents truth values True and False, facilitating conditional operations. The dict type is for key-value pairings, crucial for data structure operations. Additionally, binary data types such as bytes, bytearray, and memoryview handle binary data efficiently .

Comments in Python, marked by the '#' symbol, serve primarily for code documentation and readability enhancement. They allow developers to annotate code sections with explanations or rationales that are not visible to the interpreter. This practice clarifies intentions behind complex code blocks, helps in pinpointing areas for future updates, and makes the codebase accessible to collaborators or future developers. Comments are also crucial during debugging, serving as reminders of expected behavior or focus points for troubleshooting . Their use throughout software development fosters a more organized workflow and a maintainable code structure.

Python's data structures such as lists, tuples, sets, and dictionaries each provide unique methods for managing collections of data. Lists are mutable and ordered, allowing dynamic resizing, whereas tuples are immutable, ensuring consistency and protection against accidental changes. Sets are unordered collections of unique elements which excel in membership testing, duplication removal, and set operations like union and intersection. Dictionaries store data as key-value pairs, enabling efficient look-ups and association. These structures facilitate efficient data manipulation, offering built-in methods for tasks such as sorting, filtering, aggregation, and providing methods to support algorithmic challenges .

You might also like