You can not select more than 25 topics
			Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
		
		
		
		
		
			
		
			
				
					
					
						
							72 lines
						
					
					
						
							3.4 KiB
						
					
					
				
			
		
		
	
	
							72 lines
						
					
					
						
							3.4 KiB
						
					
					
				| ---
 | |
| title: Python
 | |
| description: Примеры на Python
 | |
| date: '2023-03-22'
 | |
| ---
 | |
| 
 | |
| ## Список неронныйх сетей
 | |
| 
 | |
| Для вычисления суммы чисел от 1 до N можно использовать цикл for:
 | |
| 
 | |
| ```py
 | |
| N = int(input("Введите N: "))
 | |
| sum = 0
 | |
| for i in range(1, N+1):
 | |
|     sum += i
 | |
| print("Сумма чисел от 1 до", N, "равна", sum)
 | |
| ```
 | |
| 
 | |
| В этой программе мы сначала запрашиваем у пользователя число N, затем создаем переменную sum, которая будет хранить сумму чисел. Далее запускаем цикл for, который проходит по всем целым числам от 1 до N (включительно), и на каждой итерации добавляет текущее число к переменной sum. В конце программы выводим на экран результат.
 | |
| 
 | |
| ## Прграмма вывода погоды
 | |
| 
 | |
| Для написания программы для вывода погоды на Python вам нужно использовать специальный API (Application Programming Interface), который позволяет получать данные о погоде от различных источников. Например, вы можете использовать API от Tomorrow.io12, который предоставляет прогнозы на несколько дней вперед.
 | |
| 
 | |
| Для доступа к API вам нужно зарегистрироваться на сайте Tomorrow.io и получить свой ключ API1. Затем вы можете использовать библиотеку requests для отправки запросов к API и получения ответов в формате JSON13. Вы также можете использовать документацию API от Tomorrow.io для генерации кода Python по вашим параметрам.
 | |
| 
 | |
| Вот пример кода для получения прогноза погоды на завтра для Москвы с помощью API от Tomorrow.io1:
 | |
| 
 | |
| ```py
 | |
| import requests
 | |
| import datetime
 | |
| 
 | |
| # Your API key from Tomorrow.io
 | |
| api_key = "IKRL1eOI7Rnc1sbhKRdePaK6HyUfw95K"
 | |
| 
 | |
| # The base URL for the API
 | |
| base_url = "https://api.tomorrow.io/v4/timelines"
 | |
| 
 | |
| # The parameters for the query
 | |
| querystring = {
 | |
|     "location": "45.0503973, 39.021093", # Moscow coordinates
 | |
|     "fields": ["temperature","humidity","windSpeed"], # Weather fields
 | |
|     "units": "metric", # Celsius units
 | |
|     "timesteps": "1d", # Daily forecast
 | |
|     "apikey": api_key 
 | |
| }
 | |
| 
 | |
| # Send a GET request to the API and get the response
 | |
| response = requests.request("GET", base_url, params=querystring)
 | |
| 
 | |
| # Convert the response to JSON format
 | |
| data = response.json()
 | |
| 
 | |
| # Get the current date and time
 | |
| now = datetime.datetime.now()
 | |
| 
 | |
| # Get the tomorrow's date 
 | |
| tomorrow = now + datetime.timedelta(days=1)
 | |
| 
 | |
| # Format the date as YYYY-MM-DD
 | |
| tomorrow_date = tomorrow.strftime("%Y-%m-%d")
 | |
| 
 | |
| # Get the weather data for tomorrow from the JSON response
 | |
| weather_data = data["data"]["timelines"][0]["intervals"][0]["values"]
 | |
| 
 | |
| # Print the weather forecast for tomorrow
 | |
| print(f"Weather forecast for {tomorrow_date} in Krasnodar:")
 | |
| print(f"Temperature: {weather_data['temperature']} °C")
 | |
| print(f"Humidity: {weather_data['humidity']} %")
 | |
| print(f"Wind speed: {weather_data['windSpeed']} m/s")
 | |
| 
 | |
| ``` |