Docsity

Python Programming Codes you should try right now., Study notes of Computer science

Toggle sidebar
bg1
Python programs you should try right now.
Each of these Python programs helps beginners:
1. Hello, World!
Hello, World!
Calculator
Guess the Number Game
Mad Libs Generator
Fibonacci Sequence
Palindrome Checker
Factorial Calculator
Simple To-Do List
Temperature Converter
Rock, Paper, Scissors Game
Number Guessing Game (Computer vs. Player)
Basic Web Scraper
File Encryption/Decryption
Word Counter
Password Generator
Hangman Game
Basic Calculator with GUI (using tkinter)
Tic-Tac-Toe Game
Basic Data Analysis
Random Quote Generator
Gain hands-on coding experience.
Reinforce fundamental programming concepts.
Develop problem-solving skills.
Encourage creativity.
See real-world relevance.
Introduce libraries and APIs.
Make learning engaging and fun.
Serve as a foundation for more advanced projects.
Introduction to Python programming.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Python Programming Codes you should try right now. and more Study notes Computer science in PDF only on Docsity!

Python programs you should try right now.

Each of these Python programs helps beginners:

1. Hello, World!

Hello, World!

Calculator

Guess the Number Game

Mad Libs Generator

Fibonacci Sequence

Palindrome Checker

Factorial Calculator

Simple To-Do List

Temperature Converter

Rock, Paper, Scissors Game

Number Guessing Game (Computer vs. Player)

Basic Web Scraper

File Encryption/Decryption

Word Counter

Password Generator

Hangman Game

Basic Calculator with GUI (using tkinter)

Tic-Tac-Toe Game

Basic Data Analysis

Random Quote Generator

Gain hands-on coding experience.

Reinforce fundamental programming concepts.

Develop problem-solving skills.

Encourage creativity.

See real-world relevance.

Introduce libraries and APIs.

Make learning engaging and fun.

Serve as a foundation for more advanced projects.

Introduction to Python programming.

How it WORKS?

Source CODE.

print("Hello, World!")

2. Calculator How it WORKS?

Source CODE.

num1 = float(input("Enter the first number: ")) operator = input("Enter an operator (+, -, , /): ") num2 = float(input("Enter the second number: ")) if operator == "+": result = num1 + num elif operator == "-": result = num1 - num elif operator == "": result = num1 * num elif operator == "/": if num2 == 0: result = "Division by zero is not allowed" else: result = num1 / num else: result = "Invalid operator" print("Result:", result) Demonstrates the basic syntax and the print() function. The print() function displays the text "Hello, World!" on the screen. Teaches basic arithmetic operations in Python. Demonstrates user input and conditional statements. Takes user input for two numbers and an operator (+, -, *, /). Uses if, elif, and else statements to perform the selected operation and print the result.

verb = input("Enter a verb: ") adjective = input("Enter an adjective: ") story = f"The {adjective} {noun} {verb} over the lazy dog." print(story)

5. Fibonacci Sequence. How it WORKS?

Source CODE.

a, b = 0, 1 n = 10 # Number of terms to generate for _ in range(n): print(a, end=" ") a, b = b, a + b

6. Palindrome Checker. How it WORKS?

Source CODE.

text = input("Enter a word or phrase: ") text = text.replace(" ", "").lower() is_palindrome = text == text[::-1] if is_palindrome: print("It's a palindrome!") else: Practice loops and understand mathematical concepts. Generate and print the Fibonacci sequence, a series of numbers. The program uses a for loop to calculate and print the Fibonacci sequence up to a specified number of terms. Practice string manipulation. Check if a word or phrase is a palindrome (reads the same forwards and backward). The program takes a user-inputted string, removes spaces, converts it to lowercase, and checks if it's the same when reversed.

print("It's not a palindrome.")

7. Factorial Calculator. How it WORKS?

Source CODE.

def factorial(n): result = 1 for i in range(1, n + 1): result *= i return result

Example usage: Calculate factorial of 5

print(factorial(5))

8. Simple To-Do List. How it WORKS?

Source CODE.

def todo_list(): tasks = [] while True: print("1. Add Task") print("2. Remove Task") print("3. Show Tasks") print("4. Quit") Practice loops and mathematical calculations. Calculate the factorial of a given number. The program defines a function factorial(n) to calculate the factorial of a number n. It uses a for loop to multiply all positive integers from 1 to n and returns the result. Introduction to lists and basic list operations. Add, remove, and display tasks in a simple to-do list. The program defines a function todo_list() that manages a to-do list using a list to store tasks. Users can add, remove, and display tasks using a simple menu.

elif choice == 'F': fahrenheit = float(input("Enter temperature in Fahrenheit: ")) celsius = (fahrenheit - 32) * 5/ print(f"{fahrenheit}°F is equal to {celsius}°C") else: print("Invalid choice. Please enter 'C' or 'F'.")

Call the function to execute it

temperature_converter()

10. Rock, Paper, Scissors Game. How it WORKS?

Source CODE.

import random def rock_paper_scissors(): choices = ["rock", "paper", "scissors"] computer_choice = random.choice(choices) user_choice = input("Choose rock, paper, or scissors: ").lower() if user_choice not in choices: print("Invalid choice. Please choose rock, paper, or scissors.") return print(f"Computer chose {computer_choice}") if user_choice == computer_choice: print("It's a tie!") elif ( (user_choice == "rock" and computer_choice == "scissors") or (user_choice == "scissors" and computer_choice == "paper") or (user_choice == "paper" and computer_choice == "rock") ): Fun introduction to conditional statements and random number generation. Create a simple text-based game where the user plays against the computer. The program generates a random choice for the computer (rock, paper, or scissors) and asks the user for their choice. It uses conditional statements to determine the winner.

print("You win!") else: print("Computer wins!")

Call the function to execute the game

rock_paper_scissors()

11. Number Guessing Game (Computer vs. Player). How it WORKS?

Source CODE.

import random def number_guessing_game(): print("Think of a number between 1 and 100 and I'll try to guess it.") lower_bound, upper_bound = 1, 100 attempts = 0 while lower_bound <= upper_bound: guess = (lower_bound + upper_bound) // 2 print(f"My guess is {guess}") attempts += 1 user_response = input("Is it too low (L), too high (H), or correct (C)? ").lower() if user_response == 'c': print(f"I guessed it in {attempts} attempts!") break elif user_response == 'l': lower_bound = guess + 1 elif user_response == 'h': upper_bound = guess - 1 else: print("Invalid response. Please enter 'L', 'H', or 'C'.") Practice using loops, random number generation, and conditional statements. Implement a simple text-based number guessing game where the computer guesses the player's number. The program generates a random secret number and asks the user to think of a number. It uses a binary search algorithm to guess the number eciently.

Source CODE.

def encrypt(text, key): encrypted_text = "" for char in text: encrypted_char = chr(ord(char) + key) encrypted_text += encrypted_char return encrypted_text def decrypt(text, key): decrypted_text = "" for char in text: decrypted_char = chr(ord(char) - key) decrypted_text += decrypted_char return decrypted_text def file_encryption_decryption(input_file, output_file, key): with open(input_file, 'r') as file: text = file.read() encrypted_text = encrypt(text, key) with open(output_file, 'w') as file: file.write(encrypted_text)

Example usage:

file_encryption_decryption('input.txt', 'encrypted.txt', 3) # Encrypt file_encryption_decryption('encrypted.txt', 'decrypted.txt', 3) # Decrypt

14. Word Counter. How it WORKS?

Source CODE.

To decrypt, it reads the encrypted content and decrypts it, saving the original text to a new file. Practice working with text data and counting. Create a program that counts the number of words and characters in a given text. The program takes user input or reads text from a file. It counts the number of words and characters (including spaces).

def word_counter(text): words = text.split() word_count = len(words) char_count = len(text) return word_count, char_count

Example usage:

text = "This is a sample sentence for word counting." word_count, char_count = word_counter(text) print(f"Words: {word_count}, Characters: {char_count}")

15. Password Generator. How it WORKS?

Source CODE.

import random import string def generate_password(length): characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for _ in range(length)) return password

Example usage: Generate a password of length 12

password = generate_password(12) print("Generated Password:", password)

16. Hangman Game. How it WORKS? Learn how to generate strong passwords. Practice using randomization and character manipulation. The program defines a function to generate a random password of a specified length. It includes a mix of uppercase letters, lowercase letters, numbers, and special characters. Create a fun text-based game and practice conditional statements and loops. Implement a basic version of the classic hangman game.

hangman()

17. Basic Calculator with GUI (using tkinter). How it WORKS?

Source CODE.

import tkinter as tk def on_button_click(event): text = event.widget.cget("text") if text == "=": try: result = eval(screen.get()) screen.set(result) except Exception as e: screen.set("Error") elif text == "C": screen.set("") else: screen.set(screen.get() + text)

Create a basic window

root = tk.Tk() root.geometry("400x550") root.title("Calculator")

Create a display screen

screen = tk.StringVar() display = tk.Entry(root, textvar=screen, font="lucida 20 bold", bd=10, insertwidth=4, width=14, justify="right") display.grid(row=0, column=0, columnspan=4) Introduction to creating graphical user interfaces (GUIs) with Python. Build a simple calculator application with a graphical interface using the tkinter library. The program uses the tkinter library to create a basic calculator with buttons for numbers and operations. It handles user input and performs calculations.

Create calculator buttons

buttons = [ '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', 'C', '=', '+' ] row_val = 1 col_val = 0 for button in buttons: tk.Button(root, text=button, padx=20, pady=20, font="lucida 15 bold", bd=8, command=lambda x=button: on_button_click(x) if x != "=" else on_button_click(x)).grid(row=row_val, column=col_val) col_val += 1 if col_val > 3: col_val = 0 row_val += 1

Run the GUI

root.mainloop()

18. Image Resizer. How it WORKS? Note: To use this program, you'll need to install the Pillow library.

Source CODE.

from PIL import Image def resize_image(input_file, output_file, width, height): try: img = Image.open(input_file) img = img.resize((width, height)) Introduction to image processing. Resize images to a specified width and height using the Pillow library (PIL). The program uses the Pillow library to open an image file. It resizes the image to the specified width and height and saves the resized image.

Source CODE.

def currency_converter(amount, from_currency, to_currency): exchange_rates = { 'usd_to_eur': 0.85, 'usd_to_gbp': 0.75, 'usd_to_jpy': 110.38,

Add more exchange rates as needed

} if from_currency == to_currency: return amount conversion_rate_key = f'{from_currency}to{to_currency}' if conversion_rate_key in exchange_rates: conversion_rate = exchange_rates[conversion_rate_key] converted_amount = amount * conversion_rate return converted_amount else: return None

Example usage: Convert $100 to Euro (EUR)

amount = 100 from_currency = 'usd' to_currency = 'eur' converted_amount = currency_converter(amount, from_currency, to_currency) print(f'{amount} {from_currency.upper()} is equal to {converted_amount} {to_currency.upper()}') It takes user input for the amount and currencies to convert and displays the converted amount.