Python
Python
Python
## Problem 2
list = (i for i in range(1,100) if i%2!=0)
for i in list:
print(i)
## Problem 3
sum = 0
for i in range(1, 11):
sum += i
print(sum)
## Problem 4
print('Enter correct username and password combo to continue')
count=3
password='Hytu76E'
while True:
password='Hytu76E' and count<3
password1 = input('Enter password: ')
if password==password1:
print('Access granted')
break
else:
print('Access denied. Try again.')
count-=1
if count<1:
print("Access Denied")
break
## Problem 5
# Prompt the user to input a number and convert it to an integer, assigning it
to the variable 'n'
n = int(input("Input a number: "))
## Problem 6
rows = 5
for i in range(0, rows + 1):
for j in range(rows - i, 0, -1):
print(j, end=' ')
print()
## Problem 7
Array = ['Bob', 'Tom', 'Tim', 'Ned']
Array.reverse()
print (Array)
## Problem 8
num = 76542
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
## Problem 9
import math
math.factorial(1000)
n = int(input('Enter a number for factorial: '))
## Problem 10
w = int(input("Enter width for square: "))
l = int(input("Enter length for square: "))
# Loop through rows
for i in range(w):
# Loop to print pattern
for j in range(l):
print('*', end=' ')
print()
while True:
print(Students[0], StudentMarks[0])
print(Students[1], StudentMarks[1])
print(Students[2], StudentMarks[2])
print(Students[3], StudentMarks[3])
break
def Average(StudentMarks):
return sum(StudentMarks) / len(StudentMarks)
average = Average(StudentMarks)
print(round(average, 2))
## Functions ##
## Problem 1
InputNumber = int(input("Enter a number: "))
def FindIt():
if InputNumber > 26:
print("False, the number is more than 26")
if InputNumber > 0 and InputNumber < 26:
print("True, the number is between 0 and 26")
if InputNumber < 0:
print("False, number is less than 0")
FindIt()
## Problem 2
def AverageMarks(Marks):
return sum(Marks) / len(Marks)
average = AverageMarks(Marks)
print(round(average, 2))
def AverageHeights(Height):
return sum(Height) / len(Height)
average = AverageHeights(Height)
print(round(average, 2))
## Problem 3
def Area():
area = w * h
print(area)
Area()
## Problem 4
from math import pi
def CircleArea():
r = float(input("Enter your radius: "))
Area = pi * r ** 2
print("The area of the circle with the radius", r, "is", round(Area, 2))
CircleArea()
## Pseudocode to Python
#1#
import math
Num1 = input("Give number 1: ")
Num2 = input("Give number 2: ")
Op = input('+/- ')
def Calculator(Num1, Num2, Op):
if Op == '+':
ans = Num1 + Num2
elif Op == '-':
ans = Num1 - Num2
print(Calculator(1, 2, '+'))
print(Calculator(9, 3, '-'))
#2#
#3 Age Check #
eligible = int(input("Enter your age: "))
if eligible >= 18:
if eligible > 75:
print("Require doctor endorsement")
else:
print("Approved")
else:
print("Not Approved")
# 4 Cycles #
from time import sleep
small = 2
big = 3
cycles = 0
while True:
small = small * 4.5
big = big * 4
cycles = cycles + 1
if small > big:
print("Small is larger than big")
break
print(small, big, cycles)
sleep(0.5)
# 5 Turns #
turns = 0
x = 3
while turns < 22:
x = x * 3
turns = turns + 3
print("X =",x)
print("Turns = ", turns)
# 6 DWhile #
x = 4
y = x+10
while y < 15:
if x < 8:
x = x + 1
print("X = ", x,"Y =", y)
# 7 AveTemp #
Week = 0
TotalTemp = 0
while Week < 7:
DailyTemp = int(input("Enter daily temp: "))
TotalTemp = TotalTemp + DailyTemp
AveTemp = TotalTemp / 7
print("Average temperatire for this week: ", round(AveTemp, 2))
Week = Week + 1
## Challenges ##
# 2 player rock paper scissors #
again = 'y'
print()
print()
if (p1 == "rock"):
if (p2 == "rock"):
print("The game is a draw")
elif (p2 == "paper"):
print("Player 2 wins!")
elif (p2 == "scissors"):
print("Player 1 wins!")
elif (p1 == "paper"):
if (p2 == "rock"):
print("Player 1 wins!")
elif (p2 == "paper"):
print("The game is a draw")
elif (p2 == "scissors"):
print("Player 2 wins!")
elif (p1 == "scissors"):
if (p2 == "rock"):
print("Player 2 wins!")
elif (p2 == "paper"):
print("Player 1 wins!")
elif (p2 == "scissors"):
print("The game is a draw")
else:
print("Invalid input, try again")
print()
import tkinter as tk
from tkinter import font
from typing import NamedTuple
from itertools import cycle
class TicTacToeGame:
def __init__(self, players=DEFAULT_PLAYERS, board_size=BOARD_SIZE):
self._players = cycle(players)
self.board_size = board_size
self.current_player = next(self._players)
self.winner_combo = []
self._current_moves = []
self._has_winner = False
self._winning_combos = []
self._setup_board()
def _setup_board(self):
self._current_moves = [
[Move(row, col) for col in range(self.board_size)]
for row in range(self.board_size)]
self._winning_combos = self._get_winning_combos()
def _get_winning_combos(self):
rows = [
[(move.row, move.col) for move in row]
for row in self._current_moves
]
columns = [list(col) for col in zip(*rows)]
first_diagonal = [row[i] for i, row in enumerate(rows)]
second_diagonal = [col[j] for j, col in enumerate(reversed(columns))]
return rows + columns + [first_diagonal, second_diagonal]
def is_valid_move(self, move):
"""Return True if move is valid, and False otherwise."""
row, col = move.row, move.col
move_was_not_played = self._current_moves[row][col].label == ""
no_winner = not self._has_winner
return no_winner and move_was_not_played
class Player(NamedTuple):
label: str
color: str
class Move(NamedTuple):
row: int
col: int
label: str = ""
BOARD_SIZE = 3
DEFAULT_PLAYERS = (
Player(label="X", color="blue"),
Player(label="O", color="green"),
)
class TicTacToeBoard(tk.Tk):
def __init__(self):
super().__init__()
self.title("Tic-Tac-Toe Game")
self._cells = {}
self._create_board_display()
self._create_board_grid()
def _create_board_display(self):
display_frame = tk.Frame(master=self)
display_frame.pack(fill=tk.X)
self.display = tk.Label(
master=display_frame,
text="Ready?",
font=font.Font(size=28, weight="bold"),
)
self.display.pack()
def _create_board_grid(self):
grid_frame = tk.Frame(master=self)
grid_frame.pack()
for row in range(3):
self.rowconfigure(row, weight=1, minsize=50)
self.columnconfigure(row, weight=1, minsize=75)
for col in range(3):
button = tk.Button(
master=grid_frame,
text="",
font=font.Font(size=36, weight="bold"),
fg="black",
width=3,
height=2,
highlightbackground="lightblue",
)
self._cells[button] = (row, col)
button.grid(
row=row,
column=col,
padx=5,
pady=5,
sticky="nsew"
)
def main():
"""Create the game's board and run its main loop."""
board = TicTacToeBoard()
board.mainloop()
if __name__ == "__main__":
main()
# Hangman #
import time
name = input("What is your name? ")
print("Hello, " + name, "Time to play hangman!")
time.sleep(1)
print("Start guessing...")
time.sleep(0.5)
# here we set the secret. You can select any word to play with.
word = ("secret")
guesses = ''
turns = 10
failed += 1
# if failed is equal to zero
if failed == 0:
print("You won")
# exit the script
break
# ask the user go guess a character
guess = input("guess a character:")
# set the players guess to guesses
guesses += guess
# if the guess is not found in the secret word
if guess not in word:
turns -= 1
print("Wrong")
# how many turns are left
print("You have", + turns, 'more guesses')
# if the turns are equal to zero
if turns == 0:
# print "You Lose"
print("You Lose")