Title: Python Core Programming Exercise Solutions
Exercise 1:
Write a Python program to print "Hello, World!".
Solution:
```python
print("Hello, World!")
```
Exercise 2:
Write a Python program to add two numbers.
Solution:
```python
num1 = 5
num2 = 3
sum = num1 num2
print("The sum of {0} and {1} is {2}".format(num1, num2, sum))
```
Exercise 3:
Write a Python program to find the square root of a number.
Solution:
```python
import math
num = 16
sqrt_num = math.sqrt(num)
print("The square root of", num, "is", sqrt_num)
```
Exercise 4:
Write a Python program to check if a number is positive, negative or zero.
Solution:
```python
num = 5
if num > 0:
print("The number is positive")
elif num < 0:
print("The number is negative")
else:
print("The number is zero")
```
Exercise 5:
Write a Python program to find the factorial of a number.
Solution:
```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n1)
num = 5
print("The factorial of", num, "is", factorial(num))
```
Exercise 6:
Write a Python program to check if a number is prime or not.
Solution:
```python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) 1):
if n % i == 0:
return False
return True
num = 7
if is_prime(num):
print(num, "is a prime number")
else:
print(num, "is not a prime number")
```
Exercise 7:
Write a Python program to print the Fibonacci sequence.
Solution:
```python
def fibonacci(n):
fib_seq = [0, 1]
for i in range(2, n):
fib_seq.append(fib_seq[i1] fib_seq[i2])
return fib_seq
num_terms = 10
print("Fibonacci sequence:", fibonacci(num_terms))
```
Exercise 8:
Write a Python program to find the sum of digits in a number.
Solution:
```python
def sum_of_digits(n):
sum = 0
while n > 0:
digit = n % 10
sum = digit
n //= 10
return sum
num = 12345
print("The sum of digits in", num, "is", sum_of_digits(num))
```
Exercise 9:
Write a Python program to reverse a number.
Solution:
```python
def reverse_number(n):
rev = 0
while n > 0:
digit = n % 10
rev = rev * 10 digit
n //= 10
return rev
num = 12345
print("The reverse of", num, "is", reverse_number(num))
```
Exercise 10:
Write a Python program to find the factorial of a large number.
Solution:
```python
import math
num = 100
fact = math.factorial(num)
print("The factorial of", num, "is", fact)
```
These are solutions to some core Python programming exercises. Make sure to understand the concepts behind each solution and try to solve similar problems on your own to reinforce your understanding. Happy coding!
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。