Example of python
Python is a high level,interpreted programming language that is easy to learn and understand. It's often used for Web development, data analysis, artificial intelligence,and more. Here are three examples to illustrate Python syntax and capabilities:
Example (1): HELLO,WORLD!
```
print("Hello, World!")
```
This code simply prints the string "Hello, World!" to the screen. It demonstrates Python's basic syntax and the `print()` function.
Example (2): GUESSING Game
```
secret_number = 42
guess = int(input("Guess a number: "))
if guess == secret_number:
print("Congratulations! You won!")
else:
print("Try again!")
```
This code creates a simple guessing game. It:
1. Sets a secret number (42).
2. Asks the user to input a guess.
3. Converts the input to an integer using `int()`.
4. Checks if the guess matches the secret number.
5. Prints a success message or prompts the user to try again.
Example (3): calculating sum
```
numbers = [1, 2, 3, 4, 5]
sum = 0
for number in numbers:
sum += number
print("Sum:", sum)
```
This code calculates the sum of a list of numbers. It:
1 Defines a list of numbers.
2 Initializes a sum variable to 0.
3 Uses a `for` loop to iterate over the list.
4 Adds each number to the sum.
5 Prints the final sum.
These examples showcase of python:
- Simple syntax
- Basic data types (strings, integers, lists)
- Control structures (if-else, for loops)
- Functions (print(), int())
Comments
Post a Comment