首页 > 编程语言 >初学编程100个代码

初学编程100个代码

时间:2023-06-24 16:55:43浏览次数:49  
标签:random num 编程 列表 lst 初学 words print 100

  Java、Python等主流编程语言如今火的不行,初学编程都有哪100个代码呢?笔者结合实际开发经验和同学们最迫切关注的技术热点,总结了100个常用的代码实现,具体如下:

  1.输出 "Hello, World!":

print("Hello, World!")

  2.求两个数的和:

点击查看代码

a = 5
b = 7
c = a + b
print(c)

  3.计算圆的面积:

import math

radius = 4
area = math.pi * radius ** 2
print(area)

  4.判断一个数是否为偶数:

num = 8
if num % 2 == 0:
print("This number is even.")
else:
print("This number is odd.")
  5.计算一个列表的平均值:

lst = [1, 2, 3, 4, 5]
avg = sum(lst) / len(lst)
print(avg)
  6.打印九九乘法表:

for i in range(1, 10):
for j in range(1, i+1):
print(f"{j}x{i}={i*j}", end='\t')
print()
  7.判断一个字符串是否为回文字符串:

s = "racecar"
if s == s[::-1]:
print("This is a palindrome.")
else:
print("This is not a palindrome.")
  8.输出斐波那契数列的前20项:

a, b = 0, 1
for i in range(20):
print(a, end=' ')
a, b = b, a+b
  9.生成一个包含10个随机数的列表:

import random

lst = []
for i in range(10):
lst.append(random.randint(1, 100))
print(lst)
  10.将一个字符串中的大写字母转换为小写字母:

s = "HelLo, WoRLd!"
s_lower = s.lower()
print(s_lower)
  11.将一个字符串中的小写字母转换为大写字母:

s = "HelLo, WoRLd!"
s_upper = s.upper()
print(s_upper)
  12.将一个列表中的元素按照从小到大的顺序排列:

lst = [5, 3, 8, 2, 7, 4, 1, 9, 6]
lst.sort()
print(lst)
  13.判断一个数是否为质数:

num = 17
if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
  14.求一个列表中的最大值和最小值:

lst = [5, 3, 8, 2, 7, 4, 1, 9, 6]
max_val = max(lst)
min_val = min(lst)
print("Max value:", max_val)
print("Min value:", min_val)
  15.将一个字符串翻转:

string = "Hello, World!"
reversed_string = string[::-1]
print(reversed_string)
  16.判断一个数是否为完全平方数:

num = 16
if (num**0.5).is_integer():
print(num, "is a perfect square.")
else:
print(num, "is not a perfect square.")
  17.计算一个字符串中包含的字母个数:

s = "Hello, World!"
count = 0
for c in s:
if c.isalpha():
count += 1
print(count)
  18.计算一个数的阶乘:

num = 5
factorial = 1
for i in range(1, num+1):
factorial *= i
print(factorial)
  19.将一个列表中的元素去重:

lst = [1, 2, 3, 2, 4, 5, 4, 6, 7, 6]
unique_lst = list(set(lst))
print(unique_lst)
  20.将一个列表中的元素随机排序:

import random

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(lst)
print(lst)
  21.将一个列表中的元素逆序排列:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
lst.reverse()
print(lst)
  22.一个字符串中的单词按照字典序排序:

s = "this is a test string"
words = s.split()
words.sort()
sorted_s = ' '.join(words)
print(sorted_s)
  23.计算两个数的最大公约数:

a = 15
b = 25

while b != 0:
t = b
b = a % b
a = t

print("The greatest common divisor is:", a)
  24.计算两个数的最小公倍数:

a = 15
b = 25
gcd = 0

for i in range(1, b+1):
if (a * i) % b == 0:
gcd = a * i
break

print("The least common multiple is:", gcd)
  25.将一个字符串中的空格替换为下划线:

s = "Hello, World!"
s_underscore = s.replace(' ', '_')
print(s_underscore)
  26.判断一个数是否为回文数:

num = 12321
if str(num) == str(num)[::-1]:
print(num, "is a palindrome.")
else:
print(num, "is not a palindrome.")
  27.判断一个字符串是否为全数字:

s = "12345"
if s.isdigit():
print(s, "consists entirely of digits.")
else:
print(s, "does not consist entirely of digits.")
  28.计算一个数的平方根:

import math

num = 16
sqrt = math.sqrt(num)
print(sqrt)
  29.将一个列表中的元素按照长度从小到大排序:

my_list = ["apple", "banana", "cherry", "date", "elderberry"]
sorted_list = sorted(my_list, key=len)
print(sorted_list)

  30.将一个列表中的元素按照长度从大到小排序:

lst = ["apple", "banana", "pear", "orange", "kiwi"]
lst.sort(key=len, reverse=True)
print(lst)
  31.将一个字符串中的每个单词首字母大写:

s = "this is a test string"
words = s.split()
capitalized_words = [word.capitalize() for word in words]
capitalized_s = ' '.join(capitalized_words)
print(capitalized_s)
  32.计算一个数的立方:

num = 5
cube = num ** 3
print(cube)
  33.计算一个数的四次方:

num = 5
fourth_power = num ** 4
print(fourth_power)
  34.将一个列表中的元素用逗号连接成一个字符串:

lst = ["apple", "banana", "pear", "orange", "kiwi"]
s = ', '.join(lst)
print(s)
  35.将一个列表中的元素用空格连接成一个字符串:

lst = ["apple", "banana", "pear", "orange", "kiwi"]
s = ' '.join(lst)
print(s)
  36.将一个列表中的元素用换行符连接成一个字符串:

lst = ["apple", "banana", "pear", "orange", "kiwi"]
s = '\n'.join(lst)
print(s)
  37.判断一个数是否为质数:

num = 17
is_prime = True

if num > 1:
for i in range(2, int(num**0.5)+1):
if num % i == 0:
is_prime = False
break
else:
is_prime = False

if is_prime:
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")
  38.将一个字符串中的字母大小写互换:

s = "Hello, World!"
swap_s = s.swapcase()
print(swap_s)
  39.判断一个字符串是否为回文字符串:

s = "racecar"
if s == s[::-1]:
print(s, "is a palindrome.")
else:
print(s, "is not a palindrome.")
  40.计算两个数的和、差、积和商:

a = 5
b = 3

sum = a + b
difference = a - b
product = a * b
quotient = a / b

print("The sum is:", sum)
print("The difference is:", difference)
print("The product is:", product)
print("The quotient is:", quotient)
  41.判断一个字符串中是否包含另一个字符串:

s = "Hello, World!"
sub_s = "World"

if sub_s in s:
print(s, "contains", sub_s)
else:
print(s, "does not contain", sub_s)
  42.将一个字符串中的数字取出来并求和:

s = "There are 7 apples and 3 oranges."
nums = [int(i) for i in s.split() if i.isdigit()]
sum_nums = sum(nums)
print(sum_nums)
  43.将一个列表中的元素按照字符串长度排序,并按照长度相同的元素字典序排序:

lst = ["pear", "banana", "kiwi", "apple", "orange"]
lst.sort(key=lambda x: (len(x), x))
print(lst)
  44.计算一个数的平方根:

import math

num = 9
sqrt_num = math.sqrt(num)
print(sqrt_num)
  45.将一个列表中的元素去重:

lst = [1, 2, 3, 2, 4, 3, 5, 6, 1]
unique_lst = list(set(lst))
print(unique_lst)
  46.将一个字符串中的每个单词逆序输出:

s = "This is a test string"
words = s.split()
reversed_words = [word[::-1] for word in words]
reversed_s = ' '.join(reversed_words)
print(reversed_s)
  47.将一个字符串中的每个单词的字母顺序逆序输出:

s = "This is a test string"
words = s.split()
reversed_words = [''.join(reversed(word)) for word in words]
reversed_s = ' '.join(reversed_words)
print(reversed_s)
  48.将一个字符串中的每个单词的首字母移到末尾:

s = "This is a test string"
words = s.split()
new_words = [word[1:] + word[0] + 'ay' for word in words]
new_s = ' '.join(new_words)
print(new_s)
  49.将一个列表中的元素两两配对:

lst = [1, 2, 3, 4, 5, 6]
pairs = [(lst[i], lst[i+1]) for i in range(0, len(lst)-1, 2)]
print(pairs)
  50.将一个列表中的元素分组:

lst = [1, 2, 3, 4, 5, 6]
groups = [[lst[i], lst[i+1]] for i in range(0, len(lst), 2)]
print(groups)
  51.将一个字符串中的每个单词的首字母大写,并将其余字母小写:

s = "THIS IS A TEST STRING"
words = s.split()
new_words = [word.capitalize() for word in words]
new_s = ' '.join(new_words)
print(new_s)
  52.将一个列表中的元素随机排序:

import random

lst = [1, 2, 3, 4, 5, 6]
random.shuffle(lst)
print(lst)
  53.将一个字符串中的字母往后移动指定的位数:

def shift_letter(letter, shift):
shifted_letter = chr((ord(letter) - 97 + shift) % 26 + 97)
return shifted_letter

s = "hello"
shift = 3
shifted_s = ''.join([shift_letter(letter, shift) for letter in s])
print(shifted_s)
  54.将一个字符串中的字母往前移动指定的位数:

def shift_letter(letter, shift):
shifted_letter = chr((ord(letter) - 97 - shift) % 26 + 97)
return shifted_letter

s = "khoor"
shift = 3
shifted_s = ''.join([shift_letter(letter, shift) for letter in s])
print(shifted_s)
  55.求一个列表中的最大数和最小数:

lst = [1, 2, 3, 4, 5, 6]
max_num = max(lst)
min_num = min(lst)
print("Max:", max_num)
print("Min:", min_num)
  56.求一个列表中的元素之和:

lst = [1, 2, 3, 4, 5, 6]
sum_lst = sum(lst)
print("Sum:", sum_lst)
  57.求一个列表中的元素平均值:

lst = [1, 2, 3, 4, 5, 6]
avg_lst = sum(lst) / len(lst)
print("Average:", avg_lst)
  58.求一个列表中的中位数:

def median(lst):
sorted_lst = sorted(lst)
lst_len = len(lst)
mid_index = lst_len // 2
if lst_len % 2 == 0:
return (sorted_lst[mid_index-1] + sorted_lst[mid_index]) / 2
else:
return sorted_lst[mid_index]

lst = [1, 2, 3, 4, 5, 6]
median_lst = median(lst)
print("Median:", median_lst)
  59.求一个列表中的众数:

from collections import Counter

lst = [1, 2, 3, 2, 4, 3, 5, 6, 1]
cnt = Counter(lst)
mode = cnt.most_common(1)[0][0]
print("Mode:", mode)
  60.求两个数的最大公约数:

def gcd(a, b):
if a % b == 0:
return b
else:
return gcd(b, a % b)

a = 48
b = 36
gcd_ab = gcd(a, b)
print("GCD:", gcd_ab)
  61.求两个数的最小公倍数:

def lcm(a, b):
return (a * b) // gcd(a, b)

a = 48
b = 36
lcm_ab = lcm(a, b)
print("LCM:", lcm_ab)
  62.将一个字符串中的每个单词首尾颠倒:

s = "This is a test string"
words = s.split()
reversed_words = [word[::-1] for word in words]
reversed_s = ' '.join(reversed_words)
print(reversed_s)
  63.将一个字符串中的每个单词逆序输出,但保留单词之间的顺序:

s = "This is a test string"
words = s.split()
reversed_words = ' '.join([word[::-1] for word in words])
print(reversed_words)
  64.将一个字符串中的大写字母转换为小写字母:

s = "Hello World"
lower_s = s.lower()
print(lower_s)
  65.将一个字符串中的小写字母转换为大写字母:

s = "Hello World"
upper_s = s.upper()
print(upper_s)
  66.将一个字符串中的大小写字母互换:

s = "Hello World"
swapcase_s = s.swapcase()
print(swapcase_s)
  67.判断一个字符串是否为回文字符串:

def is_palindrome(s):
s = s.lower()
s = ''.join([c for c in s if c.isalnum()])
return s == s[::-1]

s = "A man, a plan, a canal: Panama"
print(is_palindrome(s))
  68.将一个列表中的元素随机排序:

import random

lst = [1, 2, 3, 4, 5, 6]
random.shuffle(lst)
print(lst)
  69.判断一个列表是否为递增列表:

def is_increasing(lst):
return all(x < y for x, y in zip(lst, lst[1:]))

lst = [1, 2, 3, 4, 5, 6]
print(is_increasing(lst))
  70.判断一个列表是否为递减列表:

def is_decreasing(lst):
return all(x > y for x, y in zip(lst, lst[1:]))

lst = [6, 5, 4, 3, 2, 1]
print(is_decreasing(lst))
  71.将一个列表中的元素去重:

lst = [1, 2, 3, 2, 4, 3, 5, 6, 1]
unique_lst = list(set(lst))
print(unique_lst)
  72.将一个列表中的元素按照出现次数从高到低排序:

from collections import Counter

lst = [1, 2, 3, 2, 4, 3, 5, 6, 1]
cnt = Counter(lst)
sorted_lst = sorted(lst, key=lambda x: cnt[x], reverse=True)
print(sorted_lst)
  73.将一个字符串中的每个单词按照出现次数从高到低排序:

from collections import Counter

s = "This is a test string with some repeated words like test and some"
words = s.split()
cnt = Counter(words)
sorted_words = sorted(words, key=lambda x: cnt[x], reverse=True)
sorted_s = ' '.join(sorted_words)
print(sorted_s)
  74.计算一个数的平方根:

import math

x = 16
sqrt_x = math.sqrt(x)
print(sqrt_x)
  75.计算一个数的立方根:

x = 8
cbrt_x = x**(1/3)
print(cbrt_x)
  76.将一个二进制数转换为十进制数:

binary_num = "1011"
decimal_num = int(binary_num, 2)
print(decimal_num)
  77.将一个八进制数转换为十进制数:

octal_num = "17"
decimal_num =
  78.将一个十六进制数转换为十进制数:

hex_num = "1F"
decimal_num = int(hex_num, 16)
print(decimal_num)
  79.将一个整数转换为二进制数:

x = 11
binary_x = bin(x)[2:]
print(binary_x)
  80.将一个整数转换为八进制数:

x = 31
hex_x = hex(x)[2:]
print(hex_x)
  81.将一个整数转换为十六进制数:

x = 31
hex_x = hex(x)[2:]
print(hex_x)
  82.生成一个随机整数:

import random

random_num = random.randint(1, 10)
print(random_num)
  83.生成一个随机小数:

import random

random_float = random.random()
print(random_float)
  84.生成一个指定范围的随机小数:

import random

random_float = random.uniform(1.0, 10.0)
print(random_float)

  85.从一个列表中随机选择一个元素:

import random

lst = ['apple', 'banana', 'orange']
random_item = random.choice(lst)
print(random_item)
  86.从一个列表中随机选择指定个数的元素:

import random

lst = ['apple', 'banana', 'orange', 'pear', 'grape']
random_items = random.sample(lst, 3)
print(random_items)
  87.计算一个列表中的所有元素之和:

lst = [1, 2, 3, 4, 5, 6]
sum_lst = sum(lst)
print(sum_lst)
  88.计算一个列表中的所有元素的平均值:

lst = [1, 2, 3, 4, 5, 6]
avg_lst = sum(lst) / len(lst)
print(avg_lst)
  89.计算一个列表中的所有元素的中位数:

import statistics

lst = [1, 2, 3, 4, 5, 6]
median_lst = statistics.median(lst)
print(median_lst)
  90.计算一个列表中的所有元素的中位数:

from collections import Counter

lst = [1, 2, 3, 2, 4, 3, 5, 6, 1]
cnt = Counter(lst)
mode_lst = [k for k, v in cnt.items() if v == max(cnt.values())]
print(mode_lst)
  91.计算一个列表中所有元素的标准差:

import statistics

lst = [1, 2, 3, 4, 5, 6]
stdev_lst = statistics.stdev(lst)
print(stdev_lst)
  92.计算一个列表中所有元素的方差:

import statistics

lst = [1, 2, 3, 4, 5, 6]
var_lst = statistics.variance(lst)
print(var_lst)
  93.对一个列表进行排序:

lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_lst = sorted(lst)
print(sorted_lst)
  94.对一个列表进行倒序排序:

lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
reverse_sorted_lst = sorted(lst, reverse=True)
print(reverse_sorted_lst)
  95.将两个列表合并:

lst1 = [1, 2, 3]
lst2 = [4, 5, 6]
merged_lst = lst1 + lst2
print(merged_lst)
  96.将两个列表进行zip操作:

lst1 = [1, 2, 3]
lst2 = [4, 5, 6]
zipped_lst = list(zip(lst1, lst2))
print(zipped_lst)
  97.将一个列表中的元素去重:

lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
distinct_lst = list(set(lst))
print(distinct_lst)
  98.判断一个字符串是否为回文串:

s = "level"
is_palindrome = s == s[::-1]
print(is_palindrome)
  99.将一个字符串中的单词进行反转:

s = "Hello World"
reversed_words = ' '.join(word[::-1] for word in s.split())
print(reversed_words)
  100.将一个字符串中的字符进行计数:

s = "hello world"
char_count = {char: s.count(char) for char in set(s)}
print(char_count)
文章知识点与官方知识档案匹配,可进一步学习相关知识
————————————————
版权声明:本文为CSDN博主「让你五行代码」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zy1992As/article/details/130564521

标签:random,num,编程,列表,lst,初学,words,print,100
From: https://www.cnblogs.com/nxhujiee/p/17501309.html

相关文章

  • 8. Java-AOP 面向切面编程
    专题使用汇总:Java-IDEAJava-Maven,依赖管理,私服https://www.cnblogs.com/chenshaojun2008/p/17493632.htmlJava-IOC&DIJava-Mybatis连接池,动态sqlhttps://www.cnblogs.com/chenshaojun2008/p/17496913.htmlJava-文件上传(本地和OSS)Java-登录校验JWT,过滤器,拦截器使用总结......
  • deepspeed ZeRO-Inference 可在1-GPU上推理~100B的大模型
    原理:......
  • TensorFlow10.2 卷积神经网络-CIFAR100 实战
    ▪Loaddatasets▪BuildNetwork▪Train▪Test这里先是进行卷积然后再进行全连接Loaddatasetsdefpreprocess(x,y):#[0~1]x=tf.cast(x,dtype=tf.float32)/255.y=tf.cast(y,dtype=tf.int32)returnx,y(x,y),(x_test,y_test)=dat......
  • java编程开发之若依vue框架 --- 后台开发
    分页实现前端基于element封装的分页组件 pagination(opensnewwindow)后端基于mybatis的轻量级分页插件pageHelper(opensnewwindow)#前端调用实现1、前端定义分页流程  #后台逻辑实现@PostMapping("/list")//定义/list接口,用于查询出列表@ResponseBody//返......
  • java编程开发之若依vue --- 部署
      部署的大致步骤0.配置环境,jdk下载安装配置环境变量,Mysql下一步就好记住用户名和密码,Redis下载win版本运行即可,Maven下载配置环境变量修改本地库存放位置,Node下一步就好设置下淘宝的镜像源。JDK>=1.8(推荐1.8版本)Mysql>=5.7.0(推荐5.7版本)Redis>=3.0Maven>......
  • MasterCAM 2021中文版数控编程加工基础入门视频教程
    适用对象:MasterCAM2021中文版内容简介:本教程通过12章节课程详细讲解MasterCAM2021软件的基础操作,包括2D/3D绘图、数控编程和曲面加工等,实战性强,纯干货,结合实际操作让用户快速掌握软件,真正实现学以致用。本教程画质虽不是高清的,但不影响观看,同时附安装包,暂无配套素材文件,好的......
  • 2023年最新5000道校招常用编程面试题分享(附详细题解)
    截止到2021年最新,本资源整理了近5000道校招常用面试题,并附带详细的解题思路及代码,包含leetcode,校招笔试题,面试题,算法题,语法题。持续更新中。。。目录内容截图......
  • 不用RLHF,匹敌GPT-4!Meta重磅发布LIMA 65B,1000个样本性能飞升,LeCun转赞
    人人都知,让ChatGPT称霸天下的秘密武器,就是人类反馈强化学习(RLHF)。而现在,MetaAI等机构的爆火研究LIMA直接打破这一规则,直言RLHF并没有那么重要!论文一出,直接在AI圈炸了锅!就连LeCun忍不住发推炫一番:LIMA:LLaMa-65B+1000监督样本=GPT-4/Bard级别的性能。正如标题所称,LIMA是「LessisMo......
  • 【雕爷学编程】Arduino动手做(121)---夏普粉尘传感器模块
    37款传感器与执行器的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是不止这37种的。鉴于本人手头积累了一些传感器和执行器模块,依照实践出真知(一定要动手做)的理念,以学习和交流为目的,这里准备逐一动手尝试系列实验,不管成功(程序走通)与否,都会记录下来—小小的进步或是搞......
  • 历史最全GO编程开发相关资源整理分享
       https://github.com/jobbole/awesome-go-cn本资源整理了Go相关精选资源,内容包括:音频和音乐库、命令行工具、服务端应用、流处理、持续集成、数据库、机器学习、NLP、物联网、中间件、文本处理、安全、机器人技术等。目录内容截图......