Thursday, February 29, 2024

 Project -2 : Lets Play Rock(R) , Paper(P) and Scicessors(S) Game



So far you have learned
  • input and output,
  • if/elif/else statements,
  • basic mathematics,
  •  casting as float and int.
For this version, you have two players. Player 1 and Player 2.
You will need to create if statements (and probably nesting) to decide who has won, lost or if the game is a tie.
Make it fun and add emojis or epic comments as your players battle it out.
Keep it simple for you. Don't expect the user to type in the words rock, paper, scissors. Instead, encourage them to use R, P, or S. 

Version -1

print("Lets Play Rock(R) , Paper(P) and Scicessors(S)")
print()
player1= input ("player1 choose between R , P & S: ")
player2= input ("player2 choose between R , P & S: ")
if player1 == player2 :
print ("it is a tie")
elif player1 == "R" and player2 == "P":
print("player2 is winner")
elif player1 == "R" and player2 == "S":
print("player1 is winner")
elif player1 == "P" and player2 == "S":
print("player2 is winner")
elif player1 == "P" and player2 == "R":
print("player1 is winner")
elif player1 == "S" and player2 == "R":
print("player2 is winner")
elif player1 == "S" and player2 == "P":
print("player1 is winner")
else:
print("Entered wrong letter")

Version-2

print("E P I C 🪨 📄 ✂️ B A T T L E ")
print()
print("Select your move (R, P or S)")
print()
player1Move = input("Player 1 > ")
print()
player2Move = input("Player 2 > ")
print()
if player1Move=="R":
if player2Move=="R":
print("You both picked Rock, draw!")
elif player2Move=="S":
print("Player1 smashed Player2's Scissors into dust with their Rock!")
elif player2Move=="P":
print("Player1's Rock is smothered by Player2's Paper!")
else:
print("Invalid Move Player 2!")
elif player1Move=="P":
if player2Move=="R":
print("Player2's Rock is smothered by Player1's Paper!")
elif player2Move=="S":
print("Player1's Paper is cut into tiny pieces by Player2's Scissors!")
elif player2Move=="P":
print("Two bits of paper flap at each other. Dissapointing. Draw.")
else:
print("Invalid Move Player 2!")
elif player1Move=="S":
if player2Move=="R":
print("Player 2's Rock makes metal-dust out of Player1's Scissors")
elif player2Move=="S":
print("Ka-Shing! Scissors bounce off each other like a dodgy sword fight! Draw.")
elif player2Move=="P":
print("Player1's Scissors make confetti out of Player2's paper!")
else:
print("Invalid Move Player 2!")
else:
print("Invalid Move Player 1!")

 First simple Project - Grade Generator using python with basic understanding of coding ( if , else , print statement ,basic maths)


Giving a grade like A+ , A- , B, C, D .... as per the student obtained in an Exam out of total marks. You have to calculate the percentage and print it with the grade that the student has got.




print("Exam Grade Calculator")
subj= input ("Name of the exam:")
if subj == "cs" :
maxscore = int(input("Max possible score:"))
urscore= int(input("what is your score:"))
percentage = int((urscore/maxscore)*100)
print(percentage)
if percentage >= 90:
print("you got",percentage,"% which is a A+")
    elif percentage >= 80:
       print("you got",percentage,"% which is a A-")
    elif percentage >= 70:
       print("you got",percentage,"% which is a B")
     elif percentage >= 60:
       print("you got",percentage,"% which is a C")
    elif percentage >= 50:
       print("you got",percentage,"% which is a D")
    elif percentage >= 40:
       print("you got",percentage,"%which is a E")
    else:
       print("you got",percentage," % which is a F")
else:
       print("we dont deal with the subject")

 

A little bit of math for Python


So far we have introduced the computer to two types of numbers:
float: numbers with a decimal
int:    whole numbers

Copy this code and have a go with trying the different mathematical symbols.

adding = 4 + 3
print(adding)

subtraction = 8 - 9
print(subtraction)

multiplication = 4 * 32
print(multiplication)

division = 50 / 5
print(division)

# a number raised to the power of some number
# in this example we raise 5 to the power of 2
squared = 5**2
print(squared)

# remainder of a division
modulo = 15 % 4
print(modulo)

# whole number division
divisor = 15 // 2
print(divisor)

Lets get into coding again :

How many seconds are in a year?

tSeconds = int(input("1 min in Sec=:"))
tMinutes = int(input("1 hour in Minutes=:"))
tHours = int(input("1 Day in Hours=:" ))
#tDays = int(input("1 year in Days:"))
tYear = int(input("which year it is"))
# lets check for the leap year
if tYear % 4 == 0:
tDays = 366
Totalsecs = tDays*tHours*tMinutes*tSeconds
print("total seconds in year =",Totalsecs)
else:
tDays = 365
Totalsecs = tDays*tHours*tMinutes*tSeconds
print("total seconds in year =",Totalsecs)

Wednesday, February 28, 2024

 

Casting in If statement and using int & float

If statements support more than ==. They support inequality symbols as well. Remember those <, >, and = signs you used in math way back . 

# equal
5 == 5

# not equal
3 ! = 5

# greater than
5 > 3

# greater than or equal to
5 >= 3

# less than
3 < 5

# less than or equal to
3 <= 5

This is because the way input works behind the scenes is it always assumes what you are typing is text (or a string) and gets stored as a variable in " ".

Casting is where we explicitly tell the computer that what we are typing is a number and not a letter.


The code below is saying any score greater than 100,000 is a winner. Anything less, try again.

myScore = input("Your score: ")
if myScore > 100000:
  print("Winner!")
else:
  print("Try again ")



Let's add int

There are two types of numbers the computer will recognize:
  • int whole number (ex: 42)
  • float any number with a decimal (ex: 1.81)
int

To change "your score" to a number, we need to add int in front of the input and place the entire input in ()

Update your code to look like this:

myScore = int(input("Your score: "))
if myScore > 100000:
  print("Winner!")
else:
  print("Try again ")

The way the computer will read this code is by starting with what is in brackets first ("your score"). The computer thinks this is text because of the "". When we add int, we are telling the computer, "This is not text. Please convert this to a whole number." Now the variable, myScore will store the answer as a number.

Let's add float

You would do the exact same thing, except using float for a decimal number. In the code below, I want to find pi to 3 decimal places.

myPi = float(input("What is Pi to 3dp? "))
if myPi == 3.142 :
  print("Exactly!")
else:
  print("Try again ")

We are casting that input as a float which means we are expecting a decimal number. The code will not crash if we put a . and then numbers after it to signify a decimal number.




code for Generation Generator :- 

print("Generation Identifier")
userBorn = int(input("Which year were you born:"))
if userBorn >= 1883 and userBorn <=1900 :
  print("Lost Generation")
elif userBorn >= 1901 and userBorn <=1927 :
  print("Greatest Generation")
elif userBorn >= 1928 and userBorn <= 1945 :
   print("silent Generation")
elif userBorn >= 1946 and userBorn <= 1964 :
   print("Baby Boomers")
elif userBorn >= 1965 and userBorn <= 1980 :
   print("Generation X")
elif userBorn >= 1981 and userBorn <= 1996 : 
   print("Millenials")
elif userBorn >= 1997 and userBorn <= 2012 :
   print("Generation Z")
else:
   print("Generation alpha")




 

Nesting in if statement

Nesting is where we put an if statement within an if statement using the power of indenting. The second if statement within the first if statement must be indented and its print statement needs to be indented one more time.

Here is code using Nesting :- 

tvShow = input("What is your favorite tv show? ")
if tvShow == "peppa pig":
  print("Ugh, why?")
  faveCharacter = input("Who is your favorite character? ")
  if faveCharacter == "daddy pig":
    print("Right answer")
  else:
    print("Nah, Daddy Pig's the greatest")
elif tvShow == "paw patrol":
  print("Aww, sad times")
else:
  print("Yeah, that's cool and all…") 



Today's focus is using all the skills you have learned so far:
  • input and output
  • concatenation
  • if statements
  • nested if statements

print("Wholesome Positivity machine")
userName = input("Who are you?:")
if userName == "appu" or userName == "angshu" or userName == "rana":
  print("Good morning",userName)
  userWant= input("What do you want to achieve:")
  print("That is Good to know that You",userWant)
  userRating=input("On a scale of 1-10 how do you feel today:")
  if userRating == "5" or userRating =="6" or userRating =="7" or userRating =="8" or userRating =="9" or userRating =="10":
    print ("It is pretty good today for you")
    print("Hey",userName,"keep your chin up!Today you are going to Teach people to code! in the most amazing way")
  elif userRating == "1" or userRating =="2" or userRating =="3" or userRating =="4" :
    print("Boost yourself to be more energetic .. I know one day you can win the world.")
else:
  print("we dont know you")

If Statements

 

If Statements

These statements are a bit like asking a question. You are telling the computer: if something is true, then do this specific block of code. Double equals (==) is asking the computer to compare if these two things are exactly the same.

In the code below, I am asking if the variable myName is the same as the string Dravid

myName = input("What's your name?: ")
if myName == "Dravid":   

But that doesn't print anything?

To create a print statement related to the input from the if statement, you must go to the next line and indent once.

An Example as a code  :- 

myName = input("What's your name?: ")
if myName == "Dravid":
  print("Welcome Dude!")   

What is else?

If the condition is not met with the if statement, then we want the computer to do the else part instead. Likewise, if the condition is met in the if statement, then the else bit is ignored by the computer. The else statement must be the first thing unindented after the if statement and in line with it.

myName = input("What's your name?: ")
if myName == "Dravid":
 print("Welcome Dude!")
 print("You're just the baldest dude I've ever seen")
else:
 print("Who on earth are you?!")  

What the elif is this?

The elif command (which stands for 'elseif') allows you to ask 2, 3, 4 or 142 questions using the same input! This command must be in a certain place. You can have as many elif statements as you want, but they must go in between if and else and have the same indentation. The print statements in your elif command need to line up with the indent of the other print statements.

An Example as a code  :- 
print("Secure login into Rude Rows")
userName = input("Tell me your Username:")
password =  input("Put your password here:")
if userName == "Ruderows" and password== "abcd" :
   print("Hey there",userName)
elif userName == "suman"  and password== "efgh":
  print("Hey there",userName)
elif userName == "biman" and password== "ijkl":
  print("Hey there",userName)
else :
  print("Go away")

 

Concatenate more than one input variable including other print function content.

All it really means is combine text (remember, text is called a string) and variables together into single sentences!

Here is the code to concatenate .

myName = input("What's your name? ")
myLunch = input("What are you having for lunch? ")
print(myName, "is going to be chowing down on", myLunch, "very soon!")

  • It turns out print has a super-power. We can give it as many different things to print as we want. All we need to do is put a comma( ,) between every different thing in the ().



 

Taking user input

Let's take a look at the input command and how that works. Input is when the user gives information to the computer.


It's very similar to the print command, except that it'll show the message in the console then wait until the user has typed something into the console and pressed enter. 

Let's get your hands dirty with the below code :- 

myName = input("What is your name ?:  ")
myFood = input("What is your food ?:  ")
myMusic= input("what is your fav music?:")
myLocation = input("where do u live?:")

print("You are")
print(myName)
print("You are probably hungry for")
print(myFood)
print("You must heard of ")
print(myMusic)
print("Living in ")
print(myLocation)

output  /Example 

What is your name ?:  Annat
What is your food ?:  mango
what is your fav music?: Trans
where do u live?: Singapore

You are
Annat
You are probably hungry for
 mango
You must heard of 
Trans
Living in 
Singapore

PS- bold words are input words given by the user.
Here in this above code, when we are taking an input as "what is your name? : " with the input function then automatically it is looking for a name in the console and when you have give the name it will be stored in the "myName" variable. when we call the "myName" variable with another print function then it will print the answer of input function that is given by you.

What is a variable?
input asks for something, takes it, but then has nowhere to put it. We can change that with a variable which is a value that we can use to name and store data. (Remember, David's box for David's phone?)






Naming variables
You can give a variable any name you want, but you can't use spaces. 
You can use:  
  • underscores_between_words
  • camelCaseToMakeItEasierToRead

Printing a Variable

You can print your variable using print and the name you used for your variable in your input command. Remember the three variables we just created: myName , myFood, myMusic
In your code you can now print 'name' by using print(myName) or 'Food' by using print(myFood).











Tuesday, February 27, 2024

 Writing your first Python program (Hello World!).


Let's start with some simple code to get a simple output (the information the program gives to the user).

print("Hello World!")

output
Hello World!

You just learned your first command: the print statement. It says "Print out whatever's in my brackets". The print statement is how you get your program to put messages in the console.

  • The " " (quotes) are used to tell the command that you're putting text in there (any text you want)
  • A bunch of text (or whatever you put in quotes) is called a string.

Multiple Print Statements

Here is what multiple print statements looks like. 

print("Well we")
print("just use more lines")
print("of code")

output
Well we
just use more lines
of code


Use the triple quote """ if you want to write a big chunk of text with gaps or line breaks. 

print("""Anything that starts
with three quotes, and ends
in three quotes can span
many lines and even contain " symbols
within it without freaking anything out!""")

Output
Anything that starts
with three quotes, and ends
in three quotes can span
many lines and even contain " symbols
within it without freaking anything out!




 Overview of Python: History and Features


History: Python is a high-level, interpreted programming language created by Guido van Rossum and first released in 1991. The language was designed with an emphasis on simplicity and readability, aiming to provide a clear and concise syntax that promotes code readability and maintainability. Python's development was heavily influenced by other programming languages like ABC, Modula-3, and C.

Key milestones in Python's history include:

  • Python 1.0 (1994): The first official release of Python.
  • Python 2.0 (2000): Introduced list comprehensions, garbage collection, and Unicode support.
  • Python 3.0 (2008): A major revision of the language that introduced backward-incompatible changes to improve clarity and consistency.

Python has since seen widespread adoption in various fields, including web development, data analysis, scientific computing, artificial intelligence, and automation.

Features:

1. Readability: Python's syntax is designed to be clear and easy to read, emphasizing the use of indentation and whitespace to define code blocks, rather than relying on curly braces or keywords.

2. Simplicity: Python prioritizes simplicity and ease of use, making it accessible to beginners while still powerful enough for advanced users. Its minimalist syntax reduces the amount of code needed to express concepts compared to other languages.

3. Dynamically Typed: Python is dynamically typed, meaning variable types are inferred at runtime rather than explicitly declared. This feature allows for more flexibility and rapid development but may require additional testing to catch type-related errors.

4. Interpreted: Python is an interpreted language, which means that code is executed line by line by an interpreter rather than being compiled into machine code beforehand. This makes development and debugging faster but can result in slower execution speed compared to compiled languages.

5. High-level: Python provides built-in data structures and abstractions that simplify programming tasks, allowing developers to focus on solving problems rather than managing memory or low-level details.

6. Object-oriented: Python supports object-oriented programming (OOP) principles, including encapsulation, inheritance, and polymorphism. Everything in Python is an object, making it easy to organize and manipulate code into reusable components.

7. Extensive Standard Library: Python comes with a comprehensive standard library that includes modules and functions for performing common tasks such as file I/O, networking, regular expressions, and more. This library reduces the need for external dependencies and facilitates rapid development.

8. Cross-platform: Python is platform-independent, meaning that Python code can run on various operating systems without modification. This portability makes it an ideal choice for developing cross-platform applications.

Overall, Python's combination of simplicity, readability, and versatility has made it one of the most popular programming languages worldwide, used by developers in a wide range of industries and domains.

Thursday, February 22, 2024

 A day wise course curriculum to start python from scratch.


Day-by-day curriculum for learning Python from scratch. Each day builds upon the previous one, gradually introducing new concepts and reinforcing earlier ones.


Day 1: Introduction to Python

  • 1.Overview of Python: history, features, and applications.
  • 2.Setting up Python environment (installing Python, IDEs like PyCharm or Jupyter Notebook).
  • 3.Writing your first Python program (Hello World!).
  • 4.Basic data types: integers, floats, strings, booleans.
  • 5.Basic operations: arithmetic, string concatenation, comparison.
  • 6.Using print() function to output text.

Day 2: Variables and Data Structures

  • 1.Declaring variables and variable naming conventions.
  • 2.Dynamic typing in Python.
  • 3.Lists: creating, accessing elements, list methods.
  • 4.Tuples: creating, accessing elements (immutable sequences).
  • 5.Dictionaries: creating, accessing elements by key, dictionary methods.

Day 3: Control Flow

  • 1.Conditional statements (if, elif, else).
  • 2.Using logical operators (and, or, not).
  • 3.Loops: for loops, while loops.
  • 4.Loop control statements: break, continue.
  • 5.Iterating through lists and dictionaries.

Day 4: Functions

  • 1.Defining and calling functions.
  • 2.Function parameters and arguments.
  • 3.Return statement and returning values from functions.
  • 4.Scope of variables: local vs global.
  • 5.Built-in functions vs user-defined functions.

Day 5: More on Functions and Modules

  • 1.Default arguments and keyword arguments.
  • 2.Lambda functions.
  • 3.Importing modules and using functions from them.
  • 4.Creating your own modules.
  • 5.Documenting functions using docstrings.

Day 6: File Handling

  • 1.Opening and closing files.
  • 2.Reading from and writing to files.
  • 3.File modes: read, write, append.
  • 4.Working with text files.
  • 5.Handling exceptions using try-except blocks.

Day 7: Object-Oriented Programming Basics

  • 1.Introduction to object-oriented programming (OOP).
  • 2.Classes and objects.
  • 3.Attributes and methods.
  • 4.Constructors and destructors.
  • 5.Inheritance and polymorphism.

Day 8: More on OOP

  • 1.Encapsulation and access modifiers.
  • 2.Class and static methods.
  • 3.Method overriding and method overloading.
  • 4.Special methods (dunder/magic methods).
  • 5.Implementing OOP concepts in Python.

Day 9: Error Handling and Debugging

  • 1.Understanding exceptions and error types.
  • 2.Using try-except blocks for error handling.
  • 3.Raising exceptions with raise.
  • 4.Debugging techniques: print debugging, using debuggers.
  • 5.Handling errors gracefully in your programs.

Day 10: Final Projects and Review

  • 1.Work on a small project incorporating concepts learned.
  • 2.Review all concepts covered in the past days.
  • 3.Practice problem-solving on platforms like LeetCode, HackerRank, or Codecademy.
  • 4.Seek help or clarification on any challenging topics.
  • 5.Plan your next steps in Python learning.
We can adjust the pace based on our learning speed and schedule. It is not mandatory and it is not suggested to read the above all in 10 days . we may take 100 days to learn the basic python before stepping into the more advanced topics such as web development, data science, machine learning, or automation based on our interests and career goals.




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