Python
Python
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
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.
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
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