Join the most intelligent community of young coders. Browse, save & play with codes to understand how they work, and code your own ideas to earn badges & scholarships.

## posted a month ago

if-else
elif
mathematics

You can think of a number between 1 to 60 and then the interpreter will guess your number. Hope you like it.

x=0

A=1

B=2

C=4

D=8

E=16

F=32

print("Welcome to Mind Reader Magic Trick!")

print("Think of a number from 1 to 60.")

print("\n1,5,3,7,9,11,13,15,17,19,39,33,31,37,35,53,57,59,51,55,47,41,45,49,43,25,23,27,21,29")

while True:

print("Is the number in the list above?")

in_list=input("Y for Yes and N for No: ")

if in_list=="Y" or in_list=="y":

x=x+A

break

elif in_list=="N" or in_list=="n":

x=x

break

else:

print("\n2,7,6,3,10,18,15,11,14,19,30,26,27,22,23,31,42,51,34,43,54,35,46,55,38,47,58,50,39,59")

while True:

print("Is the number in the list above?")

in_list=input("Y for Yes and N for No: ")

if in_list=="Y" or in_list=="y":

x=x+B

break

elif in_list=="N" or in_list=="n":

x=x

break

else:

print("\n4,6,7,5,12,20,15,14,13,21,30,28,23,29,22,38,36,31,37,39,47,46,52,44,45,55,54,60,53")

while True:

print("Is the number in the list above?")

in_list=input("Y for Yes and N for No: ")

if in_list=="Y" or in_list=="y":

x=x+C

break

elif in_list=="N" or in_list=="n":

x=x

break

else:

print("\n8,13,26,31,44,57,9,14,27,40,45,58,10,15,28,41,46,59,11,24,29,42,47,60,12,25,30,43,56")

while True:

print("Is the number in the list above?")

in_list=input("Y for Yes and N for No: ")

if in_list=="Y" or in_list=="y":

x=x+D

break

elif in_list=="N" or in_list=="n":

x=x

break

else:

print("\n16,22,57,49,25,17,23,27,54,60,18,24,48,59,30,19,26,53,29,56,20,31,58,50,51,21,52,28,55")

while True:

print("Is the number in the list above?")

in_list=input("Y for Yes and N for No: ")

if in_list=="Y" or in_list=="y":

x=x+E

break

elif in_list=="N" or in_list=="n":

x=x

break

else:

print("\n32,38,42,46,33,39,47,49,59,34,40,44,51,58,35,43,48,57,56,36,45,50,55,54,37,41,60,52,53")

while True:

print("Is the number in the list above?")

in_list=input("Y for Yes and N for No: ")

if in_list=="Y" or in_list=="y":

x=x+F

break

elif in_list=="N" or in_list=="n":

x=x

break

else:

print("Voilà!!! The number you thought was",x,".")

# Play Penalty Kicker Game

## posted a month ago

games
function
for loop
elif

Welcome to Penalty Kicker. Game rules: First you will take penalties then the pc will(pc character name is James). Both sides will take 5 Penalties. You can choose three position in both taking Penalties and Goal Keeping, which are Middle, Left and Right. You have to type \'L\' for Left, \'M\' for Middle and \'R\' for Right. If you will type anything rather than L, M or R your chance will be taken as well as score will not increase. Best of Luck :-)

import random as rd

# declaring James positions
j_position = ['L', 'M', 'R']

# main game function
def game():
# taking player name

# declaring default scores
jamesScore = 0
playerScore = 0

print('\nPenalty Time!\nBest of luck :-)')

# penalty taking
for i in range(5):
# taking choice of james and player
jamesChoice = rd.choice(j_position)
playerChoice = input("\nType 'L' or 'l' for Left , 'M' or 'm' for Middle and 'R' or 'r' for Right : ")

# comparing the choices
# taking the case if james stopped the penalty
if playerChoice.upper() in j_position:
if playerChoice.upper() == jamesChoice:
print('\nJames stopped the penalty!\n')
# printing current scores
print(f'Current Scores: \nPlayer Score = {playerScore} \nJames Score = {jamesScore} ')

# if james didn't stopped then player scored
else:
print(f'\n{playerName} scored!\n')
playerScore = playerScore + 1
# printing current scores
print(f'Current Scores: \nPlayer Score = {playerScore} \nJames Score = {jamesScore} ')

# printing choices of james and player
print(f'\nPlayer Chose = {playerChoice.upper()}\nJames Chose = {jamesChoice}')

# if player didn't choose between L, M or R
else:
print('You can only choose L, M or R')

print('\nPenalty Saving Time!\nStop James before he destroy you ;-)')

# penalty saving
for j in range(5):
# taking choice of james and player
jamesChoice = rd.choice(j_position)
playerChoice = input("\nType 'L' or 'l' for Left , 'M' or 'm' for Middle and 'R' or 'r' for Right : ")

# comparing the choices
# taking the case if j stopped the penalty
if playerChoice.upper() in j_position:
if playerChoice.upper() == jamesChoice:
print(f'\n{playerName} stopped the penalty!\n')
# printing current scores
print(f'Current Scores: \nPlayer Score = {playerScore} \nJames Score = {jamesScore} ')

# if player didn't stopped then james scored
else:
print('\nJames scored!\n')
jamesScore = jamesScore + 1
# printing current scores
print(f'Current Scores: \nPlayer Score = {playerScore}\nJames Score = {jamesScore} ')

# printing choices of james and player
print(f'\nPlayer Chose = {playerChoice.upper()}\nJames Chose = {jamesChoice}')

# if player didn't choose between L, M or R
else:
print('You can only choose L, M or R')

# DECLARING THE WINNER
# if player won
if playerScore > jamesScore:
scoreDif = playerScore - jamesScore
print(f'\n{playerName} won!\n')

# a bit of commentry
if scoreDif >= 3:
print(f'{playerName} dominated James!')
elif scoreDif == 1:
print(f'That was a very close match but there can be only one winner and that is {playerName}')
else:
print('That was a wonderful match!')

# if james won
elif playerScore < jamesScore:
scoreDif = jamesScore - playerScore
print('\nJames won!\n')

# a bit of commentry
if scoreDif >= 3:
print(f'James dominated {playerName}!')
elif scoreDif == 1:
print(f'That was a very close match but there can be only one winner and that is James')
else:
print('That was a wonderful match!')

# if match tied
else:
print('The match is tied!\nWonderful play by both Players')

# asking the player if he/she wanna play again
again = input("Wanna play again? Press 'y'or 'Y' to play again or press 'x' or 'X' to exit : ")
if again.lower() == 'y':
game()
else:
print('\nThanks for playing. Hoping to see you soon')

# explaining the game rules to players

print(
'Welcome to Penalty Kicker!\n\nGame rules:\nFirst you will take penalties then the pc will(pc character name is James):\nBoth sides will take 5 Penalties\nYou can choose three position in both taking Penalties and Goal Keeping, That are Middle, Left and Right\nYou have to type \'L\' for Left, \'M\' for Middle and \'R\' for Right\nIf you will type anything rather than L, M or R your chance will be taken as well as score will not increase \nBest of Luck :-)\n')

# starting the game
start = input("Press 's'or 'S' to start game or press 'x' or 'X' to exit : ")

if start.lower() == 's':
game()
else:
print('Please come again :-)')

# Tic Tac Toe or 'X' and 'O'

## posted 3 months ago

if-else
function
while loop
games

Tic-tac-toe, is a paper-and-pencil game for two players, X or x and O or o, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a diagonal, horizontal, or vertical row is the winner. It is a solved game with a forced draw assuming best play from both players.

import random

player_1 = input("Enter player 1 name : ")

player_2 = input("Enter player 2 name : ")

characterChoose = random.randint(1,2)

game = True

winner = "none"

count = 0

#assign characters "x or o"

if characterChoose == 1:

print(f"{player_1} will choose first")

player1_character = input(f"{player_1} what character do you want : (x or o)")

if player1_character == "x":

player2_character = "o"

else:

player2_character = "x"

player1_character = "o"

else:

print(f"{player_2} will choose first")

player2_character = input(f"{player_2} what character do you want : (x or o)")

if player2_character == "x":

player1_character = "o"

else:

player1_character = "x"

player2_character = "o"

print(f"{player_1} = {player1_character}\n{player_2} = {player2_character}\n")

#who will go first

whoWillGoFirst = random.randint(1,2)

if whoWillGoFirst == 1:

print(f"{player_1} will go first\n{player_2} will go second")

else:

print(f"{player_2} will go first\n{player_1} will go second")

board = [" "," "," "," "," "," "," "," "," "," "]

#making the board

def board_game():

print('   |   |')

print(' ' + board[0] + ' | ' + board[1] + ' | ' + board[2])

print('   |   |')

print('-----------')

print('   |   |')

print(' ' + board[3] + ' | ' + board[4] + ' | ' + board[5])

print('   |   |')

print('-----------')

print('   |   |')

print(' ' + board[6] + ' | ' + board[7] + ' | ' + board[8])

print('   |   |')

# making functions for player 1 turn and player 2

def player1_turn():

position = int(input(f"{player_1} which position do you want to place your character (1 to 9)"))

position = position - 1

if board[position] == " ":

board.pop(position)

board.insert(position,player1_character)

print("the board has been updated")

board_game()

else:

print("the slot has been taken")

player1_turn()

def player2_turn():

position = int(input(f"{player_2} which position do you want to place your character (1 to 9)"))

position = position - 1

if board[position] == " ":

board.pop(position)

board.insert(position,player2_character)

print("the board has been updated")

board_game()

else:

print("the slot has been taken")

player2_turn()

#making function that will check winner

def winnerCheck():

global game

global winner

global count

if (board[0] == "x" and board[1] == "x" and board[2] == "x"

or

board[3] == "x" and board[4] == "x" and board[5] == "x"

or

board[6] == "x" and board[7] == "x" and board[8] == "x"

or

board[0] == "x" and board[4] == "x" and board[8] == "x"

or

board[2] == "x" and board[4] == "x" and board[6] == "x"

or

board[0] == "x" and board[3] == "x" and board[6] == "x"

or

board[1] == "x" and board[4] == "x" and board[7] == "x"

or

board[2] == "x" and board[5] == "x" and board[8] == "x"):

if player1_character == "x":

print(f"\n{player_1} wins the match")

game = False

else:

print(f"\n{player_2} wins the match")

game = False

elif (board[0] == "o" and board[1] == "o" and board[2] == "o"

or

board[3] == "o" and board[4] == "o" and board[5] == "o"

or

board[6] == "o" and board[7] == "o" and board[8] == "o"

or

board[0] == "o" and board[4] == "o" and board[8] == "o"

or

board[2] == "o" and board[4] == "o" and board[6] == "o"

or

board[0] == "o" and board[3] == "o" and board[6] == "o"

or

board[1] == "o" and board[4] == "o" and board[7] == "o"

or

board[2] == "o" and board[5] == "o" and board[8] == "o"):

if player1_character == "o":

print(f"\n{player_1} wins the match")

game = False

else:

print(f"\n{player_2} wins the match")

game = False

else:

if count == 9:

print("tie")

game = False

return game

#main game

while game == True:

if whoWillGoFirst == 1:

player1_turn()

count = count + 1

winner_check = winnerCheck()

if winner_check == False:

break

player2_turn()

count = count + 1

winner_check = winnerCheck()

if winner_check == False:

break

else:

player2_turn()

count = count + 1

winner_check = winnerCheck()

if winner_check == False:

break

player1_turn()

count = count + 1

winner_check = winnerCheck()

if winner_check == False:

break

# Zombie Attack

## posted 2 months ago

games
random
elif
while loop

In this game you have to kill zombies. How to play: 1. There can be ZOMBIE ANYWHERE you have to WRITE a direction(Up, Down, Right, Left, Front, Back). 2. Zombie will be on random direction EACH TIME, if you write the direction where the zombie is: 25💖 will be Added to your life. 3. Or else: 10💘 will be Subtracted from your life. 4. Your default life is: 200. 5. You have 3 Skips too. 6. If your life will be 0: The game will will END and you will get your score. BE READY!

import random as r

print(' ')

print("""Welcome to Zombie Attack!

How to play:

1. There can be zombie on any direction(Up,Down,Left,Right,Front,Back)! You have to write a direction.

2. If you write the direction where the zombie is: 25💖 will be added to your life.

3. Or else: 10💘 will be subtracted from your life.

4. Your default life is: 200

5. When your life gets to 0: You will get your score, your highest life, and the game will end!

Be reday!""")

print(' ')

Start = input("Write 'S' or else it won't start: ")

print(' ')

if Start != 'S':

print('Closing Game...')

print(' ')

else:

score = 0

life = 200

times = 1

skips_left = 4

AICheatCode_left = 3

highest_life = life

while True:

Direction = input(f'''Enter a direction(U for up, D for down, R for right, L for left, F for front, B for back)

or write 'Stop', 'Skip'(You have only {skips_left} skips_left): ''')

if Direction != 'AICheatCode':

Direction = Direction.lower()

print(' ')

Zombie_Direction = r.choice(['u','d','f','r','l','b'])

if life <= 0:

exit()

if Direction == 'stop':

print('')

break

elif Direction == 'skip':

if skips_left != 0:

score = score+0.25

skips_left = skips_left-1

times = times+1

You have: {skips_left} skips left

By the way, there was a zombie on {Zombie_Direction}''')

print(' ')

continue

else:

print('You cant skip as you have 0 skips!')

print(' ')

continue

else:

if Direction == 'AICheatCode':

if AICheatCode_left != 0:

score = score+2

times = times+2

life = life+25

AICheatCode_left = AICheatCode_left-1

print(f'You have {AICheatCode_left} AICheatCodes left')

print(' ')

else:

print('You have 0 AICheatCodess left')

print(' ')

elif Direction == Zombie_Direction:

score = score+1

times = times+1

life = life+25

You have: {skips_left} skips left

You killed the zombie on {Zombie_Direction}!''')

print(' ')

else:

times = times+1

life = life-10

You have: {skips_left} skips left

By the way, there was a zombie on {Zombie_Direction}!''')

print(' ')

if highest_life < life:

highest_life = life

# Rock paper scissors

## posted 3 months ago

if-else
random
games

This program implements the rock, paper, scissors game using the random feature of Python and if-else conditions.

#We first ask for the user's move.
print("Press 1 for rock.\nPress 2 for paper.\nPress 3 for scissors")
player_choice = int(input("Enter your choice: "))

#To get Python's choice, we use the random feature. So these two lines will randomly select a number between 1, 2, and 3.
import random
python_choice = random.choice([1,2,3])

print("Player’s move: ", player_choice)
print("Mr. Python’s move: ", python_choice)

#Here, we evaluate the winner by checking different conditions.
if(python_choice == player_choice):
print("Tie!")
else:
if(python_choice == 1 and player_choice == 2):
print("Player wins! Paper(2) covers Rock(1)!")
elif(python_choice == 2 and player_choice == 1):
print("Mr. Python wins! Paper(2) covers Rock (1)!")
elif(python_choice == 2 and player_choice == 3):
print("Player wins! Scissors (3) cut Paper (2)!")
elif(python_choice == 3 and player_choice == 2):
print("Mr. Python wins! Scissors (3) cut Paper (2)!")
elif(python_choice == 3 and player_choice == 1):
print("Player wins! Rock (1) crushes Scissors (3)!")
elif(python_choice == 1 and player_choice == 3):
print("Mr. Python wins! Rock(1) crushes Scissors (3)!")
else:
print("Wrong choice!")

# Hangman Game

## posted a month ago

while loop
function
random
dictionary
if-else

Play the classic hangman game. Guess the correct word in the least number of tries and save the Hangman!

def get_player_name():
player_name = input('Enter your name: ')
return player_name

player_name = get_player_name()
print('Hello',player_name,',Lets Play Hangman!')

words_possible = {'secret':['_','_','c','_' ,'_','t'],'game':['_', '_', 'm', '_'],'dragon':['_','r','_','_','_','n'],'python':['_','_','t','_','o','_'],'interpreter':['_','_','_','e','_','p','_','_','t','_','r',]}

import random
word = random.choice(list(words_possible.keys()))
word_to_print = words_possible[word]
print(word_to_print)

chances=5
while chances>0:
guess = input('Enter a character: ')

if guess in word:
print('Correct Guess')
for i in range(len(word)):
if word[i] == guess:
word_to_print[i]=guess
print(word_to_print)
if '_' not in word_to_print:
print('You Won!!')
break
else:
chances = chances - 1
print('Wrong Guess')
print('Chances left: ',chances)

if chances == 0:
print('Sorry you lost!!')
print("   _____ \n"
"  |     | \n"
"  |     |\n"
"  |     | \n"
"  |     O \n"
"  |    /|\ \n"
"  |    / \ \n"
"__|__\n")
elif chances == 1:

print("  _____ \n"
"  |     | \n"
"  |     |\n"
"  |     | \n"
"  |     O \n"
"  |     \n"
"  |     \n"
"__|__\n")

elif chances == 2:

print("  _____ \n"
"  |     | \n"
"  |     |\n"
"  |     | \n"
"  |      \n"
"  |     \n"
"  |     \n"
"__|__\n")

elif chances == 3:

print("  _____ \n"
"  |     | \n"
"  |     |\n"
"  |      \n"
"  |      \n"
"  |     \n"
"  |     \n"
"__|__\n")

elif chances == 4:

print("  _____ \n"
"  |     | \n"
"  |     \n"
"  |      \n"
"  |      \n"
"  |     \n"
"  |     \n"
"__|__\n")

# Temperature Converter

## posted 2 months ago

utilities
elif

A small program to convert the temperature between Celsius, Farenheit & Kelvin.

print("Hello, and welcome to the temperature converter.")
print("""Type :
( 1 ) -  For  ( Celsius )     -->    ( Fahrenheit )

( 2 ) -  For  ( Fahrenheit )  -->    ( Celsius )

( 3 ) -  For  ( Celsius )     -->    ( Kelvin )

( 4 ) -  For  ( Kelvin )      -->    ( Celsius )

( 5 ) -  For  ( Fahrenheit )  -->    ( Kelvin )

( 6 ) -  For  ( Kelvin )      -->    ( Fahrenheit )\n""")

choice = input()

if choice == "1":
print("Enter the temperature in Celsius : ")
temp = int(input())
temp = temp * 9 / 5 + 32
print("Degrees Fahrenheit : ", int(temp))

elif choice == "2":
print("Enter the temperature in Fahrenheit : ")
temp = int(input())
temp = (temp - 32) * 5 / 9
print("Degrees Celsius : ", int(temp))

elif choice == "3":
print("Enter the temperature in Celsius: ")
temp = int(input())
temp += 273
print("Degrees Kelvin : ", int(temp))

elif choice == "4":
print("Enter the temperature in Kelvin: ")
temp = int(input())
temp -= 273
print("Degrees Celsius : ", int(temp))

elif choice == "5":
print("Enter the temperature in Fahrenheit: ")
temp = int(input())
temp = (temp - 32) * 5 / 9 + 273
print("Degrees Kelvin : ", int(temp))

elif choice == "6":
print("Enter the temperature : ")
temp = int(input())
temp = (temp - 273) * 9 / 5 + 32
print("Degrees Fahrenheit in Kelvin: ", int(temp))

# Hangman game in Python

## posted 3 months ago

loop
if-else
games

In this game, a player has to guess a secret word. To do that, they pick a letter, and the program checks if that letter is present in the secret word. A player gets 10 chances for this.

name = input('What is your name: ')
print('Hello, ' + name + '! Time to play hangman! So, guess a character.')

#The word that a player has to guess.
word = 'secret'
guesses = ''

#The player can make a max of 10 wrong guesses.
turns = 10
while turns > 0:
guess = input('Guess a character: ')
guesses += guess

#For a wrong guess, we reduce the number of remaining turns by 1.
if guess not in word:
turns -= 1
print('Wrong guess!')
print('You have', turns, 'more guesses')
if turns == 0:
print('You Lose!')
break

#We check how many letters were guessed correctly so far.
#For each correct guess, we increase the remaining_count by 1.
remaining_count = 0
for char in word:
if char in guesses:
print(char, end=' ')
else:
print('_', end=' ')
remaining_count += 1
print('\n')

#If all the letters are guessed, i.e. remaining_count is 0, the player wins.
if remaining_count == 0:
print('You won!')
break

# Age Calculator

## posted 3 months ago

if-else
utilities

Enter you date in DD/MM/YYY format to calculate your age.

from datetime import date

today = date.today()
curr_date = today.day
curr_year = today.year
curr_month = today.month

date_of_birth = input("Date of birth in DD/MM/YYYY: ")
date_of_birth = date_of_birth.split("/")
age = curr_year - int(date_of_birth[2])

if int(date_of_birth[0]) > 31 or int(date_of_birth[1]) > 12 or int(date_of_birth[2]) > curr_year:
print("Invalid date.")

else:
if curr_month == int(date_of_birth[1]):
if curr_date < int(date_of_birth[0]):
age = age - 1
elif curr_month < int(date_of_birth[1]):
age = age - 1
print(age, "years.")

# Play Among Us

## posted a month ago

games
while loop
elif

Among Us is a multiplayer game where players get dropped into an alien spaceship, sky headquarters or planet base, where each player is designated with a private role of either a “crewmate” and an “impostor.” This is an online multiplayer social deduction game, and a player can either be a crewmate or an imposter. One can play the game online or on local WiFi with their selected friends.

import random

player1Name = input("Please enter the player 1 name: ")

player2Name = input("Please enter the player 2 name: ")

player3Name = input("Please enter the player 3 name: ")

player4Name = input("Please enter the player 4 name: ")

flag = 0

gameOver = -1

playersList = [player1Name, player2Name, player3Name, player4Name]

weapons = ["Machine Gun", "Rocket Launcher", "Dagger", "Alien Tentacles", "Acid", "Light saber", "Laser Ray"]

sabotageAreas = ["Electrical", "Command", "Navigation", "Engines", "Shields", "Security Cameras"]

imposter = random.choice(playersList)

playersList.remove(imposter)

victim = random.choice(playersList)

weaponUsed = random.choice(weapons)

imposterSabotages = random.choice(sabotageAreas)

print(correctPass)

print(imposter)

while gameOver == -1:

while flag == 0:

action = input("Please enter what you want to do now, imposter: ")

if action == "Kill":

print(f"Ok, you killed " + victim + " by " + weaponUsed)

flag = 1

playersList.remove(victim)

length = len(playersList)

if length > 0:

victim = random.choice(playersList)

weaponUsed = random.choice(weapons)

else:

print("The Imposter wins")

gameOver = 1

elif action == "Report":

print("You have reported an emergency meeting. Everyone, to the Cafeteria!")

print(f"Whom do you vote to? {player1Name}, {player2Name}, {player3Name}, or {player4Name}?")

vote = input("Please enter whom you want to vote: ")

if vote == imposter:

print(f"{vote} has been ejected, and he was the imposter. Crew mates win.")

gameOver = 1

else:

"You have ejected a crew mate. Imposter remains."

flag = 1

elif action == "Sabotage":

print("Ok, you have sabotaged the " + imposterSabotages + ". Now, complete the kills")

flag = 1

imposterSabotages = random.choice(sabotageAreas)

elif action == "Enter Admin Room":

if userPass == correctPass:

print("You are cleared to go, crew mate!")

print(correctPass)

else:

print("Wrong Password. You are an Imposter!")

flag = 1

else:

print("That is no action assigned to you, imposter!")

flag = 1

while flag == 1:

action = input("Crew mate, please enter what you want to do now: ")

print("Ok, you have done the task '", taskDone, "'. Now complete other tasks and find the imposters!")

flag = 0

elif action == "Report":

print("you have reported an emergency meeting. Everyone, to the Cafeteria!")

print(f"Whom do you vote to? {player1Name}, {player2Name}, {player3Name}, or {player4Name}?")

vote = input("Please enter whom you want to vote: ")

if vote == imposter:

print(f"{vote} has been ejected, and he was the imposter. Crew mates win.")

break

else:

"You have ejected a crew mate. Imposter remains."

flag = 0

elif action == "Repair Sabotage Areas":

print(f"Ok, you fixed {imposterSabotages}. Now, Find the imposter")

imposterSabotages = random.choice(sabotageAreas)

flag = 0

else:

print("That is no action assigned to you, crew mate!")

flag = 0