In Python, branching and looping are fundamental building blocks that control the flow of your program. Here's a quick breakdown:
- Decision-making: Branching allows your code to make decisions based on conditions.
- if statements: The core of branching, if statements execute a block of code only if a specified condition is true.
- if-else statements: Expand on if by providing an alternative block of code to execute if the condition is false.
- Nested conditionals: You can combine multiple if-else or if-elif (else if) statements to create complex decision-making logic.
- Repetition: Looping allows you to execute a block of code repeatedly.
- for loops: Ideal for iterating over a sequence of items, like a list or string. They execute a code block for each item in the sequence.
- while loops: Useful for repeating code as long as a certain condition remains true.
- Control flow statements: Both for and while loops can use break to exit the loop prematurely and continue to skip to the next iteration.
By mastering these concepts, you'll be able to write Python programs that adapt to different situations and perform repetitive tasks efficiently.
Now, lets practice some questions from this section :)
- Number Sign Detector: Write a program that takes a number as input and prints "Positive," "Negative," or "Zero" depending on its sign. (Explanation: Use an if-else chain to check for positive, negative, or zero.)
- Divisibility Check: Write a program that takes two numbers as input and determines if the first number is divisible by the second. Print "Divisible" or "Not Divisible." (Explanation: Use the modulo operator (%) to check for divisibility.)
- Triangle Validity: Write a program that takes three side lengths as input and determines if they form a valid triangle (sum of any two sides must be greater than the third). Print "Valid Triangle" or "Invalid Triangle." (Explanation: Use if statements to check the triangle inequality.)
- Vowel or Consonant (Enhanced): Write a program that takes a character as input and differentiates between uppercase and lowercase vowels (aeiouAEIOU) and consonants. Print the appropriate category. (Explanation: Use a combination of string methods and if statements for case-sensitivity.)
- Temperature Converter: Write a program that takes a temperature value and a unit (C or F) as input. Convert it to the other unit and print the result. (Explanation: Use if-else statements to handle different units and perform the conversion.)
- Day of the Week: Write a program that takes a number (1-7) as input and prints the corresponding day of the week (Monday-Sunday). Handle invalid input. (Explanation: Use elif statements to assign days based on the number.)
- Month Name: Write a program that takes a month number (1-12) as input and prints the corresponding month name (January-December). Use elif statements and handle invalid input. (Explanation: Use elif statements to map month numbers to names.)
- Math Operation: Write a program that takes two numbers and an operator (+, -, *, /) as input. Perform the chosen operation and print the result. Handle division by zero. (Explanation: Use elif statements to determine the operation and handle errors.)
- Traffic Light Simulator: Write a program that simulates a traffic light with three states (red, yellow, green). The program should loop and change states at specified intervals. (Explanation: Use if-elif-else statements to control the state transitions in a loop.)
- Rock-Paper-Scissors (Enhanced): Write a program that plays rock-paper-scissors against the user. Include validation for invalid user input. (Explanation: Use if-elif-else statements for game logic and handle invalid user choices.)
- List Sum: Write a program that takes a list of numbers as input and calculates the sum of all elements using a for loop.
- List Statistics: Write a program that takes a list of numbers as input, calculates the average, minimum, and maximum values, and prints them. Use a for loop to iterate through the list.
- Multiplication Table: Write a program that prints the multiplication table for a given number up to a specified limit using nested for loops.
- String Reversal (Enhanced): Write a program that takes a string as input and prints its reversed version using a for loop. Handle empty strings and strings with spaces. (Explanation: Use string slicing or string methods for efficient reversal.)
- Palindrome Checker: Write a program that takes a word or phrase as input and checks if it's a palindrome (reads the same backward and forward). Use a for loop to compare characters.
- Guessing Game: Write a program that generates a random number and asks the user to guess it. Use a while loop to keep prompting until the user guesses correctly. Limit the number of guesses.
- Password Validation (Enhanced): Write a program that prompts the user to enter a password. Use a while loop to enforce a minimum password length, specific character requirements (uppercase, lowercase, numbers, symbols), and a maximum number of attempts.
- Coin Toss Simulation (Enhanced): Write a program that simulates tossing a coin (heads or tails) a specified number of times using a while loop. Calculate the frequency of heads and tails, and display a bar chart using libraries like matplotlib (optional).
- Number Guessing Game (Multiple Players):
This question builds on the guessing game concept but adds complexity for multiple players.
- Use a list to store player names.
- Generate a random number.
- Implement a loop to iterate through players.
- Inside the loop: Use a while loop to allow each player to guess until correct or a maximum number of attempts is reached. Use if statements to check guesses and provide feedback. If a player guesses correctly, break out of the inner loop and declare them the winner.
- If no player guesses correctly after all attempts, announce a draw.
20. File line statistics :
This question involves reading a text file line by line and calculating statistics.
- Use the open function to open a text file in read mode.
- Initialize variables to store line count, word count, and character count.
- Implement a for loop to iterate over each line in the file: Use string methods like split to count words in each line. Update the total line count, word count, and character count.
- After the loop, print the calculated statistics (number of lines, words, and characters).
These questions will test your ability to combine branching and looping concepts while adding complexity. Remember to explain your thought process during the interview to showcase your problem-solving skills.