Thursday, March 14, 2024

Argunents using in Print function

 Some Argunents using in Print function 

End inside print function : You can already create print statements like a boss, but there are a few things you can do to make them easier.Let's add a few secret second arguments to the print statement and see what happens.

By default, at the end of every print statement, the computer clicks 'enter'.

How a range of numbers shows each number on a new line...
for i in range(0, 100):
  print(i)

Here output as 0,1,2,3,....99 will be printed in a vertical manner .

Add a space
Let's tweak that code and see if we can get it to print with a space between each number instead of a new line. What do you notice?
for i in range(0, 100):
  print(i, end=" ")

Here output as 0,1,2,3,....99 will be printed in a horizontal manner with a space in between numbers.

Add a space and comma 
What if we want to add a comma and a space? Let's try it by adding , to our argument.
for i in range(0, 100):
  print(i, end=", ")

Here output as 0,1,2,3,....99

Add a new line, tab, or vertical tab
What happens if you add these different options in your second argument? Play around with these options below and see what they do:

#new line
for i in range(0, 100):
  print(i, end="\n")

#tab indent
for i in range(0, 100):
  print(i, end="\t")

#vertical tab
for i in range(0, 100):
  print(i, end="\v")


We can turn the colors on and off different bits of the code by using end. Remove the previous code from your main.py file and try this out.
print("If you put")
print("\033[33m", end="") #yellow
print("nothing as the")
print("\033[35m", end="") #purple
print("end character")
print("\033[32m", end="") #green
print("then you don't")
print("\033[0m", end="") #default
print("get odd gaps")

Let's concatenate that same print statement:

print("If you put", "\033[33m", "nothing as the", "\033[35m", "end character", "\033[32m", "then you don't", "\033[0m", "get odd gaps", end="")

Now you may notice that we are getting weird double spaces in between the different sections. Let's fix that!
sep Arguments 



Take this same code and change end to sep (short for separator) and add a space at the end of each string. What happens

print("If you put ", "\033[33m", "nothing as the ", "\033[35m", "end character ", "\033[32m", "then you don't ", "\033[0m", "get odd gaps ", sep="")

That GIANT white cursor
we could turn that off! It is just a sneaky print command.
import os, time
print('\033[?25l', end="")
for i in range(1, 101):
  print(i)
  time.sleep(0.2)
  os.system("clear")

Coding Challenge :
Write a subroutine that writes text in color. All it will do is print out the text in that color and turn the color back to normal when it's finished.
Control end and sep so there are not random symbols or spaces.

def newPrint(color,word):
  if color == "Red":
    print("\033[0;31m",word,sep="",end="")
  elif color == "pink":
    print("\033[0;34m",word,sep="",end="")
  elif color == "cyan":
    print("\033[0;36m",word,sep="",end="")
#return (color, word)

print("super Subroutine")
print("with my ",end="")
newPrint("Red","new Programme ")
newPrint("pink","I can just call red")

os,time Library

 

os,time Library
What is the os library?
It allows us to "talk" to the console. One of the most powerful things we can do with this library is allow it to clear the console.
The os library in Python provides a way of using operating system dependent functionality. It allows you to interact with the operating system in various ways, such as navigating file systems, accessing environment variables, and executing system commands. Here are some common functionalities provided by the os module:
File and Directory Operations: You can perform operations related to file and directory manipulation, such as creating, deleting, renaming, and checking existence of files and directories.
Operating System Information: You can retrieve information about the operating system, such as the name, environment variables, and working directory.
Process Management: You can interact with processes, such as launching new processes, terminating processes, and obtaining process IDs.
Path Manipulation: The os.path submodule provides functions for manipulating file paths in a platform-independent way, including joining paths, splitting paths, and getting the basename and directory name of a path.
Permissions and Ownership: You can set and retrieve file permissions and ownership information.
System Utilities: The os module also includes various system-related utilities, such as functions for executing shell commands, handling signals, and working with environment variables.

Import the os library


We can clear the code above by using the os.system function to 'clear' the console.

import os
print("Welcome")
print("to")
print("Python")

os.system("clear")

username = input("Username: ")

For this code, I want the program to say "Welcome to Python", delete that, and then ask for my username on a blank screen. Remove the previous code, add the code below and see what happens when you hit run!

But The console printed and cleared 'Welcome to Replit!' before I even had a chance to read it.

Time Library
We can import a second library by placing a , after the name of the first library.

import os, time

This library allows us to pause the execution of a program for a specific amount of time.


The time.sleep(1) function allows us to pause the program for the amount of seconds listed in the ().

Add this to your code before the program is cleared to pause the program for 1 second before displaying the username.

time.sleep(1)
os.system("clear")

Example - A simple example that demonstrates using the os and time libraries to create a program that displays the current date and time:

import os
import time

# Clear the console screen (for demonstration purposes)
os.system('cls' if os.name == 'nt' else 'clear')

# Get the current date and time
current_time = time.strftime("%Y-%m-%d %H:%M:%S")

# Display the current date and time
print("Current date and time:", current_time)

We use the os.system() function to clear the console screen. This step is optional and is done for demonstration purposes to ensure a clean output.
We use the time.strftime() function to format the current date and time according to the specified format string "%Y-%m-%d %H:%M:%S". This format represents the year, month, day, hour, minute, and second in a specific order.

Example - 
Play a song from this repl and build a menu to go with it. Make it look like an iPod!Use a while true loop to create a title for a music player.
Allow the user to select to play a song and use subroutine called 'play' when they select the song.
Give the user the option to exit the program.
The title should pop up and pause along with the menu options.
If the user chooses anything else, start again by clearing the screen.

from replit import audio
import os, time

def play():
  source = audio.play_file('audio.wav')
  source.paused = False # unpause the playback
  while True:
    stop_playback = int(input("Press 2 anytime to stop playback and go back to the menu : ")) # giving the user the option to stop playback
    if stop_playback == 2:
      source.paused = True # let's pause the file 
      return # let's go back from this play() subroutine
    else: 
      continue
  
while True:
  os.system("clear")
  print("🎵 MyPOD Music Player ")
  time.sleep(1)
  print("Press 1 to Play")
  time.sleep(1)
  print("Press 2 to Exit")
  time.sleep(1)
  print("Press anything else to see the menu again")
  userInput = int(input())
  if userInput == 1:
    print("Playing some proper tunes!")
    play()
  elif userInput == 2:
    exit()
  else :
    continue

Example - You will create a video game that creates a character's health and attack stats...along with an epic name for your character.
Write a subroutine that generates a character: first name and character type (human, imp, wizard, elf, etc.).
Write a subroutine that multiplies a bunch of random dice rolls together to generate the character's health stats. Use this formula: (six_sided_roll*twelve_sided_roll)/2)+10
Write a second subroutine that multiplies a bunch of random dice rolls together to generate the character's strength stats. Use this formula:(six_sided_roll*twelve_sided_roll)/2)+12
Present the data in a menu with time.sleep and os.system("clear") to make it appealing.
Wrap it in a loop so the user has the option to create another character.

import os,time
def character_health(charater_name):
  import random
  six_sided_roll= random.randint(1,6)
  twelve_sided_roll= random.randint(1,12)
  health_stat= ((six_sided_roll*twelve_sided_roll)/2)+10
  return(health_stat)


def character_strenth(charater_name):
  import random
  six_sided_roll= random.randint(1,6)
  twelve_sided_roll= random.randint(1,12)
  strength_stat= ((six_sided_roll*twelve_sided_roll)/2)+10
  return(strength_stat) 

while True:
  os.system("clear")
  print("Character Builder")
  print("")
  character_name = input("Name of your legend:")
  character_type = input("Character Type(Human,Elf,Wizard,Orc):")
  print()
  print(character_name)
  print("Health:",character_health(character_name))
  print("Strength:",character_strenth(character_name))
  print()
  print("May your name go down in legend")
  print()
  again_no= input("want it (yes/no):")
  if again_no == "yes":
   continue
  else:
    break

More with Subroutine

 More with Subroutine

Parameters 

Let's put those subroutines to better use by sending them information using parameters and making them do different things based on different inputs.

If you change the ingredients in a recipe, you get a different kind of cake. Let's do that with subroutines.

In a subroutine, the () are for the argument (FYI argument is another word for parameter). These are the pieces of information we pass to the code. These can be variable names that are made up for the first time within the argument ().

Here is a simple subroutine that uses the argument to take in the name of an ingredient and expresses its opinion (quite strongly) about the ingredient that the user typed. For example, 'chocolate' is amazing, but 'broccoli'...not so much.

def whichCake(ingredient):
  if ingredient == "chocolate":
    print("Mmm, chocolate cake is amazing")
  elif ingredient == "broccoli":
    print("You what mate?!")
  else: 
    print("Yeah, that's great I suppose...")   

Here in this above code , we have not called the subroutine yet.

How do we call the subroutine?
We call it in the same way as before. However, instead of leaving the () blank, we send the code a message.

What happens when you add this to the end of your code above?
whichCake("chocolate")

That's right. The variable 'ingredient' in the subroutine gets set to 'chocolate' and the output shows:

Adding More Arguments
We can have as many arguments as we want, separated by commas.


Now, this subroutine is expecting three arguments: ingredient, base, and coating:

def whichCake(ingredient, base, coating)

Let's update our code to now show all three arguments:
def whichCake(ingredient, base, coating):
  if ingredient == "chocolate":
    print("Mmm, chocolate cake is amazing")
  elif ingredient == "broccoli":
    print("You what mate?!")
  else: 
    print("Yeah, that's great I suppose...")
  print("So you want a", ingredient, "cake on a", base, "base with", coating, "on top?")

whichCake("carrot", "biscuit", "icing")

I could even ask the user to name an ingredient, base, and coating by adding:

def whichCake(ingredient, base, coating):
  if ingredient == "chocolate":
    print("Mmm, chocolate cake is amazing")
  elif ingredient == "broccoli":
    print("You what mate?!")
  else: 
    print("Yeah, that's great I suppose...")
  print("So you want a", ingredient, "cake on a", base, "base with", coating, "on top?")

userIngredient = input("Name an ingredient: ")
userBase = input("Name a type of base: ")
userCoating = input("Fave cake topping: ")
whichCake(userIngredient, userBase, userCoating)


Coding Challenge :
Create subroutines that will roll a dice with any number of sides (essentially as big of a number as you like). Write one subroutine with one parameter that allows us to call a function (such as rollDice).

Example:
Infinity Dice 🎲
How many sides?: 600
You rolled 532
Roll again? yes
You rolled 102
Roll again? no

def rolldice(sides):
  import random

  while True:
    roll_again= input("Roll Again:")
    if roll_again == "yes":
      dice_output=random.randint(1,sides)
      print("you rolled",dice_output)
      continue
    else :
      break
call_a_dice=int(input("your dice has  side of:"))
rolldice(call_a_dice)


Return Command
Let's go deeper into subroutines. Can they send information back to the main part of the program?

Let's do this with the return command



The return command sends some information back to the part of the code that called it. This means the function call is replaced with whatever was returned.

We saw this before with importing libraries and random numbers. We could use the random number wherever we wanted.

def add_numbers(num1, num2):
    sum = num1 + num2
    return sum


result = add_numbers(5, 3)
 print(result) # Output will be 8


let's consider an example of a function that calculates the average of a list of number

def calculate_average(numbers):
    total = sum(numbers)
    count = len(numbers)
    average = total / count
    return average

# Example usage:
scores = [75, 80, 90, 85, 95]
avg_score = calculate_average(scores)
print("Average score:", avg_score)

Example for OTP generation 

def pinPicker(number):
import random
pin = "" #this is the empty string
for i in range(number): #for loop shows defined amount of random numbers
pin += str(random.randint(0,9)) #we want a string of random numbers between 0-9
return pin
digits_of_pin= int(input("how manny digits",))
pinPicker(digits_of_pin)
myPin = pinPicker(digits_of_pin)
print(myPin)

Example for getting integers of set of any numbers as an input and average of the list of numbers :

def calculate_average(numbers):
    total = sum(numbers)
    count = len(numbers)
    average = total / count
    return average

# Taking inputs from the user
input_numbers = input("Enter numbers separated by spaces: ")
numbers_list = [int(num) for num in input_numbers.split()]

# Calculating average
avg_score = calculate_average(numbers_list)

# Printing the result
print("Average score:", avg_score)

Example - we want to take a list of integers as input from the user and filter out only the even numbers

# Taking inputs from the user
input_numbers = input("Enter numbers separated by spaces: ")

# Splitting the input string and converting to integers
numbers_list = [int(num) for num in input_numbers.split()]

# Filtering out even numbers using list comprehension
even_numbers = [num for num in numbers_list if num % 2 == 0]

# Printing the result
print("Even numbers:", even_numbers)

Example- calculates the area of a rectangle given its length and width.

def calculate_rectangle_area(length, width):
    area = length * width
    return area

# Example usage:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = calculate_rectangle_area(length, width)
print("The area of the rectangle is:", area)

Example- Take a list of numbers as input and returns the maximum value in the list. Here's how we can implement it:

def find_maximum(numbers):
    if not numbers:
        return None  # Return None if the list is empty
    max_value = numbers[0]  # Initialize max_value with the first element
    for num in numbers:
        if num > max_value:
            max_value = num
    return max_value

# Example usage:
input_numbers = input("Enter numbers separated by spaces: ")
numbers_list = [int(num) for num in input_numbers.split()]

max_value = find_maximum(numbers_list)
if max_value is not None:
    print("The maximum value is:", max_value)
else:
    print("The list is empty.")



Explanation:
def find_maximum(numbers):: This line defines a function named find_maximum that takes a list of numbers (numbers) as input. Inside the function, it iterates through the list to find the maximum value.
if not numbers:: This line checks if the list is empty. If it is, the function returns None because there is no maximum value to find in an empty list.
max_value = numbers[0]: This line initializes the variable max_value with the first element of the list, assuming it as the maximum value initially.
The for loop iterates over each number in the list. If a number is greater than the current maximum value (max_value), it updates max_value to that number.
return max_value: This line returns the maximum value found in the list back to the caller.
input_numbers = input("Enter numbers separated by spaces: "): This line prompts the user to enter numbers separated by spaces and reads the input as a string.
numbers_list = [int(num) for num in input_numbers.split()]: This line splits the input string into substrings based on whitespace, converts each substring to an integer using int(), and creates a list of these integers (numbers_list).
max_value = find_maximum(numbers_list): This line calls the find_maximum function with the provided list of numbers. It stores the returned maximum value in the variable max_value.
The final if statement checks if the max_value is not None (i.e., the list is not empty). If it's not None, it prints out the maximum value. Otherwise, it prints that the list is empty.


Example-takes a string as input and returns the count of vowels (a, e, i, o, u) in the string. Here's how we can implement it:
def count_vowels(input_string):
    vowels = "aeiou"
    count = 0
    for char in input_string:
        if char.lower() in vowels:
            count += 1
    return count

# Example usage:
input_string = input("Enter a string: ")
vowel_count = count_vowels(input_string)
print("Number of vowels:", vowel_count)


  2D Dictionaries Remember that dictionaries are very similar to lists, except that they store data as key:value pairs. The value is what it...