python Flashcards

(146 cards)

1
Q

Functions definition and use

A

Python Functions is a block of statements that return the specific task.

The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.

It increases code reusability & readability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

If you forget to increment the loop variable, you’ll end up with an infinite loop. Give example

A

To avoid the infinite loop problem, it’s essential to increment the value of i inside the loop:

i = 0
while i < 5:
print(i)
# Output:
# 0
# 0
# 0
# … (infinite loop)

i = 0
while i<5:
print(i)
i = i + 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

create a function to find whether a number is prime or not.
input - num
output - true if prime and false if not prime

A

def is_prime(num):
for i in range(2,num):
if num%i ==0:
return False
return True

print(is_prime(24))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

transpose an array using numpy

A

use np.transpose()

array = np.array([[1, 2, 3], [4, 5, 6]])

Transpose the array
transposed_array = np.transpose(array)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Lists

A

A list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe stored at different locations.
* List can contain duplicate items.
* List in Python are Mutable. Hence, we can modify, replace or delete the items.
* List are ordered. It maintain the order of elements based on how they are added.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

flowchart definition

A

diagrammatic representation
-of an algorithm work flow or process
-illustrates a solution model to a given problem
- shows us the steps using boxes of various kinds & their order by connecting the boxes with arrows
-used in analysing, designing, documenting or managing a process or program in various fields.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Checking if string contains numeric values and alphabets (True/False)

A

print(‘ABC123’.isalnum())
print(‘ABC 123’.isalnum())

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Indexing of arrays

A

array[3]
allows us to access element at index 3

array[-3]
allows us to access elements from the end of the array, third last value in this case

In a 2D array, you can access elements using two indices (row and column)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Semantic error

A

when there is some logical errors
OR
there is no end to the loop in the syntax

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Logical OR | operator

A

print(True|True) #Output: True

print(True|False) #Output: True

print(False|True) #Output: True

print(False|False) #Output: False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

transpose a dataframe using pandas

A

dataframe.transpose()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Example of ‘syntax error: cannot assign value to a literal’?

A

5 = i

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Logical ~ (NOT) Operator

A

print(~True) #Output: False

print(~False) #Output: True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

top down approach is followed by ________

A

structural programming languages like C, FORTRAN

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

age = int(input(“Enter age: “)) #if input is string “ten” then we get a _______ error

A

Value Error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

range(1,23)
including excluding?

A

including 1, excluding 23

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

plotting box plot

A

plt.boxplot(data)

plt.title(‘Box Plot’)
plt.ylabel(‘Value’)
plt.show()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Top down approach

A

a system design approach where the design starts from the complete system which is then divided into smaller sub applications with more details.

the focus is on breaking the problem into smaller ones and then the process is repeated with each problem.

This approach is followed by structural programming language

It is focused on decomposition approach

draw diagram

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

3 dimensional array

A

A 3D array in Python is essentially an array of arrays of arrays,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

create a Python function named average_of_five_numbers that calculates the average of five given integers and returns the result.

The input consists of five integers: a, b, c, d, e.

The output should be a single integer, which is the average of a, b, c, d, e.

A

def average_of_five_numbers(a,b,c,d,e):
average =(a+b+c+d+e) /5
return average

print(average_of_five_numbers(15,14,12,13,17)) #output

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

The CONTINUE keyword

A

The continue statement is used to skip the current iteration of a loop and proceed to the next iteration.
#catches hold of semantic errors- logical error that python cannot catch - like while loop running infitite times

for i in range(1,11):
if i % 2 == 0:
continue
print(i, end=’ ‘)
print(‘done’)

output: 1 3 5 7 9 done

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

text = “Hello”
print(text[10]) # Index out of range gives _____ error

A

IndexError: string index out of range

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

when calling a function, if the argument is missing, we get a ____Error

A

TypeError

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Checking if a string has all uppercase letters (True/False)

A

print(str_variable.isupper())

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
marks = [25, 56, 67] what are the basic operations you can apply to this to get results in integers?
print(max(marks)) print(min(marks)) print(len(marks)) print(sum(marks))
26
What happens when if(False): print(False)
no result because condition is false
27
Which error comes up if a variable name starts with a number?
Syntax error : invalid decimal literal
28
In Python there is no distinct data type for single characters. Both strings and single characters
message = "69Hello Message" print(message[0]) #note there is square bracket print(type(message[0])) #
29
function can be defined using ______ keyword
def
30
parameter
named entity in a function definition that specifies an argument that function can accept
31
Disadvgs of top down approach
the codes can be repeated
32
Program to print no. of hours in a day
print (24)
33
% , /, //
% - modulo - gives remainder / - simple division - returns float // - returns quotient integer
34
Problem
a well defined tasks or challenge that requires a computational soln.
35
create a Python function named is_vowel that determines whether a given character is a vowel or not. #The input consists of a single parameter: char. Char is the character that needs to be tested. #The output should be a boolean value, returning True if the character is a vowel and False if it's not. #Write a flowchart, algorithm & python code
def is_vowel(char): vowel_string = 'aEiou' is_char_vowel = char in vowel_string return is_char_vowel print(is_vowel('a')) print(is_vowel('b'))
36
Checking if the string is a digit or a numeric value(True/False)
only works on strings and checks all characters print("123".isdigit())
37
Algorithm to find duplicates in a list
Steps: 1. Start 2. Create or input a list of elements 3. Initialize an empty dictionary freq = {} 4. Initialize an empty list duplicates = [] 5. For each element item in the list: o If item is not in freq, add it with value 1 o Else:  Increase the count of item in freq  If item not already in duplicates, append it to duplicates 6. Return the list duplicates 7. End
38
capitalising the first letter of a string, making the rest of the letters lowercase and printing it
print(string_variable.capitalize()) z important
39
Calling function without passing an argument Python will throw a _______ Error
Type Error
40
PEDMAS rules of precedence with example
The PEDMAS rules of precedence are crucial for understanding how Python evaluates mathematical expressions. Here's a breakdown of the order of operations: Parentheses: () - Expressions inside parentheses are evaluated first. Exponents: ** - Exponentiation is performed next. Multiplication and Division: *, /, //, % - These operations are performed from left to right. Addition and Subtraction: +, - - These are the last operations to be performed, also from left to right. Here's a simple example to illustrate: result = (2 + 3) * 4 ** 2 / (1 + 1) - 5 print(result) Let's break it down step-by-step according to PEDMAS: Parentheses: (2 + 3) and (1 + 1) are evaluated first, resulting in 5 and 2 respectively. Exponents: 4 ** 2 is evaluated next, resulting in 16. Multiplication and Division: 5 * 16 / 2 is evaluated from left to right, resulting in 80 / 2 which is 40. Subtraction: Finally, 40 - 5 is evaluated, resulting in 35. So, the output of the above code will be 35.
41
write a flowchart for print sum of two numbers
start -> read input a -> read input b ->calc sum of a & b -> print the sum -> end
42
import matplotlib
import matplotlib.pyplot as plt
43
symbols of a flowchart
1. Terminal - indicates flowchart start/end points - OVAL 2. Flowlines - default flow is left to right and top to bottom- ARROWS 3. Input/Output - input/output - PARALLELOGRAM 4. Process - mathematical compution / variable assignment - RECTANGLE 5. Decision - true/false statement being tested - DIAMOND/KITE 6. Module Call - program module helps to distinguish between program task and specific task module. HORIZONTAL LINES IN RECT , VERTICAL LINES IN RECT 7. Connector - allows to connect two flowcharts on same or dif page - SMALL CIRCLE WITH A LETTER OR NO. IN IT (on page) SMALL PENTAGON WITH LETTER OR NO. IN IT (off page)
44
use numpy to create a new array arr of 9 values, in 3 rows and 3 columns make it into a dataframe with index r1, r2, r3 and columns c1, c2,c3
arr =np.arange(9).reshape(3,3) df= pd.DataFrame(arr,columns=['c1','c2','c3'],index=['r1','r2','r3'])
45
functions can be called ________ times to reuse its functionality
multiple
46
3 ways for string concatenation in python
s1 = "Hello" s2 = "World" res = s1 + " " + s2 s1 = "Python" s2 = "programming" #use an f string to create a formatted string that includes both variables result = f"{s1} is a popular {s2}." a = 5 b = 10 print("The sum of {} and {} is {}.".format(a, b, a + b))
47
Top down design is based on ___ approach
decomposition approach
48
id() function and what it is useful for
This function returns a unique integer that represents the memory address of the object. This can be useful for debugging or understanding how objects are managed in memory.
49
plotting scatter plot
plt.scatter(x, y, color='blue') plt.title('Scatter Plot') plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.show()
50
to demonstrate the difference between for and while loops, use the sum of squares example.
def sum_of_squares_upto_limit(limit): i=1 sum=0 while(i*i<=limit): sum+=i*i i+=1 return sum print(sum_of_squares_upto_limit(30)) def sum_of_squares_upto_limit(limit): sum = 0 for i in range (1,limit+1): if i*i<=limit: sum += i * i return sum print(sum_of_squares_upto_limit(30))
51
Checking the starting characters in a string (True/False)
st = "Hello World" print(st.startswith('Hell'))
52
1 dimensional array
list
53
2 dimensional array
list of lists
54
using mathematical functions like pi and sqrt, pow, sin, cos, etc
first import math
55
extract substring from one index value to another
str='Hello World' print('Hello World'[0:5])
56
Algorithm to find temperature in a day
Steps: 1. Start 2. Define a function temperature_of_the_day() 3. Inside the function: o Prompt the user to input the temperature in Celsius and store it in variable temp o If temp >= 35, then:  Print “It’s a hot day” o Else if temp >= 20, then:  Print “It’s a warm day” o Else if temp >= 10, then:  Print “It’s a cool day” o Else:  Print “It’s a cold day” 4. Call the function 5. End
57
The break KEYWORD
The break statement is used to exit a loop when a specific condition is met. for i in range(1,11): if i == 5: break print(i, end = ' ') print("done") #In this code, the for loop is set to run from 1 to 10. Inside the loop, #there's a condition that checks if i is equal to 5. When i reaches 5, the break statement is executed, and the loop is immediately terminated. output: 1 2 3 4 done
58
For loops
In python, it is used to iterate over a sequence of items like strings, range, list,. The loop will execute a block of statements FOR each item IN the sequence. Eg:- Syntax :- for Var in (0, 10): # statements
59
adding a value to a series with indexes
s = pd.Series([10,20,30],index=['a','b','c']) s['d'] =400 #adding a new value with new index
60
compound data types
lists can have items of diff data types example list = ['banana', 34, 56.7, 'apple'] item 1 is string item 2 is integer item 3 is float showing diff types in one list
61
Logical AND & operator
print(True&True) #Output: True print(True&False) #Output: False print(False&True) #Output: False print(False&False) #Output: False
62
in python variables are ____?
case-sensitive
63
Algorithm to find even & odd numbers in a list.
Steps: 1. Start 2. Input a list of integers 3. Initialize two empty lists: o even_list = [] o odd_list = [] 4. For each number num in the input list: o If num % 2 == 0, append num to even_list o Else, append num to odd_list 5. Print or return both even_list and odd_list 6. End
64
While loop
In python while loop is used to repeatedly execute a block of statements while a condition is true. The loop will continue to run as long as the condition remains true. Eg:- while condition: #statements
65
logical operators
and, or, xor, not
66
plotting histogram
plt.hist(data, bins=5, edgecolor='black') plt.title('Histogram') plt.xlabel('Value') plt.ylabel('Frequency') plt.show()
67
chained conditional statements
Chained conditionals in Python allow you to check multiple conditions in a sequence, executing different blocks of code based on which condition is true. This is achieved using if, elif, and else statements. temperature = 55 print("The temperature is:", temperature) if temperature > 65: print("This is a nice day.") elif temperature > 50: print("This is an okay day.") else: print("The weather is too cold") print("End of program")
68
array slicing
Array slicing allows you to extract subarrays by specifying a range of indices: arr = array.array('i', [10, 20, 30, 40, 50]) print(arr[1:4]) # Output: array('i', [20,30,40]) print(arr[::2]) # Output: array('i', [10,30,50]) print(arr[-4:-1]) # Output: array('i', [20,30,40])
69
3 steps to solve a problem
1- Understanding the prob (input) 2- Analysing the prob (process) 3- Developing the soln (output)
70
Nested if else conditional statement
Means an 'if...else' statement inside another if statement. We can use nested if statements check conditions within conditions. Eg:- syntax if () if else if ()
71
Checking if a string has all lowercase letters (True/False)
print(str_variable.islower())
72
create a Python function named is_valid_triangle that returns if the three given angles can form a valid triangle. #An angle cannot be less than or equal to 0. #Input - The input consists of three integers: angle1, angle2, angle3. #Output - Function should return a boolean - True if the sum of the angles equals 180, indicating a valid triangle. If the sum does not equal 180, the function should return False.
def is_valid_triangle(angle1,angle2,angle3): if angle1<=0: return False if angle2 <=0 : return False if angle3 <=0: return False sum_of_angles = angle1+angle2+angle3 return sum_of_angles ==180 print(is_valid_triangle(30,60,90))
73
print(10 / 0) # Division by zero gives _____ error
ZeroDivisionError
74
Comparison operators and types
Comparison operators in Python are used to compare two values and return a boolean value, either True or False. These operators are essential in programming for making decisions and controlling the flow of the program. equal to == not equal to != greater than > less that < greater than or equal to >= less than or equal to <=
75
Algorithm to find greatest of two numbers, three & four numbers
Steps: 1. Start 2. Define a function find_greatest(a, b) 3. Inside the function: o If a > b, return "a is greater" o Else if b > a, return "b is greater" o Else, return "Both numbers are equal" 4. Input two numbers from the user 5. Call the function with those numbers 6. Print the result 7. End Similarly for 3 & 4 numbers……
76
Algorithm to find whether a number is prime or not
Steps: 1. Start 2. Define a function if_prime(n) 3. Inside the function: o If n <= 1, return False o Loop from i = 2 to sqrt(n):  If n % i == 0, return False o If loop completes with no divisors, return True 4. Call the function with a number 5. If True, print "n is a prime number" 6. Else, print "n is not a prime number" 7. End
77
Eg: def product_of_two_numbers (a, b) Here, a and b are
parameters example
78
IF ELSE statement
Else allows us to specify a block code that will execute if the condition associated with an if or (else if) elif statement evaluates to false. Else block provides a way to handle all other cases that don't meet the specific condition Eg:- else print ("Not eligible to vote")
79
Difference between for loop and while loop
FOR LOOP - Used to iterate over a sequence of items WHILE LOOP - As long as the condition is true, repeatedly used to execute a block of code. FOR LOOP - Requires a sequence to iterate. WHILE LOOP - Requires an initial condition that is checked at the start of the loop FOR LOOP - Typically used for iterating over fixed sequence of items. WHILE LOOP - Used for more complex control statements FOR LOOP - Print each fruit in a fruit list: fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) WHILE LOOP -Print i as long as i is less than 6: i = 1 while i < 6: print(i)
80
plotting line plot
plt.plot(x, y, marker='o', linestyle='-', color='red') plt.title('Line Plot') plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.show()
81
creating a dataframe
A DataFrame is a two-dimensional, size-mutable, and potentially heterogeneous tabular data structure with labeled axes (rows and columns). Here's how you can create one: import pandas as pd Creating a DataFrame from a dictionary data = { 'Name': ['Alice', 'Bob', 'Charlie', 'David'], 'Age': [24, 27, 22, 32], 'City': ['New York', 'Los Angeles', 'Chicago', 'Houston'] } df = pd.DataFrame(data) print(df) Creating a DataFrame from a list of dictionaries data = [ {'Name': 'Alice', 'Age': 24, 'City': 'New York'}, {'Name': 'Bob', 'Age': 27, 'City': 'Los Angeles'}, {'Name': 'Charlie', 'Age': 22, 'City': 'Chicago'}, {'Name': 'David', 'Age': 32, 'City': 'Houston'} ] df_from_list = pd.DataFrame(data) print(df_from_list) #Creating a fataframe from multiple series columns = pd.Index(['col1','col2','col3']) countries = pd.Series(['India','US','Japan'],index=columns,name='country') populations =pd.Series([22.33,33.88,99],index=columns,name='population') new_york = pd.DataFrame([countries,populations])
82
reading dataframe from csv file
dataframe_name = pd.read_csv("path_of_csv_file.csv", index_col=0) index_col = 0 -> first col contains the row indexes
83
techniques and design used to solve a problem
1. Pseudocode 2. Algorithm 3. Flowchart
84
Pseudocode
it is an informal high level description of the operating principle of a computer program it is used to document the program or module design (algorithm) pseudo means false. pseudocode means false code
85
if(False): print("False") output?
no output since condition is false
86
Bottom up approach used in ______
research
87
Advtgs of top down approach
- better understanding of entire program and less info about subprogram - well established communication is not required
88
string repetition
use * multiplication operator s = "Hello! " repeated_string = s * 3 print(repeated_string) # Output: Hello! Hello! Hello!
89
ELIF statement
Stands for "else if ". It allows us to check multiple conditions promoting a way to execute different blocks of code based on which condition is true. Makes our code more efficient and readable by eliminating the need for multiple nested if statements.
90
structure of function
name, parameters and body
91
data visualisation ethics
92
Checking if a string has first letter capital and rest all lowercase (titlecase) (True/False)
print(str_variable.istitle())
93
#create a Python function named is_vowel that determines whether a given character is a vowel or not. #Input Format : The input consists of a single parameter: char. Char is the character that needs to be tested. #Output Format : The output should be a boolean value, returning True if the character is a vowel and False if it's not.
def is_vowel(char): vowels='aeiou' is_char_vowel = char in vowels return is_char_vowel is_vowel('a')
94
Flowchart is used in
analysing, designing, documenting or managing a process or program in various fields
95
Built-in library function
These are standard functions in Python that are available to use. i) Abs() : Return the absolute value of a number ii) Id(): Return the identity of an object iii) Range(): generates a sequence of numbers
96
function call (invoking the function)
the act of running a function by using its name followed by arguments in parentheses.
97
How to use the in keyword to check whether a character or a sequence of characters exists within a specific string?
print('Hello' in 'Hello World') #true print('ello' in 'Hello World') #true print('Ello' in 'Hello World') #False print('bello' in 'Hello World') #False
98
IF condition statement
if statement executes a block of code if the given condition is true Eg:- age = 20 if (age>= 18) print ("Eligible for voting")
99
Checking if a string has first letter capital and the rest of the letters in lowercase (True/False)
print(str_variable.istitle())
100
Checking if string only contains alphabets (True/False)
print('23'.isalpha()) print('2A'.isalpha()) print('ABC'.isalpha())
101
taking input and storing it in a variable example keyboard input: raw input statement
age = int(input("Enter age: "))
102
return value
the value a function sends back to the place where the function was called from. it is specified by the return keyword in a function.
103
Algorithm
can be defined as a complete, unambiguous, finite number of logical steps for solving a specific problem eg: finding whether a number is prime or not
104
finding the sum of consecutive numbers in a range.
sum = 0 for i in range (1,5): #stops just before 5. 1+2+3+4=10 sum = sum + i print(sum)
105
Finding a substring within a string #Returns index value and -1 if it doesn't exist
print('Hello World'.find('Hello')) #Output 0 print('Hello World'.find('ello')) #Output 1 print('Hello World'.find('llo')) #Output 2 print('Hello World'.find('lo')) #Output 3 print('Hello World'.find('Ello')) #Output -1 print('Hello World'.find('plo')) #Output -1
106
rename a column name of dataframe
drugs.rename(columns={'Sex':'Gender'}, inplace=True)
107
function declaration
the act of defining a functions name, parameters and body. It doesnt run the function but sets it up, to be called later.
108
default integer for an undefined variable is
10
109
how to create an n dimensional array?
use np.array() function on a list
110
what are the methods one can apply to lists? animals = ['Cat', 'Dog', 'Elephant']
animals.extend(['Giraffe', 'Horse']) #adds these items at the end animals += ['Lion', 'Monkey'] #again adds these items at the end of the list animals.append(['Tiger', 'Cheetah']) #adds the list at the end as a new item animals.insert(2, 'Hippo') #use of index marks.remove('Cat') print('Hippo' in animals) #check if a value exists in the list print(animals.index("Cat")) #index is starting from zero print(animals.index('Horse')) #returns index - throws a value error if item not in list
111
Checking the ending characters in a string (True/False)
st = "Hello World" print(st.endswith('World'))
112
index and loop starting numbers?
index starts from 0 and loop starts from 1
113
language = 'Python' #iterate over each character in language
for x in language: print(x) P y t h o n
114
def product_of_two_numbers(a,b): print(a * b) product=product_of_two_numbers(2,6) print(product) #prints None - WHY?
#12 is printed inside the function #product stores None because the function doesn't return anything #In Python, if no return is used, the function returns None by default
115
Coercing a float to an int. What happens to the part after decimal?
It is truncated(chopped off). Python always rounds down to the next lowest integer, regardless of the value of the decimal portion.
116
STRING TRAVERSAL using FOR loop and WHILE loop
String traversal refers to the process of iterating over each character in a string. text = "Hello, World!" for char in text: print(char) text = "Hello, World!" index = 0 while index < len(text): print(text[index]) index += 1
117
if(True): print(False)
condition is true so False is printed
118
reading dataframe from excel file
dataframe_name = pd.read_excel("path_of_csv_file.xlsx", index_col=0) index_col = 0 -> first col contains the row indexes
119
converting a string into all uppercase and printing it
print(string_variable.upper())
120
Flowchart shows the steps as ______
boxes of various kinds and their order by connecting the boxes with arrows
121
converting a string into all lowercase and printing it
print(string_variable.lower())
122
Reading JSON Files Using Pandas
To read the files, we use the read_json() function and through it, we pass the path to the JSON file we want to read. Once we do that, it returns a “DataFrame”( A table of rows and columns) that stores data. If we want to read a file that is located on remote servers then we pass the link to its location instead of a local path. Additionally, the read_json() function in Pandas provides various parameters to customize the reading process
123
creating a series
A Series is a one-dimensional array-like object that can hold any data type. Here's how you can create one: import pandas as pd Creating a Series from a list data = [10, 20, 30, 40, 50] series = pd.Series(data) print(series) Creating a Series with custom index data = [10, 20, 30, 40, 50] #values index = ['a', 'b', 'c', 'd', 'e'] #index series_with_index = pd.Series(data, index=index) print(series_with_index)
124
which operator is used to check if the 2 strings are the same?
== output is true or false
125
Read Text Files with Pandas
Below are the methods by which we can read text files with Pandas: Using read_csv() Using read_table() Using read_fwf() Syntax: data=pandas.read_csv(‘filename.txt’, sep=’ ‘, header=None, names=[“Column1”, “Column2”]) Syntax: data=pandas.read_table(‘filename.txt’, delimiter = ‘ ‘) Syntax: data=pandas.read_fwf(‘filename.txt’)
126
what does the len function return when used on a list?
The len() function in Python is used to determine the number of items in a list. Example list my_list = [1, 2, 3, 4, 5] Using len() to get the number of items in the list list_length = len(my_list)
127
Variable names must start with?
letters or underscores
128
iloc
iloc is used for integer-based indexing. It allows you to select rows and columns by their integer positions. # Select the first row first_row = df.iloc[0] # Select the first two rows first_two_rows = df.iloc[0:2] print(first_two_rows)
129
Python dictionaries
#Python Dictionaries are also arrays #-> Mapping between keys & values #->Keys are not positional based #-> but still its an associative array d = {'a':1,'b':2,'c':3}
130
plotting bar plot
plt.bar(categories, values, color='green') plt.title('Bar Plot') plt.xlabel('Category') plt.ylabel('Value') plt.show()
131
give the syntax and example
Syntax: def function_name(parameters): #statement return expression Example: # A simple Python function def fun(): print("Welcome to GFG")
132
What is a loop? explain with example why we need it and why it is required.
A loop is a set of statements that are used to execute a set of statements more than one time. For Example: If we want to print "Hello" 100 times then we have to write a print statement 100 times which can be tedious task to perform. But with the help of loops, we can perform this in a few lines of code.
133
reading just the values or just the index of a series
s.index s.values
134
create a Python function named has_greater_element that checks whether there is any number greater than a given value in a list of numbers. #Input Format : the input consists of two parameters: numbers: A list of integers. and value: An integer to compare against. #Output Format : #The output should be a Boolean value: #True if there is at least one number greater than value in the list. #False if there is no number greater than value in the list or if the list is empty.
def has_greater_element(numbers, value): if not numbers: # Check if the list is empty return False for num in numbers: # Loop through the list if num > value: # Check if any number is greater return True return False # If no number is greater, return False print(has_greater_element([50, 60, 90], 15)) # Output: True print(has_greater_element([10, 5, 2], 15)) # Output: False print(has_greater_element([], 10)) # Output: False
135
What are conditional statements? Give proper example.
Conditional statements in Python are used to execute different blocks of code depending on whether a certain condition is true or false. They are essential for creating programs that can make decisions and respond to different situations. The primary conditional statements in Python are if, else, and elif.
136
#loop for sum of numbers from 1 to 10
sum = 0 for i in range (1, 11): sum = sum + 1 print(sum)
137
code/method for checking type of variable?
type(variable)
138
User-defined function
We can create our own functions based on our requirements. # A simple Python function def fun1(): print("Hello World")
139
Argument
the actual value that is passed to a function when it is called. It is used to assign a value to the corresponding parameter in the function defined.
140
#Create a function temperature_in_the _city #If the temperature is <0, Print "It is freezing", if temp is <=10, print "it is cold" #if temp is <=20, print, it is pleasant, else if temp >=20, print it is hot
def temperature_in_the_city(temp): if temp < 0: print ('It is freezing') elif temp <= 10: print('It is cold') elif temp <= 20: print ('It is pleasant') else: print ('It is hot') temperature_in_the_city(-4)
141
write a algorithm for print sum of two numbers
1. define the function is - vowel with character as a paramether passed. 2. check whether the charater is vowel or not & store it in is-char-vowel 3. return the value of is-char-vowel 4. call the function "in-vowel" & test the function with different characters.
142
if(False): print(True) #this gives which error?
IndentationError: expected an indented block after 'if' statement on line 1
143
in depth steps for problem solving
1. Understanding/Analysing the problem 2. Developing the algorithm/pseudocode 3. Coding 4. Testing and debugging
144
loc
loc is used for label-based indexing. It allows you to select rows and columns by their labels. Assuming the DataFrame has labeled indices df.index = ['a', 'b', 'c'] Select the row with label 'a' row_a = df.loc['a'] print(row_a) Select rows with labels 'a' and 'b' rows_ab = df.loc[['a', 'b']] print(rows_ab)
145
Logical XOR ^ operator
print(True^True) #Output: False print(True^False) #Output: True print(False^True) #Output: True print(False^False) #Output: False
146
STRING OPERATION : using String traversal using loop #Reverse the word in string
def reverse(word): reversed_word='' for ch in word: reversed_word = ch + reversed_word return reversed_word print(reverse('python')) def reverse(word): reversed_word = '' i = len(word) - 1 # Start from the last character while i >= 0: reversed_word += word[i] i -= 1 return reversed_word print(reverse('python')) Algorithms -Reverse a string in python Steps: 1. Start 2. Input the string str 3. Initialize an empty string rev = "" 4. Loop from the end of str to the beginning: 5. For each character ch, append it to rev 6. After the loop ends, rev contains the reversed string 7. Print rev 8. End