Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
94 views

Python

This document describes a Python program that implements the "Cow and Bull" guessing game. It includes functions to generate a random secret code, evaluate guesses by returning the number of "bulls" and "cows", and run the full game by allowing guesses, providing feedback, and determining a winner. The game generates a random 4-digit number with no repeats as the secret code and allows the player to make guesses, telling them the number of correct digits in the right vs wrong positions until they guess correctly or run out of attempts.

Uploaded by

Harshit1 Pareek
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

Python

This document describes a Python program that implements the "Cow and Bull" guessing game. It includes functions to generate a random secret code, evaluate guesses by returning the number of "bulls" and "cows", and run the full game by allowing guesses, providing feedback, and determining a winner. The game generates a random 4-digit number with no repeats as the secret code and allows the player to make guesses, telling them the number of correct digits in the right vs wrong positions until they guess correctly or run out of attempts.

Uploaded by

Harshit1 Pareek
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

SKITM&G, JAIPUR

DEPARTMENT OF CSE

PYTHON

Harish Minariya
22ESKCA038
CONTENTS
• Application for Python
• Features
• Python language introduction
• Python syntax & indentation
• Python string
• Python list
• Pythontuple
• Python dictionary
• Python operator
• Conditional statement
• Loops on python
• Variable,object,class
• Project
3

INTRODUCTION
• Python is a popular programming language. It was
created by Guido van Rossum, and released in 1991.
• It was designed with an emphasis on code readability,
and its syntax allows programmers to express their
concepts in fewer lines of code.
• Python is a programming language that lets you work
quickly and integrate systems more efficiently.
FEATURES
• Free and Open Source
• Easy to code
• Object-Oriented Language
• GUI Programming Support
• High-Level Language
• Large Community Support
• Python is a Portable language
• Python is an Integrated language
5

PYTHON STRING
STRING: Strings are generally a set of characters .Strings literals in
python are surrounded by either Single quotation marks, or double
quotation marks.
--'hello' is the same as "hello". String can be displayed literally with a
print() function.
Example: print('hello') or print(" hello") . Assign string to a variable: It is
done with the variable name followed by an equal sign and the string.
Example: a =" hello"
print(a)
Output: hello
6

PYTHON LIST
LIST : List is a collection which is ordered and changeable.
Allows duplicate members.
• In python, list are written with square bracket List items are
indexed, the first item has index [o] , the second item has
index [1] etc.
Mylist = ["apple", "banana", "cherry"]
7

PYTHON TUPLES
TUPLES: A tuple is a collection which is ordered and
unchangeable.
In python tuples are written with brackets.
Example mytuple = ("apple", "banana", "cherry")
Create a Tuple:
>>thistuple = ("apple", "banana", "cherry")
>>print(thistuple)
8

PYTHON DICTIONARY
DICTIONARY: A dictionary is a collection which is
unordered changeable and indexed.
• In python dictionaries are written with curly brackets, and
they have keys
and values.
Example: thisdict = { "brand": "Ford","Model":
"mustang","Year" : 1964}
9

PYTHON OPERATORS
Operators : Operators are used to perform mathmathical operation on variables
and values.
1 Airthmetic operators: It is used with numeric values to perform common
mathemathical operation. Addition (x+y),Subtraction (x-y), Multiplication
(x*y), Division (x/y), Modulus (x%y), Exponentiation(x**y), Floor
division(x//y).
2.Assignment operators: Assignment operators are used to assign the values to
variables.(=, += ==, *=, /= and so on...)
3. Comparison operators: It is used to compare the two values. (==, >, < >,
<=)
4. Logical Operators: Logical operators are used to combine conditional
statement. (and Returns true if both true, or Returns true If one statement is
true, not Returns False if the results is true)
5. Identity Operators: Identity operators are used to compare the objects, not if
they are equal, but if they are actually the same object, with the same memory
location: eg: 'is' and 'is not'
10

CONDITIONAL STATEMENT
Conditional statements (if, else, and elif) are fundamental programming
constructs that allow you to control the flow of your program based on
conditions that you specify. They provide a way to make decisions in your
program and execute differet code based on those decisions.
• IF STATEMENT : The if statement allows you to execute a block of code if
a certain condition is true. Here's the basic syntax:
if condition:
# code to execute if condition is true
• ELSE STATEMENT : The else statement allows you to execute a different
block of code if the if condition is False. Here's the basic syntax:
if condition:
# code to execute if condition is true
else:
# code to execute if condition is false
11

PYTHON LOOPS
LOOPS:Python has two primitive loop commands.
1 .while loops 2. for loops
while loop: with the while loop we can execute a set of statements as long as
is true.
Example: number = 5
sum=0
i=0
while (i < number):
sum = sum + I
i=i+1
print (sum)

for loops: a for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary
, a string).
12

VARIABLES, OBJECTS, AND CLASSES


VARIABLE:
A variable is a reference to a value stored in a computer's memory.
• Variables can be sorted into a variety of categories (or data types) such as numbers (int/float
etc), Boolean values (true/false), and sequences (strings, lists etc).
OBJECT :
An object is a collection of data from a computer's memory that can be manipulated.
• ALL VARIABLES ARE OBJECTS although some objects can be defined by data referred
to by multiple variables.
• Methods are the functions used to act on/alter an object's data. They describe what your
object can "do.“
CLASS :
• A class is a collection of objects who share the same set of variables/methods.
• The definition of the class provides a blueprint for all the objects within it (instances).
• Instances may share the same variables (color, size, shape, etc.), but they do NOT share the
same values for each variable (blue/red/pink, small/large, square/circular etc.)
COW AND BULL GAME
13

The "Cow and Bull" game is a word-based or number-based guessing game where one player (the codemaker) selects a secret
word or number, and the other player (the codebreaker) attempts to guess it within a certain number of attempts. In the context of
your Python script, it's a number-based version of the game.
How The Game Works:
14
1. *Secret Code Generation*:
- The codemaker generates a secret code, which is typically a 4-digit number with no repeating digits. This secret code is what
the codebreaker needs to guess.

2. *Guessing Process*:
- The codebreaker makes guesses by entering 4-digit numbers.
- After each guess, the codemaker provides feedback in terms of "bulls" and "cows" to help the codebreaker refine their guess.

3. *Bulls and Cows Feedback*:


- "Bulls" represent correct digits that are in the correct position in the secret code.
- "Cows" represent correct digits that are in the wrong position in the secret code.

4. *Winning Conditions*:
- The codebreaker continues to make guesses until they guess the secret code correctly (4 bulls).
- If the codebreaker successfully guesses the secret code within the specified number of attempts, they win.
- If they run out of attempts without guessing the code, the codemaker wins.
Examples
15

Here's an example to illustrate how Bulls and Cows feedback works:


- Secret code: 1234
- Codebreaker's guess: 1438
- Feedback: 2 Bulls (1 and 3 are in the correct positions), 1 Cow (4 is a correct digit but in the wrong position).

The game continues until the codebreaker either correctly guesses the entire secret code or exhausts their allowed attempts.

Your Python script implements this game by generating a secret code, allowing the player to make guesses, providing feedback,
and determining the game's outcome based on the player's performance.
import random
CODE
16
def generate_secret_code():
digits = list(range(10))
random.shuffle(digits)
return ''.join(map(str, digits[:4]))
def evaluate_guess(secret, guess):
bulls = 0
cows = 0
for i in range(4):
if guess[i] == secret[i]:
bulls += 1
elif guess[i] in secret:
cows += 1
return bulls, cows
def play_bulls_and_cows(max_attempts):
secret_code = generate_secret_code()
attempts = 0
print("Welcome to Bulls and Cows!")
print("Try to guess the 4-digit secret code with no repeating digits.")
print(f"You have {max_attempts} attempts.")
while attempts < max_attempts:
guess = input("Enter your guess: ")
attempts += 1
if len(guess) != 4 or not guess.isdigit() or len(set(guess)) != 4:
print("Invalid input. Please enter a 4-digit number with no repeating digits.")
continue
bulls, cows = evaluate_guess(secret_code, guess)
if bulls == 4:
print(f"Congratulations! You guessed the secret code '{secret_code}' in {attempts} attempts!")
break
else:
print(f"Bulls: {bulls}, Cows: {cows}")
if bulls != 4:
print(f"Sorry, you've run out of attempts. The secret code was '{secret_code}'.")

if __name__ == "__main__":
max_attempts = int(input("Enter the number of guesses you'd like to have: "))
play_bulls_and_cows(max_attempts)
OUTPUT
17

Enter the number of guesses you'd like to have: 3


Welcome to Bulls and Cows!
Try to guess the 4-digit secret code with no repeating digits.
You have 3 attempts.
Enter your guess: 2
Invalid input. Please enter a 4-digit number with no repeating digits.
Enter your guess: 1234
Bulls: 1, Cows: 0
Enter your guess: 6321
Bulls: 0, Cows: 0
Sorry, you've run out of attempts. The secret code was '0954'.
THANK YOU

You might also like