-
Notifications
You must be signed in to change notification settings - Fork 0
/
```py.txt
176 lines (141 loc) · 6.21 KB
/
```py.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
```python
import random
def get_user_choice():
user_choice = input("Enter your choice (rock, paper, scissors) or 'q' to quit: ").lower()
while user_choice not in ['rock', 'paper', 'scissors', 'q']:
user_choice = input("Invalid choice. Please enter rock, paper, scissors, or 'q' to quit: ").lower()
return user_choice
def get_computer_choice():
return random.choice(['rock', 'paper', 'scissors'])
def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "It's a tie!"
if (user_choice == 'rock' and computer_choice == 'scissors') or \
(user_choice == 'paper' and computer_choice == 'rock') or \
(user_choice == 'scissors' and computer_choice == 'paper'):
return "You win!"
else:
return "Computer wins!"
while True:
user_choice = get_user_choice()
if user_choice == 'q':
print("Thanks for playing!")
break
computer_choice = get_computer_choice()
print(f"Computer chose: {computer_choice}")
print(determine_winner(user_choice, computer_choice))
```
In this program, the `get_user_choice` function prompts the user to enter their choice and validates the input. The `get_computer_choice` function generates a random choice for the computer. The `determine_winner` function determines the winner based on the rules of rock-paper-scissors.
The main part of the program runs in a loop, allowing the user to continue playing until they enter 'q' to quit. The computer's choice is displayed, along with the outcome of the game.```python
def sort_numbers():
numbers = input("Enter a list of numbers separated by spaces: ")
numbers_list = numbers.split()
unique_numbers = list(set(numbers_list)) # Remove duplicates
sorted_numbers = sorted(unique_numbers, key=int, reverse=True) # Sort in descending order
print("Sorted list without duplicates: ", sorted_numbers)
sort_numbers()
``````python
import random
def roll_die():
return random.randint(1, 6)
def play_game():
player1_score = 0
player2_score = 0
for _ in range(10): # Play 10 rounds
input("Player 1: Press Enter to roll the die.")
player1_roll = roll_die()
print("Player 1 rolled:", player1_roll)
player1_score += player1_roll
input("Player 2: Press Enter to roll the die.")
player2_roll = roll_die()
print("Player 2 rolled:", player2_roll)
player2_score += player2_roll
print("\nFinal Scores:")
print("Player 1 score:", player1_score)
print("Player 2 score:", player2_score)
if player1_score > player2_score:
print("Player 1 wins!")
elif player2_score > player1_score:
print("Player 2 wins!")
else:
print("It's a tie!")
play_game()
```
This program simulates a dice game where two players take turns rolling a six-sided die. The game consists of 10 rounds, and after all rounds, the program displays the final scores of each player and determines the winner based on the highest score. Each time a player rolls the die, the program generates a random number between 1 and 6 as the roll result.```python
def sum_even_numbers(numbers):
sum_even = 0
even_numbers = []
for num in numbers:
if num % 2 == 0:
sum_even += num
even_numbers.append(num)
return sum_even, max(numbers), min(numbers), even_numbers
try:
numbers = [int(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
result = sum_even_numbers(numbers)
print(f"The sum of all even numbers in the list is: {result[0]}")
print(f"The maximum number in the list is: {result[1]}")
print(f"The minimum number in the list is: {result[2]}")
print(f"The even numbers in the list are: {result[3]}")
except ValueError:
print("Invalid input. Please enter valid numbers separated by spaces.")
```
This program takes a list of numbers as input, calculates the sum of all even numbers in the list, finds the maximum and minimum numbers, and prints out the results. It also includes error handling for invalid input. Feel free to test it with a sample list of numbers!```python
# Basic calculator program in Python
# Function to add two numbers
def add(x, y):
return x + y
# Function to subtract two numbers
def subtract(x, y):
return x - y
# Function to multiply two numbers
def multiply(x, y):
return x * y
# Function to divide two numbers
def divide(x, y):
if y == 0:
return "Error: Division by zero!"
else:
return x / y
print("Welcome to the Basic Calculator Program!")
while True:
try:
# Get user input for two numbers and operation
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operation = input("Enter the operation (+, -, *, /): ")
# Perform the operation based on user input
if operation == '+':
result = add(num1, num2)
elif operation == '-':
result = subtract(num1, num2)
elif operation == '*':
result = multiply(num1, num2)
elif operation == '/':
result = divide(num1, num2)
else:
print("Invalid operation! Please try again.")
continue
print("Result: ", result)
except ValueError:
print("Invalid input! Please enter a valid number.")
```
This code snippet implements a basic calculator program in Python that allows the user to perform addition, subtraction, multiplication, and division. The program takes input from the user for two numbers and the operation to be performed, then displays the result. It also includes error handling for division by zero and invalid input.```python
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def generate_prime_numbers(limit):
primes = []
for num in range(2, limit+1):
if is_prime(num):
primes.append(num)
return primes
limit = int(input("Enter a limit: "))
prime_numbers = generate_prime_numbers(limit)
print("Prime numbers up to", limit, ":", prime_numbers)
```
You can run this program and input a limit to get a list of prime numbers up to that limit.